Exemplo n.º 1
0
    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)
Exemplo n.º 2
0
def main(pattern='test_*.py'):
    try:
        folder = os.path.dirname(__file__)
    except:
        folder = os.path.dirname(sys.argv[0]) or os.getcwd()
    from reportlab.lib.utils import isSourceDistro
    haveSRC = isSourceDistro()

    def cleanup(folder,patterns=('*.pdf', '*.log','*.svg','runAll.txt', 'test_*.txt')):
        for pat in patterns:
            for filename in GlobDirectoryWalker(folder, pattern=pat):
                try:
                    os.remove(filename)
                except:
                    pass

    # special case for reportlab/test directory - clean up
    # all PDF & log files before starting run.  You don't
    # want this if reusing runAll anywhere else.
    if string.find(folder, 'reportlab' + os.sep + 'test') > -1: cleanup(folder)
    cleanup(outputfile(''))

    NI = []
    testSuite = makeSuite(folder,nonImportable=NI,pattern=pattern+(not haveSRC and 'c' or ''))
    unittest.TextTestRunner().run(testSuite)
    if haveSRC: cleanup(folder,patterns=('*.pyc','*.pyo'))
    if NI:
        sys.stderr.write('\n###################### the following tests could not be imported\n')
        for f,tb in NI:
            print 'file: "%s"\n%s\n' % (f,string.join(tb,''))
    print 'Logs and output files written to folder "%s"' % outputfile('')
Exemplo n.º 3
0
    def test0(self):
        "A basic document drawing some strings"
	
	self.luxi = TTFont("DejaVu", "DejaVuSans.ttf")
        pdfmetrics.registerFont(self.luxi)
        # if they do not have the Japanese font files, go away quietly
        #from reportlab.pdfbase.cidfonts import UnicodeCIDFont, findCMapFile


##        enc = 'ETenms-B5-H'
##        try:
##            findCMapFile(enc)
##        except:
##            #they don't have the font pack, return silently
##            print 'CMap not found'
##            return
        #pdfmetrics.registerFont(UnicodeCIDFont('MSung-Light'))

        c = Canvas(outputfile('test_multibyte_gr.pdf'))
        c.setFont('Helvetica', 24)
        c.drawString(100,700, 'Greek characters Font Support')
        c.setFont('Helvetica', 10)
        c.drawString(100,680, 'Short sample: ')

        hBoxText('Αυτό είναι ενα δοκιμαστικό κείμενο.' , c, 100, 600, 'DejaVu')


##
        c.save()
        if VERBOSE:
            print 'saved '+outputfile('test_multibyte_gr.pdf')
Exemplo n.º 4
0
    def test0(self):
        "A basic document drawing some strings"

        self.luxi = TTFont("DejaVu", "DejaVuSans.ttf")
        pdfmetrics.registerFont(self.luxi)
        # if they do not have the Japanese font files, go away quietly
        # from reportlab.pdfbase.cidfonts import UnicodeCIDFont, findCMapFile

        ##        enc = 'ETenms-B5-H'
        ##        try:
        ##            findCMapFile(enc)
        ##        except:
        ##            #they don't have the font pack, return silently
        ##            print 'CMap not found'
        ##            return
        # pdfmetrics.registerFont(UnicodeCIDFont('MSung-Light'))

        c = Canvas(outputfile("test_multibyte_gr.pdf"))
        c.setFont("Helvetica", 24)
        c.drawString(100, 700, "Greek characters Font Support")
        c.setFont("Helvetica", 10)
        c.drawString(100, 680, "Short sample: ")

        hBoxText("Αυτό είναι ενα δοκιμαστικό κείμενο.", c, 100, 600, "DejaVu")

        ##
        c.save()
        if VERBOSE:
            print "saved " + outputfile("test_multibyte_gr.pdf")
Exemplo n.º 5
0
    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)
Exemplo n.º 6
0
    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):
        "Test if pythonpoint.pdf can be created from pythonpoint.xml."

        join, dirname, isfile, abspath = os.path.join, os.path.dirname, os.path.isfile, os.path.abspath
        rlDir = abspath(dirname(reportlab.__file__))
        from reportlab.tools.pythonpoint import pythonpoint
        from reportlab.lib.utils import isCompactDistro, open_for_read
        ppDir = dirname(pythonpoint.__file__)
        xml = join(ppDir, 'demos', 'pythonpoint.xml')
        datafilename = 'pythonpoint.pdf'
        outDir = outputfile('')
        if isCompactDistro():
            cwd = None
            xml = open_for_read(xml)
        else:
            cwd = os.getcwd()
            os.chdir(join(ppDir, 'demos'))
        pdf = join(outDir, datafilename)
        if isfile(pdf): os.remove(pdf)
        pythonpoint.process(xml,
                            outDir=outDir,
                            verbose=0,
                            datafilename=datafilename)
        if cwd: os.chdir(cwd)
        assert os.path.exists(pdf)
Exemplo n.º 8
0
    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.utils import _RL_DIR
        gif = os.path.join(_RL_DIR,'test','pythonpowered.gif')
        story.append(ParagraphAndImage(Paragraph(text,bt),Image(gif)))
        phrase = 'This should be a paragraph spanning at least three pages. '
        description = phrase * 250
        story.append(Paragraph(description, bt))

        doc = MyDocTemplate(outputfile('test_platypus_paragraphs.pdf'))
        doc.multiBuild(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)
Exemplo n.º 10
0
    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!'
Exemplo n.º 11
0
    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()
Exemplo n.º 12
0
    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)
Exemplo n.º 13
0
    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')
Exemplo n.º 14
0
    def test1(self):
        "Test two strings in group in drawing."

        path = outputfile("test_renderSVG_simple_test1.svg")

        d = Drawing(200, 100)
        g = Group()
        g.add(String(0, 0, "foo"))
        g.add(String(100, 0, "bar"))
        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 = string.strip(textChildren[0].childNodes[0].nodeValue)
        t1 = string.strip(textChildren[1].childNodes[0].nodeValue)

        assert t0 == 'foo'
        assert t1 == 'bar'
Exemplo n.º 15
0
    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')
Exemplo n.º 16
0
    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.utils import _RL_DIR
        gif = os.path.join(_RL_DIR, 'test', '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)
Exemplo n.º 17
0
    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')
Exemplo n.º 18
0
def _test0(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(
            """
        Subsequent pages test pageBreakBefore, frameBreakBefore and
        keepTogether attributes.  Generated at %s.  The number in brackets
        at the end of each paragraph is its position in the story. (%d)"""
            % (time.ctime(time.time()), len(story)),
            bt,
        )
    )

    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))

    doc = MyDocTemplate(outputfile("test_platypus_breaking.pdf"))
    doc.multiBuild(story)
Exemplo n.º 19
0
    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)
Exemplo n.º 20
0
 def test(self):
     c = Canvas(outputfile('test_hello.pdf'))
     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'
     )
     c.setFont('Helvetica-Bold', 36)
     c.drawString(100, 700, 'Hello World')
     c.save()
Exemplo n.º 21
0
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
Exemplo n.º 22
0
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
Exemplo n.º 23
0
    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")
Exemplo n.º 24
0
    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)
Exemplo n.º 25
0
    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')
Exemplo n.º 26
0
 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)
Exemplo n.º 27
0
    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()
Exemplo n.º 28
0
    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 _showDoc(fn,story):
    pageTemplate = PageTemplate('normal', [Frame(72, 440, 170, 284, id='F1'),
                            Frame(326, 440, 170, 284, id='F2'),
                            Frame(72, 72, 170, 284, id='F3'),
                            Frame(326, 72, 170, 284, id='F4'),
                            ], myMainPageFrame)
    doc = BaseDocTemplate(outputfile(fn),
            pageTemplates = pageTemplate,
            showBoundary = 1,
            )
    doc.multiBuild(story)
Exemplo n.º 30
0
    def __del__(self):
        if IMAGES[-1] != None:
            return
        else:
            del IMAGES[-1]

        d = Drawing(A4[0], A4[1])
        for img in IMAGES:
            d.add(img)
        outPath = outputfile("test_graphics_images.pdf")
        renderPDF.drawToFile(d, outPath) #, '')
        assert os.path.exists(outPath) == 1
Exemplo n.º 31
0
    def __del__(self):
        if IMAGES[-1] != None:
            return
        else:
            del IMAGES[-1]

        d = Drawing(A4[0], A4[1])
        for img in IMAGES:
            d.add(img)
        outPath = outputfile("test_graphics_images.pdf")
        renderPDF.drawToFile(d, outPath)  #, '')
        assert os.path.exists(outPath) == 1
Exemplo n.º 32
0
    def test0(self):
        """Test story with TOC and a cascaded header hierarchy.

        The story should contain exactly one table of contents that is
        immediatly followed by a list of of cascaded levels of header
        lines, each nested one level deeper than the previous one.

        Features to be visually confirmed by a human being are:

            1. TOC lines are indented in multiples of 1 cm.
            2. Wrapped TOC lines continue with additional 0.5 cm indentation.
            3. ...
        """

        maxLevels = 12

        # Create styles to be used for document headers
        # on differnet levels.
        headerLevelStyles = []
        for i in range(maxLevels):
            headerLevelStyles.append(makeHeaderStyle(i))

        # Create styles to be used for TOC entry lines
        # for headers on differnet levels.
        tocLevelStyles = []
        d, e = tableofcontents.delta, tableofcontents.epsilon
        for i in range(maxLevels):
            tocLevelStyles.append(makeTocHeaderStyle(i, d, e))

        # Build story.
        story = []
        styleSheet = getSampleStyleSheet()
        bt = styleSheet['BodyText']

        description = '<font color=red>%s</font>' % self.test0.__doc__
        story.append(XPreformatted(description, bt))

        toc = TableOfContents()
        toc.levelStyles = tocLevelStyles
        story.append(toc)

        for i in range(maxLevels):
            story.append(Paragraph('HEADER, LEVEL %d' % i,
                                   headerLevelStyles[i]))
            #now put some body stuff in.
            txt = randomtext.randomText(randomtext.PYTHON, 5)
            para = Paragraph(txt, makeBodyStyle())
            story.append(para)

        path = outputfile('test_platypus_toc.pdf')
        doc = MyDocTemplate(path)
        doc.multiBuild(story)
Exemplo n.º 33
0
    def test0(self):
        """Test story with TOC and a cascaded header hierarchy.

        The story should contain exactly one table of contents that is
        immediatly followed by a list of of cascaded levels of header
        lines, each nested one level deeper than the previous one.

        Features to be visually confirmed by a human being are:

            1. TOC lines are indented in multiples of 1 cm.
            2. Wrapped TOC lines continue with additional 0.5 cm indentation.
            3. ...
        """

        maxLevels = 12

        # Create styles to be used for document headers
        # on differnet levels.
        headerLevelStyles = []
        for i in range(maxLevels):
            headerLevelStyles.append(makeHeaderStyle(i))

        # Create styles to be used for TOC entry lines
        # for headers on differnet levels.
        tocLevelStyles = []
        d, e = tableofcontents.delta, tableofcontents.epsilon
        for i in range(maxLevels):
            tocLevelStyles.append(makeTocHeaderStyle(i, d, e))

        # Build story.
        story = []
        styleSheet = getSampleStyleSheet()
        bt = styleSheet['BodyText']

        description = '<font color=red>%s</font>' % self.test0.__doc__
        story.append(XPreformatted(description, bt))

        toc = TableOfContents()
        toc.levelStyles = tocLevelStyles
        story.append(toc)

        for i in range(maxLevels):
            story.append(Paragraph('HEADER, LEVEL %d' % i,
                                   headerLevelStyles[i]))
            #now put some body stuff in.
            txt = randomtext.randomText(randomtext.PYTHON, 5)
            para = Paragraph(txt, makeBodyStyle())
            story.append(para)

        path = outputfile('test_platypus_toc.pdf')
        doc = MyDocTemplate(path)
        doc.multiBuild(story)
Exemplo n.º 34
0
def _showDoc(fn, story):
    pageTemplate = PageTemplate('normal', [
        Frame(72, 440, 170, 284, id='F1'),
        Frame(326, 440, 170, 284, id='F2'),
        Frame(72, 72, 170, 284, id='F3'),
        Frame(326, 72, 170, 284, id='F4'),
    ], myMainPageFrame)
    doc = BaseDocTemplate(
        outputfile(fn),
        pageTemplates=pageTemplate,
        showBoundary=1,
    )
    doc.multiBuild(story)
Exemplo n.º 35
0
def run():
    doc = SimpleDocTemplate(outputfile('test_platypus_tables.pdf'), pagesize=(8.5*inch, 11*inch), showBoundary=1)
    styles = makeStyles()
    lst = []
    for style in styles:
        t = getTable()
        t.setStyle(style)
##        print '--------------'
##        for rowstyle in t._cellstyles:
##            for s in rowstyle:
##                print s.alignment
        lst.append(t)
        lst.append(Spacer(0,12))
    doc.build(lst)
Exemplo n.º 36
0
    def test1(self):
        "Test if all Python files have a Unix-like first line."

        path = outputfile("test_firstline.log")
        file = open(path, 'w')
        file.write('No Unix-like first line found in the files below.\n\n')

        paths = self.findSuspiciousModules(RL_HOME, 'reportlab')
        paths.sort()

        for p in paths:
            file.write("%s\n" % p)

        file.close()
Exemplo n.º 37
0
    def testTTF(self):
        "Test PDF generation with TrueType fonts"
        pdfmetrics.registerFont(TTFont("TestFont", "luxiserif.ttf"))
        pdfmetrics.registerFont(TTFont("RinaFont", "rina.ttf"))
        _simple_subset_generation('test_pdfbase_ttfonts1.pdf', 1)
        _simple_subset_generation('test_pdfbase_ttfonts3.pdf', 3)
        _simple_subset_generation('test_pdfbase_ttfonts35.pdf', 3, 5)

        # Do it twice with the same font object
        c = Canvas(outputfile('test_pdfbase_ttfontsadditional.pdf'))
        # Draw a table of Unicode characters
        c.setFont('TestFont', 10)
        c.drawString(100, 700, 'Hello, ' + utf8(0xffee))
        c.save()
Exemplo n.º 38
0
    def testTTF(self):
        "Test PDF generation with TrueType fonts"
        pdfmetrics.registerFont(TTFont("TestFont", "luxiserif.ttf"))
        pdfmetrics.registerFont(TTFont("RinaFont", "rina.ttf"))
        _simple_subset_generation('test_pdfbase_ttfonts1.pdf',1)
        _simple_subset_generation('test_pdfbase_ttfonts3.pdf',3)
        _simple_subset_generation('test_pdfbase_ttfonts35.pdf',3,5)

        # Do it twice with the same font object
        c = Canvas(outputfile('test_pdfbase_ttfontsadditional.pdf'))
        # Draw a table of Unicode characters
        c.setFont('TestFont', 10)
        c.drawString(100, 700, 'Hello, ' + utf8(0xffee))
        c.save()
Exemplo n.º 39
0
def _simple_subset_generation(fn,npages,alter=0):
    c = Canvas(outputfile(fn))
    c.setFont('Helvetica', 30)
    c.drawString(100,700, 'Unicode TrueType Font Test %d pages' % npages)
    # Draw a table of Unicode characters
    for p in xrange(npages):
        for fontName in ('TestFont','RinaFont'):
            c.setFont(fontName, 10)
            for i in xrange(32):
                for j in xrange(32):
                    ch = utf8(i * 32 + j+p*alter)
                    c.drawString(80 + j * 13 + int(j / 16) * 4, 600 - i * 13 - int(i / 8) * 8, ch)
        c.showPage()
    c.save()
Exemplo n.º 40
0
    def testUl(self):
        from reportlab.platypus import BaseDocTemplate, PageTemplate, Frame, PageBegin
        from reportlab.lib.units import inch
        class MyDocTemplate(BaseDocTemplate):
            _invalidInitArgs = ('pageTemplates',)

            def __init__(self, filename, **kw):
                self.allowSplitting = 0
                BaseDocTemplate.__init__(self, filename, **kw)
                self.addPageTemplates(
                        [
                        PageTemplate('normal',
                                [Frame(inch, inch, 6.27*inch, 9.69*inch, id='first',topPadding=0,rightPadding=0,leftPadding=0,bottomPadding=0,showBoundary=ShowBoundaryValue(color="red"))],
                                ),
                        ])

        styleSheet = getSampleStyleSheet()
        normal = ParagraphStyle(name='normal',fontName='Times-Roman',fontSize=12,leading=1.2*12,parent=styleSheet['Normal'])
        normal_sp = ParagraphStyle(name='normal_sp',parent=normal,alignment=TA_JUSTIFY,spaceBefore=12)
        normal_just = ParagraphStyle(name='normal_just',parent=normal,alignment=TA_JUSTIFY,spaceAfter=12)
        normal_right = ParagraphStyle(name='normal_right',parent=normal,alignment=TA_RIGHT)
        normal_center = ParagraphStyle(name='normal_center',parent=normal,alignment=TA_CENTER)
        normal_indent = ParagraphStyle(name='normal_indent',firstLineIndent=0.5*inch,parent=normal)
        normal_indent_lv_2 = ParagraphStyle(name='normal_indent_lv_2',firstLineIndent=1.0*inch,parent=normal)
        text0 = '''Furthermore, a subset of English sentences interesting on quite
independent grounds is not quite equivalent to a stipulation to place
the constructions into these various categories. We will bring evidence in favor of
The following thesis:  most of the methodological work in modern
linguistics can be defined in such a way as to impose problems of
phonemic and morphological analysis.'''
        story =[]
        a = story.append
        for mode in (0,1,2,3):
            text = text0
            if mode==1:
                text = text.replace('English sentences','<b>English sentences</b>').replace('quite equivalent','<i>quite equivalent</i>')
                text = text.replace('the methodological work','<b>the methodological work</b>').replace('to impose problems','<i>to impose problems</i>')
                a(Paragraph('Justified paragraph in normal/bold/italic font',style=normal))
            elif mode==2:
                text = '<b>%s</b>' % text
                a(Paragraph('Justified paragraph in bold font',style=normal))
            elif mode==3:
                text = '<i>%s</i>' % text
                a(Paragraph('Justified paragraph in italic font',style=normal))
            else:
                a(Paragraph('Justified paragraph in normal font',style=normal))

            a(Paragraph(text,style=normal_just))
        doc = MyDocTemplate(outputfile('test_platypus_paragraphs_just.pdf'))
        doc.build(story)
Exemplo n.º 41
0
def _simple_subset_generation(fn, npages, alter=0):
    c = Canvas(outputfile(fn))
    c.setFont('Helvetica', 30)
    c.drawString(100, 700, 'Unicode TrueType Font Test %d pages' % npages)
    # Draw a table of Unicode characters
    for p in xrange(npages):
        for fontName in ('TestFont', 'RinaFont'):
            c.setFont(fontName, 10)
            for i in xrange(32):
                for j in xrange(32):
                    ch = utf8(i * 32 + j + p * alter)
                    c.drawString(80 + j * 13 + int(j / 16) * 4,
                                 600 - i * 13 - int(i / 8) * 8, ch)
        c.showPage()
    c.save()
Exemplo n.º 42
0
def _test0(self):
    "This makes one long multi-page paragraph."

    # 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)
Exemplo n.º 43
0
def run():
    doc = SimpleDocTemplate(outputfile('test_platypus_tables.pdf'),
                            pagesize=(8.5 * inch, 11 * inch),
                            showBoundary=1)
    styles = makeStyles()
    lst = []
    for style in styles:
        t = getTable()
        t.setStyle(style)
        ##        print '--------------'
        ##        for rowstyle in t._cellstyles:
        ##            for s in rowstyle:
        ##                print s.alignment
        lst.append(t)
        lst.append(Spacer(0, 12))
    doc.build(lst)
Exemplo n.º 44
0
    def _writeLogFile(self, objType):
        "Write log file for different kind of documentable objects."

        cwd = os.getcwd()
        objects = getModuleObjects(RL_HOME, 'reportlab', objType)
        objects.sort()
        os.chdir(cwd)

        expl = {
            FunctionType: 'functions',
            ClassType: 'classes',
            MethodType: 'methods',
            ModuleType: 'modules'
        }[objType]

        path = outputfile("test_docstrings-%s.log" % expl)
        file = open(path, 'w')
        file.write('No doc strings found for the following %s below.\n\n' %
                   expl)
        p = re.compile('__.+__')

        lines = []
        for name, obj in objects:
            if objType == MethodType:
                n = obj.__name__
                # Skip names with leading and trailing double underscores.
                if p.match(n):
                    continue

            if objType == FunctionType:
                if not obj.__doc__ or len(obj.__doc__) == 0:
                    lines.append("%s.%s\n" % (name, obj.__name__))
            else:
                if not obj.__doc__ or len(obj.__doc__) == 0:
                    if objType == ClassType:
                        lines.append("%s.%s\n" %
                                     (obj.__module__, obj.__name__))
                    elif objType == MethodType:
                        lines.append("%s.%s\n" % (obj.im_class, obj.__name__))
                    else:
                        lines.append("%s\n" % (obj.__name__))

        lines.sort()
        for line in lines:
            file.write(line)

        file.close()
Exemplo n.º 45
0
    def test5(self):
        "List and display all named colors and their gray equivalents."

        canvas = reportlab.pdfgen.canvas.Canvas(
            outputfile('test_lib_colors.pdf'))

        #do all named colors
        framePage(canvas, 'Color Demo - page %d' % canvas.getPageNumber())

        all_colors = reportlab.lib.colors.getAllNamedColors().items()
        all_colors.sort()  # alpha order by name
        canvas.setFont('Times-Roman', 10)
        text = 'This shows all the named colors in the HTML standard (plus their gray and CMYK equivalents).'
        canvas.drawString(72, 740, text)

        canvas.drawString(200, 725, 'Pure RGB')
        canvas.drawString(300, 725, 'B&W Approx')
        canvas.drawString(400, 725, 'CMYK Approx')

        y = 700
        for (name, color) in all_colors:
            canvas.setFillColor(colors.black)
            canvas.drawString(100, y, name)
            canvas.setFillColor(color)
            canvas.rect(200, y - 10, 80, 30, fill=1)
            canvas.setFillColor(colors.color2bw(color))
            canvas.rect(300, y - 10, 80, 30, fill=1)

            c, m, yel, k = colors.rgb2cmyk(color.red, color.green, color.blue)
            CMYK = colors.CMYKColor(c, m, yel, k)
            canvas.setFillColor(CMYK)
            canvas.rect(400, y - 10, 80, 30, fill=1)

            y = y - 40
            if y < 100:
                canvas.showPage()
                framePage(canvas,
                          'Color Demo - page %d' % canvas.getPageNumber())
                canvas.setFont('Times-Roman', 10)
                y = 700
                canvas.drawString(200, 725, 'Pure RGB')
                canvas.drawString(300, 725, 'B&W Approx')
                canvas.drawString(400, 725, 'CMYK Approx')

        canvas.save()
Exemplo n.º 46
0
def makeTestDoc(fontNames):
    filename = outputfile('test_pdfbase_pdfmetrics.pdf')
    c = Canvas(filename)
    c.bookmarkPage('Glyph Width Tests')
    c.showOutline()
    c.addOutlineEntry('Glyph Width Tests', 'Glyph Width Tests', level=0)
    if verbose:
        print   # get it on a different line to the unittest log output.
    for fontName in fontNames:
        if verbose:
            print 'width test for', fontName

        makeWidthTestForAllGlyphs(c, fontName)
        c.showPage()
    c.save()
    if verbose:
        if verbose:
            print 'saved',filename
Exemplo n.º 47
0
def main(pattern='test_*.py'):
    try:
        folder = os.path.dirname(__file__)
        assert folder
    except:
        folder = os.path.dirname(sys.argv[0]) or os.getcwd()
    #allow for Benn's "screwball cygwin distro":
    if folder == '':
        folder = '.'
    from reportlab.lib.utils import isSourceDistro
    haveSRC = isSourceDistro()

    def cleanup(folder,
                patterns=('*.pdf', '*.log', '*.svg', 'runAll.txt',
                          'test_*.txt', '_i_am_actually_a_*.*')):
        if not folder: return
        for pat in patterns:
            for filename in GlobDirectoryWalker(folder, pattern=pat):
                try:
                    os.remove(filename)
                except:
                    pass

    # special case for reportlab/test directory - clean up
    # all PDF & log files before starting run.  You don't
    # want this if reusing runAll anywhere else.
    if string.find(folder, 'reportlab' + os.sep + 'test') > -1: cleanup(folder)
    cleanup(outputfile(''))
    NI = []
    cleanOnly = '--clean' in sys.argv
    if not cleanOnly:
        testSuite = makeSuite(folder,
                              nonImportable=NI,
                              pattern=pattern + (not haveSRC and 'c' or ''))
        unittest.TextTestRunner().run(testSuite)
    if haveSRC: cleanup(folder, patterns=('*.pyc', '*.pyo'))
    if not cleanOnly:
        if NI:
            sys.stderr.write(
                '\n###################### the following tests could not be imported\n'
            )
            for f, tb in NI:
                print 'file: "%s"\n%s\n' % (f, string.join(tb, ''))
        printLocation()
Exemplo n.º 48
0
    def test5(self):
        "List and display all named colors and their gray equivalents."

        canvas = reportlab.pdfgen.canvas.Canvas(outputfile('test_lib_colors.pdf'))

        #do all named colors
        framePage(canvas, 'Color Demo - page %d' % canvas.getPageNumber())

        all_colors = reportlab.lib.colors.getAllNamedColors().items()
        all_colors.sort() # alpha order by name
        canvas.setFont('Times-Roman', 10)
        text = 'This shows all the named colors in the HTML standard (plus their gray and CMYK equivalents).'
        canvas.drawString(72,740, text)

        canvas.drawString(200,725,'Pure RGB')
        canvas.drawString(300,725,'B&W Approx')
        canvas.drawString(400,725,'CMYK Approx')

        y = 700
        for (name, color) in all_colors:
            canvas.setFillColor(colors.black)
            canvas.drawString(100, y, name)
            canvas.setFillColor(color)
            canvas.rect(200, y-10, 80, 30, fill=1)
            canvas.setFillColor(colors.color2bw(color))
            canvas.rect(300, y-10, 80, 30, fill=1)

            c, m, yel, k = colors.rgb2cmyk(color.red, color.green, color.blue)
            CMYK = colors.CMYKColor(c,m,yel,k)
            canvas.setFillColor(CMYK)
            canvas.rect(400, y-10, 80, 30, fill=1)

            y = y - 40
            if y < 100:
                canvas.showPage()
                framePage(canvas, 'Color Demo - page %d' % canvas.getPageNumber())
                canvas.setFont('Times-Roman', 10)
                y = 700
                canvas.drawString(200,725,'Pure RGB')
                canvas.drawString(300,725,'B&W Approx')
                canvas.drawString(400,725,'CMYK Approx')

        canvas.save()
Exemplo n.º 49
0
    def _writeLogFile(self, objType):
        "Write log file for different kind of documentable objects."

        cwd = os.getcwd()
        objects = getModuleObjects(RL_HOME, 'reportlab', objType)
        objects.sort()
        os.chdir(cwd)

        expl = {FunctionType:'functions',
                ClassType:'classes',
                MethodType:'methods',
                ModuleType:'modules'}[objType]

        path = outputfile("test_docstrings-%s.log" % expl)
        file = open(path, 'w')
        file.write('No doc strings found for the following %s below.\n\n' % expl)
        p = re.compile('__.+__')

        lines = []
        for name, obj in objects:
            if objType == MethodType:
                n = obj.__name__
                # Skip names with leading and trailing double underscores.
                if p.match(n):
                    continue

            if objType == FunctionType:
                if not obj.__doc__ or len(obj.__doc__) == 0:
                    lines.append("%s.%s\n" % (name, obj.__name__))
            else:
                if not obj.__doc__ or len(obj.__doc__) == 0:
                    if objType == ClassType:
                        lines.append("%s.%s\n" % (obj.__module__, obj.__name__))
                    elif objType == MethodType:
                        lines.append("%s.%s\n" % (obj.im_class, obj.__name__))
                    else:
                        lines.append("%s\n" % (obj.__name__))

        lines.sort()
        for line in lines:
            file.write(line)

        file.close()
Exemplo n.º 50
0
    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()
Exemplo n.º 51
0
    def _doTest(self, filename, mode, desc):
        "A generic method called by all test real methods."

        filename = outputfile(self.baseFileName + filename)
        c = Canvas(filename)

        # Handle different modes.
        if mode == 'FullScreen':
            c.showFullScreen0()
        elif mode == 'Outline':
            c.bookmarkPage('page1')
            c.addOutlineEntry('Token Outline Entry', 'page1')
            c.showOutline()
        elif mode == 'UseNone':
            pass

        c.setFont('Helvetica', 20)
        c.drawString(100, 700, desc)
        c.save()

        assert fileDoesExist(filename)
Exemplo n.º 52
0
        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 makeSuite():
    return makeSuiteForClasses(PostScriptTestCase)


#noruntests
if __name__ == "__main__":
    unittest.TextTestRunner().run(makeSuite())
    print 'saved '+outputfile('test_pdfgen_postscript_visible.pdf')
    print 'saved '+outputfile('test_pdfgen_postscript_tray.pdf')
    printLocation()
Exemplo n.º 53
0
    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

        ##        enc = 'ETenms-B5-H'
        ##        try:
        ##            findCMapFile(enc)
        ##        except:
        ##            #they don't have the font pack, return silently
        ##            print 'CMap not found'
        ##            return
        pdfmetrics.registerFont(UnicodeCIDFont('MSung-Light'))

        c = Canvas(outputfile('test_multibyte_cht.pdf'))
        c.setFont('Helvetica', 24)
        c.drawString(100, 700, 'Traditional Chinese Font Support')
        c.setFont('Helvetica', 10)
        c.drawString(100, 680,
                     'Short sample: "Taiwan  -  Ang Lee" (movie director)')

        hBoxText(u'\u81fa\u7063  -  \u674e\u5b89', c, 100, 600, 'MSung-Light')

        ##        #hBoxText(message3 + ' MHei-Medium', c, 100, 580, 'MHei-Medium', enc)
        ##
        ##
        ##
        ##        c.setFont('Helvetica', 10)
        ##        tx = c.beginText(100, 500)
        ##        tx.textLines("""
        ##            This test document shows Traditional Chinese output from Reportlab PDF Library.
        ##            You may use one Chinese font, MSung-Light, and a number of different
        ##            encodings.
        ##
        ##            The available encoding names (with comments from the PDF specification) are:
        ##            encodings_cht = [
        ##                'B5pc-H',           # Macintosh, Big Five character set, Big Five encoding,
        ##                                    # Script Manager code 2
        ##                'B5pc-V',           # Vertical version of B5pc-H
        ##                'ETen-B5-H',        # Microsoft Code Page 950 (lfCharSet 0x88), Big Five
        ##                                    # character set with ETen extensions
        ##                'ETen-B5-V',        # Vertical version of ETen-B5-H
        ##                'ETenms-B5-H',      # Microsoft Code Page 950 (lfCharSet 0x88), Big Five
        ##                                    # character set with ETen extensions; this uses proportional
        ##                                    # forms for half-width Latin characters.
        ##                'ETenms-B5-V',      # Vertical version of ETenms-B5-H
        ##                'CNS-EUC-H',        # CNS 11643-1992 character set, EUC-TW encoding
        ##                'CNS-EUC-V',        # Vertical version of CNS-EUC-H
        ##                'UniCNS-UCS2-H',    # Unicode (UCS-2) encoding for the Adobe-CNS1
        ##                                    # character collection
        ##                'UniCNS-UCS2-V'    # Vertical version of UniCNS-UCS2-H.
        ##                ]
        ##
        ##            The next 32 pages show the complete character set available in the encoding
        ##            "ETen-B5-H".  This is Big5 with the ETen extensions.  ETen extensions are the
        ##            most common extension to Big5 and include circled and roman numbers, Japanese
        ##            hiragana and katakana, Cyrillic and fractions in rows C6-C8; and 7 extra characters
        ##            and some line drawing characters in row F9.
        ##            """)
        ##        c.drawText(tx)
        ##        c.setFont('Helvetica',10)
        ##        c.drawCentredString(297, 36, 'Page %d' % c.getPageNumber())
        ##
        ##        c.showPage()
        ##
        ##        # full Big5 code page
        ##        c.setFont('Helvetica', 18)
        ##        c.drawString(72,750, 'Characters available in Big 5')
        ##        y = 500
        ##        for row in range(0xA1,0xFF):
        ##            cc = Big5CodeChart(row, 'MSung-Light',enc)
        ##            cc.charsPerRow = 16
        ##            cc.rows = 10
        ##            cc.codePoints = 160
        ##            cc.drawOn(c, 72, y)
        ##            y = y - cc.height - 25
        ##            if y < 50:
        ##                c.setFont('Helvetica',10)
        ##                c.drawCentredString(297, 36, 'Page %d' % c.getPageNumber())
        ##                c.showPage()
        ##                y = 600
        ##
        ##
        c.save()
        if VERBOSE:
            print 'saved ' + outputfile('test_multibyte_cht.pdf')
Exemplo n.º 54
0
    def test1(self):
        "Test all different box anchors."

        # Build story.
        story = []
        styleSheet = getSampleStyleSheet()
        bt = styleSheet['BodyText']
        h1 = styleSheet['Heading1']
        h2 = styleSheet['Heading2']
        h3 = styleSheet['Heading3']

        story.append(Paragraph('Tests for class <i>Label</i>', h1))
        story.append(Paragraph('Testing box anchors', h2))
        story.append(
            Paragraph(
                """This should display "Hello World" labels
written as black text on a yellow box relative to the origin of the crosshair
axes. The labels indicate their relative position being one of the nine
canonical points of a box: sw, se, nw, ne, w, e, n, s or c (standing for
<i>southwest</i>, <i>southeast</i>... and <i>center</i>).""", bt))
        story.append(Spacer(0, 0.5 * cm))

        # Round 1a
        story.append(Paragraph('Helvetica 10pt', h3))
        story.append(Spacer(0, 0.5 * cm))

        w, h = drawWidth, drawHeight = 400, 100
        protoLabel = self._makeProtoLabel()
        protoLabel.setOrigin(drawWidth / 2, drawHeight / 2)
        protoLabel.textAnchor = 'start'
        protoLabel.fontName = 'Helvetica'
        protoLabel.fontSize = 10
        drawings = self._makeDrawings(protoLabel)
        for d in drawings:
            story.append(d)
            story.append(Spacer(0, 1 * cm))

        story.append(PageBreak())

        # Round 1b
        story.append(Paragraph('Helvetica 18pt', h3))
        story.append(Spacer(0, 0.5 * cm))

        w, h = drawWidth, drawHeight = 400, 100
        protoLabel = self._makeProtoLabel()
        protoLabel.setOrigin(drawWidth / 2, drawHeight / 2)
        protoLabel.textAnchor = 'start'
        protoLabel.fontName = 'Helvetica'
        protoLabel.fontSize = 18
        drawings = self._makeDrawings(protoLabel)
        for d in drawings:
            story.append(d)
            story.append(Spacer(0, 1 * cm))

        story.append(PageBreak())

        # Round 1c
        story.append(Paragraph('Helvetica 18pt, multi-line', h3))
        story.append(Spacer(0, 0.5 * cm))

        w, h = drawWidth, drawHeight = 400, 100
        protoLabel = self._makeProtoLabel()
        protoLabel.setOrigin(drawWidth / 2, drawHeight / 2)
        protoLabel.textAnchor = 'start'
        protoLabel.fontName = 'Helvetica'
        protoLabel.fontSize = 18
        drawings = self._makeDrawings(protoLabel, text='Hello\nWorld!')
        for d in drawings:
            story.append(d)
            story.append(Spacer(0, 1 * cm))

        story.append(PageBreak())

        story.append(Paragraph('Testing text (and box) anchors', h2))
        story.append(
            Paragraph(
                """This should display labels as before,
but now with a fixes size and showing some effect of setting the
textAnchor attribute.""", bt))
        story.append(Spacer(0, 0.5 * cm))

        # Round 2a
        story.append(Paragraph("Helvetica 10pt, textAnchor='start'", h3))
        story.append(Spacer(0, 0.5 * cm))

        w, h = drawWidth, drawHeight = 400, 100
        protoLabel = self._makeProtoLabel()
        protoLabel.setOrigin(drawWidth / 2, drawHeight / 2)
        protoLabel.width = 4 * cm
        protoLabel.height = 1.5 * cm
        protoLabel.textAnchor = 'start'
        protoLabel.fontName = 'Helvetica'
        protoLabel.fontSize = 10
        drawings = self._makeDrawings(protoLabel)
        for d in drawings:
            story.append(d)
            story.append(Spacer(0, 1 * cm))

        story.append(PageBreak())

        # Round 2b
        story.append(Paragraph("Helvetica 10pt, textAnchor='middle'", h3))
        story.append(Spacer(0, 0.5 * cm))

        w, h = drawWidth, drawHeight = 400, 100
        protoLabel = self._makeProtoLabel()
        protoLabel.setOrigin(drawWidth / 2, drawHeight / 2)
        protoLabel.width = 4 * cm
        protoLabel.height = 1.5 * cm
        protoLabel.textAnchor = 'middle'
        protoLabel.fontName = 'Helvetica'
        protoLabel.fontSize = 10
        drawings = self._makeDrawings(protoLabel)
        for d in drawings:
            story.append(d)
            story.append(Spacer(0, 1 * cm))

        story.append(PageBreak())

        # Round 2c
        story.append(Paragraph("Helvetica 10pt, textAnchor='end'", h3))
        story.append(Spacer(0, 0.5 * cm))

        w, h = drawWidth, drawHeight = 400, 100
        protoLabel = self._makeProtoLabel()
        protoLabel.setOrigin(drawWidth / 2, drawHeight / 2)
        protoLabel.width = 4 * cm
        protoLabel.height = 1.5 * cm
        protoLabel.textAnchor = 'end'
        protoLabel.fontName = 'Helvetica'
        protoLabel.fontSize = 10
        drawings = self._makeDrawings(protoLabel)
        for d in drawings:
            story.append(d)
            story.append(Spacer(0, 1 * cm))

        story.append(PageBreak())

        # Round 2d
        story.append(
            Paragraph("Helvetica 10pt, multi-line, textAnchor='start'", h3))
        story.append(Spacer(0, 0.5 * cm))

        w, h = drawWidth, drawHeight = 400, 100
        protoLabel = self._makeProtoLabel()
        protoLabel.setOrigin(drawWidth / 2, drawHeight / 2)
        protoLabel.width = 4 * cm
        protoLabel.height = 1.5 * cm
        protoLabel.textAnchor = 'start'
        protoLabel.fontName = 'Helvetica'
        protoLabel.fontSize = 10
        drawings = self._makeDrawings(protoLabel, text='Hello\nWorld!')
        for d in drawings:
            story.append(d)
            story.append(Spacer(0, 1 * cm))

        story.append(PageBreak())

        path = outputfile('test_charts_textlabels.pdf')
        doc = MyDocTemplate(path)
        doc.multiBuild(story)