def run(filename): c = makeDocument(filename) c.save() source = str(c) open(outputfile("test_pdfgen_pycanvas_out.txt"),"w").write(source) import reportlab.rl_config if reportlab.rl_config.verbose: print source
def func(val): story = [ DocAssert(val,'this should fail'), DocPara('repr(doc._nameSpace)',escape=True), ] doc = SimpleDocTemplate(outputfile('test_doc_programming_asserts.pdf')) doc.build(story)
def ___test2_all(self): """Dumps out ALl GLYPHS in a CID font. Reach for your microscope :-)""" try: from reportlab.pdfbase.cidfonts import CIDFont, findCMapFile findCMapFile('90ms-RKSJ-H') findCMapFile('Identity-H') except: #don't have the font pack. return silently return pdfmetrics.registerFont(CIDFont('HeiseiMin-W3','Identity-H')) c = Canvas('test_japanese_2.pdf') c.setFont('Helvetica', 30) c.drawString(100,800, 'All Glyphs in Adobe-Japan-1-2 collection!') # the two typefaces c.setFont('HeiseiMin-W3-Identity-H', 2) x0 = 50 y0 = 700 dx = 2 dy = 2 for row in range(256): for cell in range(256): s = chr(row) + chr(cell) x = x0 + cell*dx y = y0 - row*dy c.drawString(x,y,s) c.save() if VERBOSE: print('saved '+outputfile('test_multibyte_jpn.pdf'))
def _test0(self): "This makes one long multi-page paragraph." from reportlab.platypus.flowables import DocAssign, DocExec, DocPara, DocIf, DocWhile # Build story. story = [] styleSheet = getSampleStyleSheet() h1 = styleSheet["Heading1"] h1.pageBreakBefore = 1 h1.keepWithNext = 1 h1.outlineLevel = 0 h2 = styleSheet["Heading2"] h2.backColor = colors.cyan h2.keepWithNext = 1 h2.outlineLevel = 1 bt = styleSheet["BodyText"] story.append(Paragraph("""Cross-Referencing Test""", styleSheet["Title"])) story.append( Paragraph( """ Subsequent pages test cross-references: indexes, tables and individual cross references. The number in brackets at the end of each paragraph is its position in the story. (%d)""" % len(story), bt, ) ) story.append(Paragraph("""Table of Contents:""", styleSheet["Title"])) toc = TableOfContents() story.append(toc) chapterNum = 1 for i in range(10): story.append(Paragraph("Chapter %d: Chapters always starts a new page" % chapterNum, h1)) chapterNum = chapterNum + 1 for j in range(3): story.append( Paragraph( "Heading1 paragraphs should always" "have a page break before. Heading 2 on the other hand" "should always have a FRAME break before (%d)" % len(story), bt, ) ) story.append(Paragraph("Heading 2 should always be kept with the next thing (%d)" % len(story), h2)) for j in range(3): story.append(Paragraph(randomText(theme=PYTHON, sentences=2) + " (%d)" % len(story), bt)) story.append(Paragraph("I should never be at the bottom of a frame (%d)" % len(story), h2)) story.append(Paragraph(randomText(theme=PYTHON, sentences=1) + " (%d)" % len(story), bt)) story.append(Paragraph("The Index which goes at the back", h1)) story.append(SimpleIndex()) doc = MyDocTemplate(outputfile("test_platypus_xref.pdf")) doc.multiBuild(story)
def test0(self): "Make a PDFgen document with most graphics features" self.pageCount = 0 makeDocument(outputfile('test_pdfgen_callback.pdf'), pageCallBack=self.callMe) #no point saving it! assert self.pageCount >= 7, 'page count not called!'
def test0(self, isFast=0): """Hello World, on a rectangular background. The rectangle's fillColor is yellow. The string's fillColor is red. """ reportlab.rl_config.shapeChecking = not isFast pdfPath = outputfile('test_graphics_speed_fast.pdf') c = Canvas(pdfPath) t0 = time.time() d = Drawing(400, 200) num = 100 for i in range(num): pc = Pie() pc.x = 150 pc.y = 50 pc.data = [10,20,30,40,50,60] pc.labels = ['a','b','c','d','e','f'] pc.slices.strokeWidth=0.5 pc.slices[3].popout = 20 pc.slices[3].strokeWidth = 2 pc.slices[3].strokeDashArray = [2,2] pc.slices[3].labelRadius = 1.75 pc.slices[3].fontColor = colors.red d.add(pc) d.drawOn(c, 80, 500) t1 = time.time() result = 'drew %d pie charts in %0.4f' % (num, t1 - t0) open(outputfile('test_graphics_speed_test%s.log' % (isFast+1)), 'w').write(result)
def test1(self): c=canvas.Canvas(outputfile('test_pdfgen_obscure.pdf')) c.setViewerPreference('PrintScaling','None') c.setViewerPreference('HideToolbar','true') c.setViewerPreference('HideMenubar','true') c.addPageLabel(0, prefix="Front") c.addPageLabel(1, style='ROMAN_LOWER', start=2) c.addPageLabel(8, style='ARABIC') # (These are fixes for missing pages) c.addPageLabel(11, style='ARABIC',start=6) c.addPageLabel(17, style='ARABIC', start=14) c.addPageLabel(21, style='ARABIC', start=22) #check that duplicate page start will not cause sort error in python 3.x c.addPageLabel(98, style='ROMAN_LOWER', start=99, prefix='r') c.addPageLabel(98, style='ARABIC', start=99, prefix='A') c.addPageLabel(99, style='LETTERS_UPPER') c.addPageLabel(102, prefix="Back",start=1) # Make some (mostly) empty pages for i in range(113): c.drawString(100, 100, 'This is page '+str(i)) c.showPage() # Output the PDF c.save()
def test5(self): '''extreme test inspired by Moritz Pfeiffer https://bitbucket.org/moritzpfeiffer/''' with self.assertRaises(LayoutError): text=""" Clearly, the natural general principle that will subsume this case is not subject to a parasitic gap construction. Presumably, most of the methodological work in modern linguistics can be defined in such a way as to impose the system of base rules exclusive of the lexicon. In the discussion of resumptive pronouns following (81), the fundamental error of regarding functional notions as categorial is to be regarded as a descriptive <span color="red">fact</span>.<br/>So far, the earlier discussion of deviance is not quite equivalent to a parasitic gap construction. To characterize a linguistic level L, a case of semigrammaticalness of a different sort may remedy and, at the same time, eliminate irrelevant intervening contexts in selectional <span color="red">rules</span>.<br/> Summarizing, then, we assume that the descriptive power of the base component can be defined in such a way as to impose nondistinctness in the sense of distinctive feature theory. """ styleSheet = getSampleStyleSheet() story = [] story.append(Paragraph(text, styleSheet['Normal'])) doc = BaseDocTemplate( outputfile('test_platypus_much_too_large.pdf'), pagesize=portrait(A4), pageTemplates=[PageTemplate( 'page_template', [Frame(0, 0, 0, 0, leftPadding=0, rightPadding=0, topPadding=0, bottomPadding=0, id='DUMMY_FRAME')], )], ) doc.build(story)
def test1(self): "This makes several special paragraphs." # Build story. story = [] styleSheet = getSampleStyleSheet() bt = styleSheet["BodyText"] btN = ParagraphStyle("BodyTextTTNone", parent=bt, textTransform="none") btL = ParagraphStyle("BodyTextTTLower", parent=bt, textTransform="lowercase") btU = ParagraphStyle("BodyTextTTUpper", parent=bt, textTransform="uppercase") btC = ParagraphStyle("BodyTextTTCapitalize", parent=bt, textTransform="capitalize") story.append(Paragraph("""This should be ORDINARY text.""", style=bt)) story.append(Paragraph("""This should be ORDINARY text.""", style=btN)) story.append(Paragraph("""This should be LOWER text.""", style=btL)) story.append(Paragraph("""This should be upper text.""", style=btU)) story.append(Paragraph("""This should be cAPITALIZED text.""", style=btC)) story.append(Paragraph("""T<i>hi</i>s shoul<font color="red">d b</font>e <b>ORDINARY</b> text.""", style=bt)) story.append(Paragraph("""T<i>hi</i>s shoul<font color="red">d b</font>e <b>ORDINARY</b> text.""", style=btN)) story.append(Paragraph("""T<i>hi</i>s shoul<font color="red">d b</font>e <b>LOWER</b> text.""", style=btL)) story.append(Paragraph("""T<i>hi</i>s shoul<font color="red">d b</font>e <b>upper</b> text.""", style=btU)) story.append( Paragraph("""T<i>hi</i>s shoul<font color="red">d b</font>e <b>cAPITALIZED</b> text.""", style=btC) ) doc = MyDocTemplate(outputfile("test_platypus_specialparagraphs.pdf")) doc.multiBuild(story)
def textAccum2(): doc = MyDocTemplate(outputfile("test_platypus_accum2.pdf"), pagesize=(8.5 * inch, 11 * inch), showBoundary=1) story = [] story.append(Paragraph("A table with 500 rows", styleSheet["BodyText"])) sty = [ ("GRID", (0, 0), (-1, -1), 1, colors.green), ("BOX", (0, 0), (-1, -1), 2, colors.red), ("FONTNAME", (0, 0), (-1, -1), "Helvetica"), ("FONTSIZE", (0, 0), (-1, -1), 10), ] def myCV(s, fontName="Helvetica", fontSize=10, maxWidth=72): return "\n".join(simpleSplit(s, fontName, fontSize, maxWidth)) data = [ [ PA.onDrawStr(str(i + 1), i + 1), myCV("xx " * (i % 10), maxWidth=100 - 12), myCV("blah " * (i % 40), maxWidth=200 - 12), ] for i in range(500) ] t = LongTable(data, style=sty, colWidths=[50, 100, 200]) story.append(t) doc.build(story)
def test5(self): from reportlab.lib.pagesizes import A4,LETTER canv = canvas.Canvas(outputfile('test_pdfgen_general_page_sizes.pdf'), pagesize=A4, ) canv.setFont('Helvetica',10) S = A4 canv.drawString(0,S[1]-10,'Top Left=(%s,%s) Page Size=%s x %s' % (0,S[1],S[0],S[1])) canv.drawCentredString(0.5*S[0],0.5*S[1],'Center =(%s,%s) Page Size=%s x %s' % (0.5*S[0],0.5*S[1],S[0],S[1])) canv.drawRightString(S[0],2,'Bottom Right=(%s,%s) Page Size=%s x %s' % (S[0],0,S[0],S[1])) canv.showPage() S = LETTER canv.setPageSize(S) canv.drawString(0,S[1]-10,'Top Left=(%s,%s) Page Size=%s x %s' % (0,S[1],S[0],S[1])) canv.drawCentredString(0.5*S[0],0.5*S[1],'Center =(%s,%s) Page Size=%s x %s' % (0.5*S[0],0.5*S[1],S[0],S[1])) canv.drawRightString(S[0],2,'Bottom Right=(%s,%s) Page Size=%s x %s' % (S[0],0,S[0],S[1])) canv.showPage() S = A4 canv.setPageSize(S) canv.setPageRotation(180) canv.drawString(0,S[1]-10,'Top Left=(%s,%s) Page Size=%s x %s' % (0,S[1],S[0],S[1])) canv.drawCentredString(0.5*S[0],0.5*S[1],'Center =(%s,%s) Page Size=%s x %s' % (0.5*S[0],0.5*S[1],S[0],S[1])) canv.drawRightString(S[0],2,'Bottom Right=(%s,%s) Page Size=%s x %s' % (S[0],0,S[0],S[1])) canv.showPage() S = A4[1],A4[0] canv.setPageSize(S) canv.setPageRotation(0) canv.drawString(0,S[1]-30,'Top Left=(%s,%s) Page Size=%s x %s' % (0,S[1],S[0],S[1])) canv.drawCentredString(0.5*S[0],0.5*S[1],'Center =(%s,%s) Page Size=%s x %s' % (0.5*S[0],0.5*S[1],S[0],S[1])) canv.drawRightString(S[0],32,'Bottom Right=(%s,%s) Page Size=%s x %s' % (S[0],0,S[0],S[1])) canv.showPage() canv.save()
def test0(self): "test_platypus_wrapping.WrappingTestCase.test0" # Build story. story = [] styleSheet = getSampleStyleSheet() h1 = styleSheet['Heading1'] h1.spaceBefore = 18 bt = styleSheet['BodyText'] bt.spaceBefore = 6 story.append(Paragraph('Test of paragraph wrapping', h1)) story.append(Spacer(18, 18)) txt = "Normally we wrap paragraphs by looking for spaces between the words. However, with long technical command references and URLs, sometimes this gives ugly results. We attempt to split really long words on certain tokens: slashes, dots etc." story.append(Paragraph(txt, bt)) story.append( Paragraph( 'This is an attempt to break long URLs sanely. Here is a file name: <font face="Courier">C:\\Windows\\System32\\Drivers\\etc\\hosts</font>. ', bt)) story.append( Paragraph( 'This paragraph has a URL (basically, a word) too long to fit on one line, so it just overflows. http://some-really-long-site.somewhere-verbose.com/webthingies/framework/xc4987236hgsdlkafh/foo?format=dingbats&content=rubbish. Ideally, we would wrap it in the middle.', bt)) doc = MyDocTemplate(outputfile('test_platypus_wrapping.pdf')) doc.multiBuild(story)
def test2(self): "Test two strings in transformed group in drawing." path = outputfile("test_renderSVG_simple_test2.svg") d = Drawing(200, 100) g = Group() g.add(String(0, 0, "foo")) g.add(String(100, 0, "bar")) g.scale(1.5, 1.2) g.translate(50, 0) d.add(g) renderSVG.drawToFile(d, path) if not HAVE_XML_PARSER: warnIgnoredRestofTest() return svg = load(path) fg = svg.getElementsByTagName('g')[0] # flipping group dg = fg.getElementsByTagName('g')[0] # diagram group g = dg.getElementsByTagName('g')[0] # custom group textChildren = g.getElementsByTagName('text') # text nodes t0 = textChildren[0].childNodes[0].nodeValue.strip() t1 = textChildren[1].childNodes[0].nodeValue.strip() assert t0 == 'foo' assert t1 == 'bar'
def test0(self): "This makes one long multi-page paragraph." # Build story. story = [] styleSheet = getSampleStyleSheet() bt = styleSheet['BodyText'] text = '''If you imagine that the box of X's tothe left is an image, what I want to be able to do is flow a series of paragraphs around the image so that once the bottom of the image is reached, then text will flow back to the left margin. I know that it would be possible to something like this using tables, but I can't see how to have a generic solution. There are two examples of this in the demonstration section of the reportlab site. If you look at the "minimal" euro python conference brochure, at the end of the timetable section (page 8), there are adverts for "AdSu" and "O'Reilly". I can see how the AdSu one might be done generically, but the O'Reilly, unsure... I guess I'm hoping that I've missed something, and that it's actually easy to do using platypus. ''' from reportlab.platypus.flowables import ParagraphAndImage, Image from reportlab.lib.testutils import testsFolder gif = os.path.join(testsFolder, 'pythonpowered.gif') story.append(ParagraphAndImage(Paragraph(text, bt), Image(gif))) phrase = 'This should be a paragraph spanning at least three pages. ' description = ''.join([('%d: ' % i) + phrase for i in range(250)]) story.append( ParagraphAndImage(Paragraph(description, bt), Image(gif), side='left')) doc = MyDocTemplate(outputfile('test_platypus_paragraphandimage.pdf')) doc.multiBuild(story)
def testTray(self): "Makes a document with tray command - only works on printers supporting it" c = Canvas(outputfile('test_pdfbase_postscript_tray.pdf')) c.setPageCompression(0) c.setFont('Helvetica-Bold', 18) c.drawString(100, 700, 'Hello World. This is page 1 of a 2 page document.') c.drawString(100, 680, 'This also has a tray command ("5 setpapertray").') c.addPostScriptCommand('5 setpapertray') c.showPage() c.setFont('Helvetica-Bold', 16) c.drawString(100, 700, 'Page 2. This should come from a different tray.') c.drawString( 100, 680, 'Also, if you print it using a PS device and Acrobat 4/5,') c.drawString(100, 660, 'or export to Postscript, you should see the word') c.drawString(100, 640, '"Hello PostScript" below. In ordinary Acrobat Reader') c.drawString(100, 620, 'we expect to see nothing.') c.addPostScriptCommand( '/Helvetica findfont 48 scalefont setfont 100 400 moveto (Hello PostScript) show' ) c.save()
def testVisible(self): "Makes a document with extra text - should export and distill" c = Canvas(outputfile('test_pdfbase_postscript_visible.pdf')) c.setPageCompression(0) c.setFont('Helvetica-Bold', 18) c.drawString(100, 700, 'Hello World. This is page 1 of a 2 page document.') c.showPage() c.setFont('Helvetica-Bold', 16) c.drawString(100, 700, 'Page 2. This has some postscript drawing code.') c.drawString(100, 680, 'If you print it using a PS device and Acrobat 4/5,') c.drawString(100, 660, 'or export to Postscript, you should see the word') c.drawString(100, 640, '"Hello PostScript" below. In ordinary Acrobat Reader') c.drawString(100, 620, 'we expect to see nothing.') c.addPostScriptCommand( '/Helvetica findfont 48 scalefont setfont 100 400 moveto (Hello PostScript) show' ) c.drawString(100, 500, 'This document also inserts two postscript') c.drawString(100, 480, ' comments at beginning and endof the stream;') c.drawString(100, 460, 'search files for "%PS_BEFORE" and "%PS_AFTER".') c.addPostScriptCommand('%PS_BEFORE', position=0) c.addPostScriptCommand('%PS_AFTER', position=2) c.save()
def testAAbsoluteAndRelativeFields(self): # the old test1 in pdfform c = canvas.Canvas(outputfile("test_pdfbase_pdfform_formtest.pdf")) # first page c.setFont("Courier", 10) c.drawString(100, 500, "hello world") pdfform.textFieldAbsolute(c, "fieldA", 100, 600, 100, 20, "default value") pdfform.textFieldAbsolute(c, "fieldB", 100, 300, 100, 50, "another default value", multiline=1) pdfform.selectFieldAbsolute(c, "fieldC", "France", ["Canada", "France", "China"], 100, 200, 100, 20) c.rect(100, 600, 100, 20) pdfform.buttonFieldAbsolute(c, "field2", "Yes", 100, 700, width=20, height=20) c.rect(100, 700, 20, 20) pdfform.buttonFieldAbsolute(c, "field3", "Off", 100, 800, width=20, height=20) c.rect(100, 800, 20, 20) # second page c.showPage() c.setFont("Helvetica", 7) c.translate(50, 20) c.drawString(100, 500, "hello world") pdfform.textFieldRelative(c, "fieldA_1", 100, 600, 100, 20, "default value 2") c.setStrokeColorRGB(1, 0, 0) c.setFillColorRGB(0, 1, 0.5) pdfform.textFieldRelative(c, "fieldB_1", 100, 300, 100, 50, "another default value 2", multiline=1) pdfform.selectFieldRelative(c, "fieldC_1", "France 1", ["Canada 0", "France 1", "China 2"], 100, 200, 100, 20) c.rect(100, 600, 100, 20) pdfform.buttonFieldRelative(c, "field2_1", "Yes", 100, 700, width=20, height=20) c.rect(100, 700, 20, 20) pdfform.buttonFieldRelative(c, "field3_1", "Off", 100, 800, width=20, height=20) c.rect(100, 800, 20, 20) c.save()
def run(): doc = AndyTemplate(outputfile('test_platypus_general.pdf'), subject='test0') #doc.setPageCallBack(showProgress) commentary = getCommentary() examples = getExamples() doc.build(commentary, examples)
def tearDown(self): "Hook method for deconstructing the test fixture after testing it." if FINISHED: path=outputfile('test_graphics_charts.pdf') doc = MyDocTemplate(path) doc.build(self.story)
def test1(self): """Ilpo Nyyss\xf6nen posted this broken test""" normalStyle = ParagraphStyle(name="normal") keepStyle = ParagraphStyle(name="keep", keepWithNext=True) content = [Paragraph("line 1", keepStyle), Indenter(left=1 * cm), Paragraph("line 2", normalStyle)] doc = SimpleDocTemplate(outputfile("test_platypus_breaking1.pdf")) doc.build(content)
def testUtf8FileName(self): fn=outputfile('test_pdfbase_utf8_filename') if not isUnicode(fn): fn = fn.decode('utf8') fn += u'_portr\xe4t.pdf' c = Canvas(fn) c.drawString(100,700, u'Filename='+fn) c.save()
def testVisible(self): "Makes a document with extra text - should export and distill" c = Canvas(outputfile('test_pdfbase_postscript_visible.pdf')) c.setPageCompression(0) c.setFont('Helvetica-Bold', 18) c.drawString(100,700, 'Hello World. This is page 1 of a 2 page document.') c.showPage() c.setFont('Helvetica-Bold', 16) c.drawString(100,700, 'Page 2. This has some postscript drawing code.') c.drawString(100,680, 'If you print it using a PS device and Acrobat 4/5,') c.drawString(100,660, 'or export to Postscript, you should see the word') c.drawString(100,640, '"Hello PostScript" below. In ordinary Acrobat Reader') c.drawString(100,620, 'we expect to see nothing.') c.addPostScriptCommand('/Helvetica findfont 48 scalefont setfont 100 400 moveto (Hello PostScript) show') c.drawString(100,500, 'This document also inserts two postscript') c.drawString(100,480, ' comments at beginning and endof the stream;') c.drawString(100,460, 'search files for "%PS_BEFORE" and "%PS_AFTER".') c.addPostScriptCommand('%PS_BEFORE', position=0) c.addPostScriptCommand('%PS_AFTER', position=2) c.save()
def test0(self): "This makes one long multi-page paragraph." # Build story. story = [] styleSheet = getSampleStyleSheet() bt = styleSheet['BodyText'] text = '''If you imagine that the box of X's tothe left is an image, what I want to be able to do is flow a series of paragraphs around the image so that once the bottom of the image is reached, then text will flow back to the left margin. I know that it would be possible to something like this using tables, but I can't see how to have a generic solution. There are two examples of this in the demonstration section of the reportlab site. If you look at the "minimal" euro python conference brochure, at the end of the timetable section (page 8), there are adverts for "AdSu" and "O'Reilly". I can see how the AdSu one might be done generically, but the O'Reilly, unsure... I guess I'm hoping that I've missed something, and that it's actually easy to do using platypus. ''' from reportlab.platypus.flowables import ParagraphAndImage, Image from reportlab.lib.testutils import testsFolder gif = os.path.join(testsFolder,'pythonpowered.gif') story.append(ParagraphAndImage(Paragraph(text,bt),Image(gif))) phrase = 'This should be a paragraph spanning at least three pages. ' description = ''.join([('%d: '%i)+phrase for i in xrange(250)]) story.append(ParagraphAndImage(Paragraph(description, bt),Image(gif),side='left')) doc = MyDocTemplate(outputfile('test_platypus_paragraphandimage.pdf')) doc.multiBuild(story)
def ___test2_all(self): """Dumps out ALl GLYPHS in a CID font. Reach for your microscope :-)""" try: from reportlab.pdfbase.cidfonts import CIDFont, findCMapFile findCMapFile('90ms-RKSJ-H') findCMapFile('Identity-H') except: #don't have the font pack. return silently return pdfmetrics.registerFont(CIDFont('HeiseiMin-W3','Identity-H')) c = Canvas('test_japanese_2.pdf') c.setFont('Helvetica', 30) c.drawString(100,800, 'All Glyphs in Adobe-Japan-1-2 collection!') # the two typefaces c.setFont('HeiseiMin-W3-Identity-H', 2) x0 = 50 y0 = 700 dx = 2 dy = 2 for row in range(256): for cell in range(256): s = chr(row) + chr(cell) x = x0 + cell*dx y = y0 - row*dy c.drawString(x,y,s) c.save() if VERBOSE: print 'saved '+outputfile('test_multibyte_jpn.pdf')
def test0(self): "A basic document drawing some strings" # if they do not have the Japanese font files, go away quietly from reportlab.pdfbase.cidfonts import UnicodeCIDFont, findCMapFile pdfmetrics.registerFont(UnicodeCIDFont('STSong-Light')) c = Canvas(outputfile('test_multibyte_chs.pdf')) c.setFont('Helvetica', 30) c.drawString(100,700, 'Simplified Chinese Font Support') c.setFont('Helvetica', 10) c.drawString(100,680, 'Short sample: "China - Zhang Ziyi" (famous actress)') # the two typefaces hBoxText('\u4e2d\u56fd - \u7ae0\u5b50\u6021', c, 100, 660, 'STSong-Light', ) c.setFont('Helvetica',10) c.drawCentredString(297, 36, 'Page %d' % c.getPageNumber()) c.showPage() ## # full kuten chart in EUC ## c.setFont('Helvetica', 18) ## c.drawString(72,750, 'Characters available in GB 2312-80, EUC encoding') ## y = 600 ## enc = 'GB_EUC_H' ## for row in range(1, 95): ## KutenRowCodeChart(row, 'STSong-Light',enc).drawOn(c, 72, y) ## y = y - 125 ## if y < 50: ## c.setFont('Helvetica',10) ## c.drawCentredString(297, 36, 'Page %d' % c.getPageNumber()) ## c.showPage() ## y = 700 ## c.save() if VERBOSE: print('saved '+outputfile('test_multibyte_chs.pdf'))
def test0(self): "A basic document drawing some strings" # if they do not have the Japanese font files, go away quietly from reportlab.pdfbase.cidfonts import UnicodeCIDFont, findCMapFile pdfmetrics.registerFont(UnicodeCIDFont('STSong-Light')) c = Canvas(outputfile('test_multibyte_chs.pdf')) c.setFont('Helvetica', 30) c.drawString(100, 700, 'Simplified Chinese Font Support') c.setFont('Helvetica', 10) c.drawString(100, 680, 'Short sample: "China - Zhang Ziyi" (famous actress)') # the two typefaces hBoxText( u'\u4e2d\u56fd - \u7ae0\u5b50\u6021', c, 100, 660, 'STSong-Light', ) c.setFont('Helvetica', 10) c.drawCentredString(297, 36, 'Page %d' % c.getPageNumber()) c.showPage() ## # full kuten chart in EUC ## c.setFont('Helvetica', 18) ## c.drawString(72,750, 'Characters available in GB 2312-80, EUC encoding') ## y = 600 ## enc = 'GB_EUC_H' ## for row in range(1, 95): ## KutenRowCodeChart(row, 'STSong-Light',enc).drawOn(c, 72, y) ## y = y - 125 ## if y < 50: ## c.setFont('Helvetica',10) ## c.drawCentredString(297, 36, 'Page %d' % c.getPageNumber()) ## c.showPage() ## y = 700 ## c.save() if VERBOSE: print('saved ' + outputfile('test_multibyte_chs.pdf'))
def run_samples(S, kind='axes'): outDir = outputfile('charts-out') for f in S: if f.startswith('sample'): d = S[f]() d.save(formats=['pdf', 'gif', 'svg'], outDir=outDir, fnRoot='test_graphics_charts_%s_%s' % (kind, f))
def test0(self): "Test two strings in drawing." path = outputfile("axestest0.svg") from reportlab.graphics.charts.axes import XCategoryAxis d = XCategoryAxis().demo() renderSVG.drawToFile(d, path)
def test0(self): "Test two strings in drawing." path = outputfile("axestest0.ps") from reportlab.graphics.charts.axes import XCategoryAxis d = XCategoryAxis().demo() renderPS.drawToFile(d, path)
def func(val): story = [ DocAssert(val, 'this should fail'), DocPara('repr(doc._nameSpace)', escape=True), ] doc = SimpleDocTemplate( outputfile('test_doc_programming_asserts.pdf')) doc.build(story)
def testOSFile(self): import io fd = os.open(outputfile('test_pdfgen_osfile.pdf'),getattr(os,'O_BINARY',0)|os.O_WRONLY|os.O_CREAT) fn = io.FileIO(fd,'wb') c = canvas.Canvas(fn) c.drawString(100, 700, 'Hello World my filedescriptor is %d!' % fd) c.showPage() c.save()
def test_doctemplate(self): "Test generating an encrypted pdf by setting a user password on the DocTemplate." header = ParagraphStyle(name='Heading', fontSize=36) story = [Paragraph("Top secret", header)] fname = outputfile('test_encrypt_doctemplate.pdf') doc = SimpleDocTemplate(fname, encrypt='User') doc.build(story) parsedoc(fname)
def run(filename): c = makeDocument(filename) c.save() source = str(c) open(outputfile("test_pdfgen_pycanvas_out.txt"), "w").write(source) import reportlab.rl_config if reportlab.rl_config.verbose: print source
def run_samples(L): outDir = outputfile('charts-out') for k, f, kind in L: d = f() if not isinstance(d, Drawing): continue d.save(formats=['pdf', 'gif', 'svg', 'ps', 'py'] + eps(), outDir=outDir, fnRoot='test_graphics_charts_%s_%s' % (kind, k))
def testIt(self): "This makes one long multi-page paragraph." # Build story. story = [] styleSheet = getSampleStyleSheet() h1 = styleSheet['Heading1'] h1.pageBreakBefore = 1 h1.keepWithNext = 1 h2 = styleSheet['Heading2'] h2.frameBreakBefore = 1 h2.keepWithNext = 1 h3 = styleSheet['Heading3'] h3.backColor = colors.cyan h3.keepWithNext = 1 bt = styleSheet['BodyText'] story.append(Paragraph(""" This tests ability to alternate left and right templates. We start on a plain one. The next page should display a left-side template, with a big inner margin and staple-like holes on the right.""",style=bt)) story.append(NextPageTemplate(['left','right'])) story.append(Paragraph(""" One can specify a list of templates instead of a single one in order to sequence through them.""",style=bt)) def doSome(): for i in range(10): story.append(Paragraph('Heading 1 always starts a new page (%d)' % len(story), h1)) for j in range(3): story.append(Paragraph('Heading1 paragraphs should always' 'have a page break before. Heading 2 on the other hand' 'should always have a FRAME break before (%d)' % len(story), bt)) story.append(Paragraph('Heading 2 always starts a new frame (%d)' % len(story), h2)) story.append(Paragraph('Heading1 paragraphs should always' 'have a page break before. Heading 2 on the other hand' 'should always have a FRAME break before (%d)' % len(story), bt)) for j in range(3): story.append(Paragraph(randomText(theme=PYTHON, sentences=2)+' (%d)' % len(story), bt)) story.append(Paragraph('I should never be at the bottom of a frame (%d)' % len(story), h3)) story.append(Paragraph(randomText(theme=PYTHON, sentences=1)+' (%d)' % len(story), bt)) doSome() story.append(NextPageTemplate('plain')) story.append(Paragraph('Back to plain old page template',h1)) story.append(Paragraph('Back to plain old formatting', bt)) story.append(Paragraph("""use a template name of * to indicate where the iteration should restart""",style=bt)) story.append(NextPageTemplate(['left','*','right'])) doSome() #doc = MyDocTemplate(outputfile('test_platypus_leftright.pdf')) doc = MyDocTemplate(outputfile('test_platypus_leftright.pdf')) doc.multiBuild(story)
def test_canvas(self): "Test generating an encrypted pdf by setting a user password on the Canvas." fname = outputfile('test_encrypt_canvas.pdf') c = Canvas(fname, encrypt='User') c.setAuthor('Anonymous') c.setFont('Helvetica-Bold', 36) c.drawString(100, 700, 'Top secret') c.save() parsedoc(fname)
def testUmlautLinks(self): bt = getSampleStyleSheet()['BodyText'] story = [ Paragraph( u'Es folgt ein Link zu http://dömäin.example.com: <a href="http://dömäin.example.com">Link</a>', bt) ] doc = MyDocTemplate(outputfile('test_platypus_umlautlinks.pdf')) doc.multiBuild(story)
def testMultipleSavesOk(self): c = canvas.Canvas(outputfile('test_pdfgen_savetwice.pdf')) c.drawString(100, 700, 'Hello. This was saved twice') c.showPage() # Output the PDF stuff = c.getpdfdata() #multiple calls to save / getpdfdata used to cause errors stuff = c.getpdfdata()
def test(self): c = Canvas(outputfile('test_hello.pdf')) #Author with Japanese text c.setAuthor('\xe3\x83\x9b\xe3\x83\x86\xe3\x83\xab\xe3\x83\xbbe\xe3\x83\x91\xe3\x83\xb3\xe3\x83\x95\xe3\x83\xac\xe3\x83\x83\xe3\x83\x88') #Subject with Arabic magic c.setSubject(u'\u0643\u0644\u0627\u0645 \u0639\u0631\u0628\u064a') c.setFont('Helvetica-Bold', 36) c.drawString(100,700, 'Hello World') c.save()
def testMultipleSavesOk(self): c=canvas.Canvas(outputfile('test_pdfgen_savetwice.pdf')) c.drawString(100, 700, 'Hello. This was saved twice') c.showPage() # Output the PDF stuff = c.getpdfdata() #multiple calls to save / getpdfdata used to cause errors stuff = c.getpdfdata()
def test0(self): "Test two strings in drawing." path = outputfile("test_renderPS_simple_test0.ps") d = Drawing(200, 100) d.add(String(0, 0, "foo")) d.add(String(100, 0, "bar")) renderPS.drawToFile(d, path)
def test2(self): "This is a profiled version of test1()." try: import profile except ImportError: return fileName = outputfile('test_graphics_speed_profile.log') # This runs ok, when only this test script is executed, # but fails, when imported from runAll.py... profile.run("t = GraphicsSpeedTestCase('test2')", fileName)
def test4(self): "Test character encoding." path = outputfile("test_renderPS_simple_test4.ps") specialChar = u'\u2019' d = Drawing(200, 100) d.add(String(0, 0, "foo"+specialChar)) d.add(String(100, 0, "bar")) renderPS.drawToFile(d, path)
def testBoxes(self): c = canvas.Canvas(outputfile('test_pdfgen_boxes.pdf')) w, h = c._pagesize c.setCropBox((0.1, 0.1, w - 0.2, h - 0.2)) c.setBleedBox((-0.1, -0.1, w + 0.2, h + 0.2)) c.setArtBox((0.2, 0.2, w - 0.4, h - 0.4)) c.setTrimBox((0.01, 0.01, w - 0.02, h - 0.02)) c.drawString(100, 700, 'Hello World!') c.showPage() c.save()
def test3(self): from reportlab.lib.units import cm from reportlab.lib import colors width=300 height=60 #Create fairly simple drawing object, drawing=Drawing(width, height) p=ArcPath(strokeColor=colors.darkgreen, fillColor=colors.green, hrefURL="http://en.wikipedia.org/wiki/Vector_path", hrefTitle="This big letter C is actually a closed vector path.", strokewidth=0) p.addArc(1*cm, 1*cm, 0.8*cm, 20, 340, moveTo=True) p.addArc(1*cm, 1*cm, 0.9*cm, 20, 340, reverse=True) p.closePath() drawing.add(p) drawing.add(Rect(2.25*cm, 0.1*cm, 1.5*cm, 0.8*cm, rx=0.25*cm, ry=0.25*cm, hrefURL="http://en.wikipedia.org/wiki/Rounded_rectangle", hrefTitle="Rounded Rectangle", strokeColor=colors.red, fillColor=colors.yellow)) drawing.add(String(1*cm, 1*cm, "Hello World!", hrefURL="http://en.wikipedia.org/wiki/Hello_world", hrefTitle="Why 'Hello World'?", fillColor=colors.darkgreen)) drawing.add(Rect(4.5*cm, 0.5*cm, 5*cm, 1*cm, hrefURL="http://en.wikipedia.org/wiki/Rectangle", hrefTitle="Wikipedia page on rectangles", strokeColor=colors.blue, fillColor=colors.red)) drawing.add(Ellipse(7*cm, 1*cm, 2*cm, 0.95*cm, hrefURL="http://en.wikipedia.org/wiki/Ellipse", strokeColor=colors.black, fillColor=colors.yellow)) drawing.add(Circle(7*cm, 1*cm, 0.9*cm, hrefURL="http://en.wikipedia.org/wiki/Circle", strokeColor=colors.black, fillColor=colors.brown)) drawing.add(Ellipse(7*cm, 1*cm, 0.5*cm, 0.9*cm, hrefTitle="Tooltip with no link?", strokeColor=colors.black, fillColor=colors.black)) drawing.add(Polygon([4.5*cm, 1.25*cm, 5*cm, 0.1*cm, 4*cm, 0.1*cm], hrefURL="http://en.wikipedia.org/wiki/Polygon", hrefTitle="This triangle is a simple polygon.", strokeColor=colors.darkgreen, fillColor=colors.green)) renderPS.drawToFile(drawing, outputfile("test_renderPS_simple_test3.ps"))
def _test0(self): "Perform original test function." pdfPath = outputfile('test_charts_textlabels.pdf') c = Canvas(pdfPath) label = Label() demoLabel = label.demo() demoLabel.drawOn(c, 0, 0) c.save()
def test0(self): "This makes one long multi-page paragraph." # Build story. story = [] styleSheet = getSampleStyleSheet() h1 = styleSheet['Heading1'] h1.spaceBefore = 18 bt = styleSheet['BodyText'] bt.spaceBefore = 6 story.append(Paragraph('Test of paragraph wrapping',h1)) story.append(Spacer(18,18)) txt = "Normally we wrap paragraphs by looking for spaces between the words. However, with long technical command references and URLs, sometimes this gives ugly results. We attempt to split really long words on certain tokens: slashes, dots etc." story.append(Paragraph(txt,bt)) story.append(Paragraph('This is an attempt to break long URLs sanely. Here is a file name: <font face="Courier">C:\\Windows\\System32\\Drivers\\etc\\hosts</font>. ', bt)) story.append(Paragraph('This paragraph has a URL (basically, a word) too long to fit on one line, so it just overflows. http://some-really-long-site.somewhere-verbose.com/webthingies/framework/xc4987236hgsdlkafh/foo?format=dingbats&content=rubbish. Ideally, we would wrap it in the middle.', bt)) doc = MyDocTemplate(outputfile('test_platypus_wrapping.pdf')) doc.multiBuild(story)
def test5(self): from reportlab.lib.pagesizes import A4, LETTER canv = canvas.Canvas(outputfile("test_pdfgen_general_page_sizes.pdf"), pagesize=A4) canv.setFont("Helvetica", 10) S = A4 canv.drawString(0, S[1] - 10, "Top Left=(%s,%s) Page Size=%s x %s" % (0, S[1], S[0], S[1])) canv.drawCentredString( 0.5 * S[0], 0.5 * S[1], "Center =(%s,%s) Page Size=%s x %s" % (0.5 * S[0], 0.5 * S[1], S[0], S[1]) ) canv.drawRightString(S[0], 2, "Bottom Right=(%s,%s) Page Size=%s x %s" % (S[0], 0, S[0], S[1])) canv.showPage() S = LETTER canv.setPageSize(S) canv.drawString(0, S[1] - 10, "Top Left=(%s,%s) Page Size=%s x %s" % (0, S[1], S[0], S[1])) canv.drawCentredString( 0.5 * S[0], 0.5 * S[1], "Center =(%s,%s) Page Size=%s x %s" % (0.5 * S[0], 0.5 * S[1], S[0], S[1]) ) canv.drawRightString(S[0], 2, "Bottom Right=(%s,%s) Page Size=%s x %s" % (S[0], 0, S[0], S[1])) canv.showPage() S = A4 canv.setPageSize(S) canv.setPageRotation(180) canv.drawString(0, S[1] - 10, "Top Left=(%s,%s) Page Size=%s x %s" % (0, S[1], S[0], S[1])) canv.drawCentredString( 0.5 * S[0], 0.5 * S[1], "Center =(%s,%s) Page Size=%s x %s" % (0.5 * S[0], 0.5 * S[1], S[0], S[1]) ) canv.drawRightString(S[0], 2, "Bottom Right=(%s,%s) Page Size=%s x %s" % (S[0], 0, S[0], S[1])) canv.showPage() canv.save()
def setUp(self): SecureTestCase.setUp(self) try: fn = __file__ except: fn = sys.argv[0] self.output = open(outputfile(os.path.splitext(os.path.basename(fn))[0]+'.txt'),'w')
def func(val): story = [ DocAssert(val,'this should fail'), DocPara("'val=%r'" % val), DocPara('"{"+", ".join(("%s=%s" % (_k,(_v.__class__.__name__ if "<" in repr(_v) else repr(_v)[1:] if repr(_v) and repr(_v)[0] in "ub" else repr(_v))) for _k,_v in sorted(doc._nameSpace.items()) if _k not in ("_k","_v")))+"}"',escape=True), ] doc = SimpleDocTemplate(outputfile('test_doc_programming_asserts.pdf')) doc.build(story)