Example #1
0
def computeO(userPassword, ownerPassword, revision):
    from reportlab.lib.arciv import ArcIV
    #print 'digest of hello is %s' % md5('hello').digest()
    assert revision in (2, 3), 'Unknown algorithm revision %s' % revision
    if not ownerPassword:
        ownerPassword = userPassword

    ownerPad = asBytes(ownerPassword) + PadString
    ownerPad = ownerPad[0:32]

    password = asBytes(userPassword) + PadString
    userPad = password[:32]

    digest = md5(ownerPad).digest()
    if DEBUG:
        print(
            'PadString=%s\nownerPad=%s\npassword=%s\nuserPad=%s\ndigest=%s\nrevision=%s'
            % (ascii(PadString), ascii(ownerPad), ascii(password),
               ascii(userPad), ascii(digest), revision))
    if revision == 2:
        O = ArcIV(digest[:5]).encode(userPad)
    elif revision == 3:
        for i in range(50):
            digest = md5(digest).digest()
        digest = digest[:16]
        O = userPad
        for i in range(20):
            thisKey = xorKey(i, digest)
            O = ArcIV(thisKey).encode(O)
    if DEBUG:
        print('computeO(%s,%s,%s)==>%s' % tuple([
            hexText(str(x)) for x in (userPassword, ownerPassword, revision, O)
        ]))
    return O
Example #2
0
 def normalize(self, x):
     if x in (0, 1): return x
     try:
         S = x.upper()
     except:
         raise ValueError('Must be boolean not %s' % ascii(s))
     if S in ('YES', 'TRUE'): return True
     if S in ('NO', 'FALSE', None): return False
     raise ValueError('Must be boolean not %s' % ascii(s))
Example #3
0
 def sascii(x):
     s = ascii(x)
     if s.startswith('u') or s.startswith('b'): s = s[1:]
     if s.startswith("'") or s.startswith('"'): s = s[1:]
     if s.startswith('\\u') or s.startswith('\\x'): s = s[1:]
     if s.endswith("'") or s.endswith('"'): s = s[:-1]
     return s
Example #4
0
def test(outDir='epsout', shout=False):
    from reportlab.graphics import testshapes
    from reportlab.rl_config import verbose
    OLDFONTS = testshapes._FONTS[:]
    testshapes._FONTS[:] = [
        'Times-Roman', 'Times-Bold', 'Times-Italic', 'Times-BoldItalic',
        'Courier'
    ]
    try:
        import os
        # save all drawings and their doc strings from the test file
        if not os.path.isdir(outDir):
            os.mkdir(outDir)
        #grab all drawings from the test module
        drawings = []

        for funcname in dir(testshapes):
            if funcname[0:10] == 'getDrawing':
                drawing = eval('testshapes.' + funcname + '()')  #execute it
                docstring = eval('testshapes.' + funcname + '.__doc__')
                drawings.append((drawing, docstring))

        i = 0
        for (d, docstring) in drawings:
            filename = outDir + os.sep + 'renderPS_%d.eps' % i
            drawToFile(d, filename)
            if shout or verbose > 2:
                print('renderPS test saved %s' % ascii(filename))
            i += 1
    finally:
        testshapes._FONTS[:] = OLDFONTS
Example #5
0
 def namedsetitem(self, name, item, value):
     if self.name == name:
         self[item] = value
     else:
         try:
             self.parent.namedsetitem(name, item, value)
         except:
             raise ValueError("can't match name %s" % ascii(name))
Example #6
0
 def _escape(self, s):
     '''
     return a copy of string s with special characters in postscript strings
     escaped with backslashes.
     '''
     try:
         return _escape_and_limit(s)
     except:
         raise ValueError("cannot escape %s" % ascii(s))
Example #7
0
 def processTuple(self, e, overrides, containerdict=None):
     tagname = e[0]
     nodemappers = self.nodemappers
     if overrides:
         nodemappers = nodemappers.copy()
         # do overrides
         nodemappers.update(overrides)
     defaultmapper = nodemappers.get(None, None)
     processor = nodemappers.get(tagname, defaultmapper)
     if processor is None:
         raise NameError("no processor for %s" % ascii(tagname))
     e2 = processor.translate(e, self, overrides, containerdict)
     return e2
Example #8
0
def findFontAndRegister(fontName):
    '''search for and register a font given its name'''
    fontName = str(fontName)
    assert type(fontName) is str, 'fontName=%s is not required type str' % ascii(fontName)
    #it might have a font-specific encoding e.g. Symbol
    # or Dingbats.  If not, take the default.
    face = getTypeFace(fontName)
    if face.requiredEncoding:
        font = Font(fontName, fontName, face.requiredEncoding)
    else:
        font = Font(fontName, fontName, defaultEncoding)
    registerFont(font)
    return font
Example #9
0
def test(outDir='pdfout', shout=False):
    from reportlab.graphics.shapes import _baseGFontName, _baseGFontNameBI
    from reportlab.rl_config import verbose
    import os
    if not os.path.isdir(outDir):
        os.mkdir(outDir)
    fn = os.path.join(outDir, 'renderPDF.pdf')
    c = Canvas(fn)
    c.setFont(_baseGFontName, 36)
    c.drawString(80, 750, 'Graphics Test')

    # print all drawings and their doc strings from the test
    # file

    #grab all drawings from the test module
    from reportlab.graphics import testshapes
    drawings = []
    for funcname in dir(testshapes):
        if funcname[0:10] == 'getDrawing':
            func = getattr(testshapes, funcname)
            drawing = func()  #execute it
            docstring = getattr(func, '__doc__', '')
            drawings.append((drawing, docstring))

    #print in a loop, with their doc strings
    c.setFont(_baseGFontName, 12)
    y = 740
    i = 1
    for (drawing, docstring) in drawings:
        assert (docstring is not None), "Drawing %d has no docstring!" % i
        if y < 300:  #allows 5-6 lines of text
            c.showPage()
            y = 740
        # draw a title
        y = y - 30
        c.setFont(_baseGFontNameBI, 12)
        c.drawString(80, y, 'Drawing %d' % i)
        c.setFont(_baseGFontName, 12)
        y = y - 14
        textObj = c.beginText(80, y)
        textObj.textLines(docstring)
        c.drawText(textObj)
        y = textObj.getY()
        y = y - drawing.height
        draw(drawing, c, 80, y)
        i = i + 1
    if y != 740: c.showPage()

    c.save()
    if shout or verbose > 2:
        print('saved %s' % ascii(fn))
Example #10
0
    def test4(self):
        "Test character encoding."

        path = outputfile("test_renderSVG_simple_test4.svg")
        specialChar = u'\u2019'

        d = Drawing(200, 100)
        d.add(String(0, 0, "foo"+specialChar))
        d.add(String(100, 0, "bar"))
        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
        textChildren = dg.getElementsByTagName('text')  # text nodes
        t0 = textChildren[0].childNodes[0].nodeValue.strip()
        t1 = textChildren[1].childNodes[0].nodeValue.strip()
        assert t0 == 'foo'+specialChar, "%s should equal %s" % (ascii(t0),ascii('foo'+specialChar))
        assert t1 == 'bar'
Example #11
0
 def testFpStr(self):
     # should give siz decimal places if less than 1.
     # if more, give up to seven sig figs
     for func, kind in getFuncs('fp_str'):
         assert func(
             1, 2, 3
         ) == '1 2 3', "%s fp_str(1,2,3)=='1 2 3' fails with value %s!" % (
             kind, ascii(func(1, 2, 3)))
         assert func(
             1) == '1', "%s fp_str(1) == '1' fails with value %s!" % (
                 kind, ascii(func(1)))
         assert func(
             595.275574
         ) == '595.2756', "%s fp_str(595.275574) == '595.2756' fails with value %s!" % (
             kind, ascii(func(595.25574)))
         assert func(
             59.5275574
         ) == '59.52756', "%s fp_str(59.5275574) == '59.52756' fails with value %s!" % (
             kind, ascii(func(59.525574)))
         assert func(
             5.95275574
         ) == '5.952756', "%s fp_str(5.95275574) == '5.952756' fails with value %s!" % (
             kind, ascii(func(5.9525574)))
Example #12
0
def test(outDir='pdfout',shout=False):
    from reportlab.graphics.shapes import _baseGFontName, _baseGFontNameBI
    from reportlab.rl_config import verbose
    import os
    if not os.path.isdir(outDir):
        os.mkdir(outDir)
    fn = os.path.join(outDir,'renderPDF.pdf')
    c = Canvas(fn)
    c.setFont(_baseGFontName, 36)
    c.drawString(80, 750, 'Graphics Test')

    # print all drawings and their doc strings from the test
    # file

    #grab all drawings from the test module
    from reportlab.graphics import testshapes
    drawings = []
    for funcname in dir(testshapes):
        if funcname[0:10] == 'getDrawing':
            drawing = eval('testshapes.' + funcname + '()')  #execute it
            docstring = eval('testshapes.' + funcname + '.__doc__')
            drawings.append((drawing, docstring))

    #print in a loop, with their doc strings
    c.setFont(_baseGFontName, 12)
    y = 740
    i = 1
    for (drawing, docstring) in drawings:
        assert (docstring is not None), "Drawing %d has no docstring!" % i
        if y < 300:  #allows 5-6 lines of text
            c.showPage()
            y = 740
        # draw a title
        y = y - 30
        c.setFont(_baseGFontNameBI,12)
        c.drawString(80, y, 'Drawing %d' % i)
        c.setFont(_baseGFontName,12)
        y = y - 14
        textObj = c.beginText(80, y)
        textObj.textLines(docstring)
        c.drawText(textObj)
        y = textObj.getY()
        y = y - drawing.height
        draw(drawing, c, 80, y)
        i = i + 1
    if y!=740: c.showPage()

    c.save()
    if shout or verbose>2:
        print('saved %s' % ascii(fn))
Example #13
0
    def test4(self):
        "Test character encoding."

        path = outputfile("test_renderSVG_simple_test4.svg")
        specialChar = u'\u2019'

        d = Drawing(200, 100)
        d.add(String(0, 0, "foo" + specialChar))
        d.add(String(100, 0, "bar"))
        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
        textChildren = dg.getElementsByTagName('text')  # text nodes
        t0 = textChildren[0].childNodes[0].nodeValue.strip()
        t1 = textChildren[1].childNodes[0].nodeValue.strip()
        assert t0 == 'foo' + specialChar, "%s should equal %s" % (
            ascii(t0), ascii('foo' + specialChar))
        assert t1 == 'bar'
Example #14
0
def findFontAndRegister(fontName):
    '''search for and register a font given its name'''
    fontName = str(fontName)
    assert type(
        fontName
    ) is str, 'fontName=%s is not required type str' % ascii(fontName)
    #it might have a font-specific encoding e.g. Symbol
    # or Dingbats.  If not, take the default.
    face = getTypeFace(fontName)
    if face.requiredEncoding:
        font = Font(fontName, fontName, face.requiredEncoding)
    else:
        font = Font(fontName, fontName, defaultEncoding)
    registerFont(font)
    return font
Example #15
0
 def write(self, u):
     if isBytes(u):
         try:
             u = u.decode('utf-8')
         except:
             et, ev, tb = sys.exc_info()
             ev = str(ev)
             del et, tb
             raise ValueError("String %r not encoded as 'utf-8'\nerror=%s" %
                              (u, ev))
     elif not isUnicode(u):
         raise ValueError(
             "EncodedWriter.write(%s) argument should be 'utf-8' bytes or str"
             % ascii(u))
     self.append(u)
Example #16
0
    def test2(self):
        "Test toColor function on half a dozen ways to say 'red'."

        allRed = [
            colors.red,
            [1, 0, 0],
            (1, 0, 0),
            b'red',
            b'RED',
            b'0xFF0000',
            b'0xff0000',
            b'rgb(255,0,0)',
            u'red',
            u'RED',
            u'0xFF0000',
            u'0xff0000',
            u'rgb(255,0,0)',
        ]

        for thing in allRed:
            assert colors.toColor(
                thing
            ) == colors.red, "colors.toColor(%s)-->%s != colors.red(%s)" % (
                ascii(thing), ascii(colors.toColor(thing)), colors.red)
Example #17
0
    def __init__(self,BASE=None,UNWANTED=[],**kw):
        data = {}
        if BASE:
            if isinstance(BASE,AttrMap):
                data = BASE
            else:
                if not isSeq(BASE): BASE = (BASE,)
                for B in BASE:
                    am = getattr(B,'_attrMap',self)
                    if am is not self:
                        if am: data.update(am)
                    else:
                        raise ValueError('BASE=%s has wrong kind of value' % ascii(B))

        dict.__init__(self,data)
        self.remove(UNWANTED)
        self.update(kw)
Example #18
0
    def __init__(self,BASE=None,UNWANTED=[],**kw):
        data = {}
        if BASE:
            if isinstance(BASE,AttrMap):
                data = BASE
            else:
                if not isSeq(BASE): BASE = (BASE,)
                for B in BASE:
                    am = getattr(B,'_attrMap',self)
                    if am is not self:
                        if am: data.update(am)
                    else:
                        raise ValueError('BASE=%s has wrong kind of value' % ascii(B))

        dict.__init__(self,data)
        self.remove(UNWANTED)
        self.update(kw)
Example #19
0
 def eval(self,L):
     arguments = self.arguments
     document = self.__document
     for x in L:
         if isinstance(x,strTypes):
             yield pdfdocEnc(x)
         elif isinstance(x,PDFObject):
             yield x.format(document)
         elif isinstance(x,PDFPatternIf):
             result = list(self.eval(x.cond))
             cond = result and result[0]
             for z in self.eval(x.thenPart if cond else x.elsePart):
                 yield z
         else:
             name = x[0]
             value = arguments.get(name, None)
             if value is None:
                 raise ValueError("%s value not defined" % ascii(name))
             if isinstance(value,PDFObject):
                 yield format(value,document)
             elif isinstance(value,strTypes):
                 yield pdfdocEnc(value)
             else:
                 yield pdfdocEnc(str(value))
Example #20
0
 def eval(self,L):
     arguments = self.arguments
     document = self.__document
     for x in L:
         if isinstance(x,strTypes):
             yield pdfdocEnc(x)
         elif isinstance(x,PDFObject):
             yield x.format(document)
         elif isinstance(x,PDFPatternIf):
             result = list(self.eval(x.cond))
             cond = result and result[0]
             for z in self.eval(x.thenPart if cond else x.elsePart):
                 yield z
         else:
             name = x[0]
             value = arguments.get(name, None)
             if value is None:
                 raise ValueError("%s value not defined" % ascii(name))
             if isinstance(value,PDFObject):
                 yield format(value,document)
             elif isinstance(value,strTypes):
                 yield pdfdocEnc(value)
             else:
                 yield pdfdocEnc(str(value))
Example #21
0
def eqCheck(r,x):
    if r!=x:
        print('Strings unequal\nexp: %s\ngot: %s' % (ascii(x),ascii(r)))
Example #22
0
def eqCheck(r,x):
    if r!=x:
        print('Strings unequal\nexp: %s\ngot: %s' % (ascii(x),ascii(r)))
Example #23
0
def computeO(userPassword, ownerPassword, revision):
    from reportlab.lib.arciv import ArcIV
    #print 'digest of hello is %s' % md5('hello').digest()
    assert revision in (2,3), 'Unknown algorithm revision %s' % revision
    if not ownerPassword:
        ownerPassword = userPassword

    ownerPad = asBytes(ownerPassword) + PadString
    ownerPad = ownerPad[0:32]

    password = asBytes(userPassword) + PadString
    userPad = password[:32]

    digest = md5(ownerPad).digest()
    if DEBUG: print('PadString=%s\nownerPad=%s\npassword=%s\nuserPad=%s\ndigest=%s\nrevision=%s' % (ascii(PadString),ascii(ownerPad),ascii(password),ascii(userPad),ascii(digest),revision))
    if revision == 2:
        O = ArcIV(digest[:5]).encode(userPad)
    elif revision == 3:
        for i in range(50):
            digest = md5(digest).digest()
        digest = digest[:16]
        O = userPad
        for i in range(20):
            thisKey = xorKey(i, digest)
            O = ArcIV(thisKey).encode(O)
    if DEBUG: print('computeO(%s,%s,%s)==>%s' % tuple([hexText(str(x)) for x in (userPassword, ownerPassword, revision,O)]))
    return O
Example #24
0
 def saveToFile(self,fn,fmt=None):
     im = self.toPIL()
     if fmt is None:
         if not isinstance(fn,str):
             raise ValueError("Invalid value '%s' for fn when fmt is None" % ascii(fn))
         fmt = os.path.splitext(fn)[1]
         if fmt.startswith('.'): fmt = fmt[1:]
     configPIL = self.configPIL or {}
     configPIL.setdefault('preConvertCB',None)
     preConvertCB=configPIL.pop('preConvertCB')
     if preConvertCB:
         im = preConvertCB(im)
     fmt = fmt.upper()
     if fmt in ('GIF',):
         im = _convert2pilp(im)
     elif fmt in ('TIFF','TIFFP','TIFFL','TIF','TIFF1'):
         if fmt.endswith('P'):
             im = _convert2pilp(im)
         elif fmt.endswith('L'):
             im = _convert2pilL(im)
         elif fmt.endswith('1'):
             im = _convert2pil1(im)
         fmt='TIFF'
     elif fmt in ('PCT','PICT'):
         return _saveAsPICT(im,fn,fmt,transparent=configPIL.get('transparent',None))
     elif fmt in ('PNG','BMP', 'PPM'):
         if fmt=='PNG':
             try:
                 from PIL import PngImagePlugin
             except ImportError:
                 import PngImagePlugin
         elif fmt=='BMP':
             try:
                 from PIL import BmpImagePlugin
             except ImportError:
                 import BmpImagePlugin
     elif fmt in ('JPG','JPEG'):
         fmt = 'JPEG'
     elif fmt in ('GIF',):
         pass
     else:
         raise RenderPMError("Unknown image kind %s" % fmt)
     if fmt=='TIFF':
         tc = configPIL.get('transparent',None)
         if tc:
             from PIL import ImageChops, Image
             T = 768*[0]
             for o, c in zip((0,256,512), tc.bitmap_rgb()):
                 T[o+c] = 255
             #if isinstance(fn,str): ImageChops.invert(im.point(T).convert('L').point(255*[0]+[255])).save(fn+'_mask.gif','GIF')
             im = Image.merge('RGBA', im.split()+(ImageChops.invert(im.point(T).convert('L').point(255*[0]+[255])),))
             #if isinstance(fn,str): im.save(fn+'_masked.gif','GIF')
         for a,d in ('resolution',self._dpi),('resolution unit','inch'):
             configPIL[a] = configPIL.get(a,d)
     configPIL.setdefault('chops_invert',0)
     if configPIL.pop('chops_invert'):
         from PIL import ImageChops
         im = ImageChops.invert(im)
     configPIL.setdefault('preSaveCB',None)
     preSaveCB=configPIL.pop('preSaveCB')
     if preSaveCB:
         im = preSaveCB(im)
     im.save(fn,fmt,**configPIL)
     if not hasattr(fn,'write') and os.name=='mac':
         from reportlab.lib.utils import markfilename
         markfilename(fn,ext=fmt)
Example #25
0
 def translate(self, nodetuple, controller, overrides, containerdict=None):
     # add own overrides if present
     if self.nodemappers:
         overrides = overrides.copy()
         overrides.update(self.nodemappers)
     (tagname, attdict, content, extra) = nodetuple
     #tagname = nodedict[0]
     #content = nodedict.get(1, None)
     if not attdict: attdict = {}
     sdict = attdict.copy() # for modification
     prefix = tagname
     # prefix must be set before processing children
     #print "processing", tagname
     #print containerdict
     if containerdict is not None:
         cprefix = containerdict["__prefix__"]
         if cprefix:
             prefix = "%s.%s" % (cprefix, prefix)
     else:
         cprefix = ''
     sdict['__prefix__'] = prefix
     sdict['__parent_prefix__'] = cprefix
     sdict['__depth__'] = prefix.count('.')
     sdict['__parent_depth__'] = sdict['__depth__']-1
     sdict['__tag_depth__'] = (prefix+'.').count(tagname+'.')
     sdict['__mapnode__'] = self
     sdict['__controller__'] = controller
     sdict['__overrides__'] = overrides
     sdict['__containerdict__'] = containerdict
     sdict['__nodetuple__'] = nodetuple
     sdict["__tagname__"] = tagname
     sdict["__attrs__"] = LazyAttrs(attdict)
     defaults = self.defaults
     for name in list(defaults.keys()):
         if name not in sdict:
             sdict[name] = defaults[name]
     shadow = ShadowDict(tagname, sdict, containerdict)
     sdict['__shadow__'] = shadow
     #if content is None: stop
     if content is not None:
         pcontent = self.MyProcessContent(content, controller, overrides, shadow)
         sdict["__content__"] = pcontent
         # you can refer to TITLE.__content__
         top = controller.topDict
         if containerdict is not None:
             containerdict[tagname+".__content__"] = pcontent
         # you can refer to PLAY.TITLE.__content__
         top[prefix+".__content__"] = pcontent
         sstring = self.full_substitution_string
         if sstring is None:
             raise ValueError("no content allowed for %s" % ascii(tagname))
     else:
         sstring = self.empty_substitution_string
         if sstring is None:
             raise ValueError("content required for %s" % ascii(tagname))
     transforms = self.transforms
     for name in list(transforms.keys()):
         if name in sdict:
             t = transforms[name]
             if isinstance(t,SpecialTransform) or name=='__attrs__':
                 sdict[name] = t(sdict,name)
             else:
                 oldvalue = asUnicodeEx(sdict[name]) # IS STRING CONVERSION ALWAYS RIGHT?
                 if isinstance(t,ExtendedTransform):
                     sdict[name] = t(oldvalue, sdict)
                 else:
                     sdict[name] = t(oldvalue)
     try:
         result = shadow.substitute(sstring) #sstring % sdict
     except:
         raise ValueError("for tagname %s bad string %s for dict %s" % (
             ascii(tagname), ascii(sstring), ascii(list(sdict.keys()))))
     return result
Example #26
0
 def testEscapePDF(self):
     for func, kind in getFuncs('escapePDF'):
         assert func(
             '(test)'
         ) == '\\(test\\)', "%s escapePDF('(test)')=='\\\\(test\\\\)' fails with value %s!" % (
             kind, ascii(func('(test)')))
Example #27
0
def test(outDir='pmout', shout=False):
    def ext(x):
        if x=='tiff': x='tif'
        return x
    #grab all drawings from the test module and write out.
    #make a page of links in HTML to assist viewing.
    import os
    from reportlab.graphics import testshapes
    from reportlab.rl_config import verbose
    getAllTestDrawings = testshapes.getAllTestDrawings
    drawings = []
    if not os.path.isdir(outDir):
        os.mkdir(outDir)
    htmlTop = """<html><head><title>renderPM output results</title></head>
    <body>
    <h1>renderPM results of output</h1>
    """
    htmlBottom = """</body>
    </html>
    """
    html = [htmlTop]
    names = {}
    argv = sys.argv[1:]
    E = [a for a in argv if a.startswith('--ext=')]
    if not E:
        E = ['gif','tiff', 'png', 'jpg', 'pct', 'py', 'svg']
    else:
        for a in E:
            argv.remove(a)
        E = (','.join([a[6:] for a in E])).split(',')

    errs = []
    import traceback
    from xml.sax.saxutils import escape
    def handleError(name,fmt):
        msg = 'Problem drawing %s fmt=%s file'%(name,fmt)
        if shout or verbose>2: print(msg)
        errs.append('<br/><h2 style="color:red">%s</h2>' % msg)
        buf = getStringIO()
        traceback.print_exc(file=buf)
        errs.append('<pre>%s</pre>' % escape(buf.getvalue()))

    #print in a loop, with their doc strings
    for (drawing, docstring, name) in getAllTestDrawings(doTTF=hasattr(_renderPM,'ft_get_face')):
        i = names[name] = names.setdefault(name,0)+1
        if i>1: name += '.%02d' % (i-1)
        if argv and name not in argv: continue
        fnRoot = name
        w = int(drawing.width)
        h = int(drawing.height)
        html.append('<hr><h2>Drawing %s</h2>\n<pre>%s</pre>' % (name, docstring))

        for k in E:
            if k in ['gif','png','jpg','pct']:
                html.append('<p>%s format</p>\n' % k.upper())
            try:
                filename = '%s.%s' % (fnRoot, ext(k))
                fullpath = os.path.join(outDir, filename)
                if os.path.isfile(fullpath):
                    os.remove(fullpath)
                if k=='pct':
                    from reportlab.lib.colors import white
                    drawToFile(drawing,fullpath,fmt=k,configPIL={'transparent':white})
                elif k in ['py','svg']:
                    drawing.save(formats=['py','svg'],outDir=outDir,fnRoot=fnRoot)
                else:
                    drawToFile(drawing,fullpath,fmt=k)
                if k in ['gif','png','jpg']:
                    html.append('<img src="%s" border="1"><br>\n' % filename)
                elif k=='py':
                    html.append('<a href="%s">python source</a><br>\n' % filename)
                elif k=='svg':
                    html.append('<a href="%s">SVG</a><br>\n' % filename)
                if shout or verbose>2: print('wrote %s'%ascii(fullpath))
            except AttributeError:
                handleError(name,k)
        if os.environ.get('RL_NOEPSPREVIEW','0')=='1': drawing.__dict__['preview'] = 0
        for k in ('eps', 'pdf'):
            try:
                drawing.save(formats=[k],outDir=outDir,fnRoot=fnRoot)
            except:
                handleError(name,k)

    if errs:
        html[0] = html[0].replace('</h1>',' <a href="#errors" style="color: red">(errors)</a></h1>')
        html.append('<a name="errors"/>')
        html.extend(errs)
    html.append(htmlBottom)
    htmlFileName = os.path.join(outDir, 'pm-index.html')
    with open(htmlFileName, 'w') as f:
        f.writelines(html)
    if sys.platform=='mac':
        from reportlab.lib.utils import markfilename
        markfilename(htmlFileName,ext='HTML')
    if shout or verbose>2: print('wrote %s' % htmlFileName)
Example #28
0
 def saveToFile(self, fn, fmt=None):
     im = self.toPIL()
     if fmt is None:
         if not isinstance(fn, str):
             raise ValueError("Invalid value '%s' for fn when fmt is None" %
                              ascii(fn))
         fmt = os.path.splitext(fn)[1]
         if fmt.startswith('.'): fmt = fmt[1:]
     configPIL = self.configPIL or {}
     configPIL.setdefault('preConvertCB', None)
     preConvertCB = configPIL.pop('preConvertCB')
     if preConvertCB:
         im = preConvertCB(im)
     fmt = fmt.upper()
     if fmt in ('GIF', ):
         im = _convert2pilp(im)
     elif fmt in ('TIFF', 'TIFFP', 'TIFFL', 'TIF', 'TIFF1'):
         if fmt.endswith('P'):
             im = _convert2pilp(im)
         elif fmt.endswith('L'):
             im = _convert2pilL(im)
         elif fmt.endswith('1'):
             im = _convert2pil1(im)
         fmt = 'TIFF'
     elif fmt in ('PCT', 'PICT'):
         return _saveAsPICT(im,
                            fn,
                            fmt,
                            transparent=configPIL.get('transparent', None))
     elif fmt in ('PNG', 'BMP', 'PPM'):
         if fmt == 'PNG':
             try:
                 from PIL import PngImagePlugin
             except ImportError:
                 import PngImagePlugin
         elif fmt == 'BMP':
             try:
                 from PIL import BmpImagePlugin
             except ImportError:
                 import BmpImagePlugin
     elif fmt in ('JPG', 'JPEG'):
         fmt = 'JPEG'
     elif fmt in ('GIF', ):
         pass
     else:
         raise RenderPMError("Unknown image kind %s" % fmt)
     if fmt == 'TIFF':
         tc = configPIL.get('transparent', None)
         if tc:
             from PIL import ImageChops, Image
             T = 768 * [0]
             for o, c in zip((0, 256, 512), tc.bitmap_rgb()):
                 T[o + c] = 255
             #if isinstance(fn,str): ImageChops.invert(im.point(T).convert('L').point(255*[0]+[255])).save(fn+'_mask.gif','GIF')
             im = Image.merge(
                 'RGBA',
                 im.split() + (ImageChops.invert(
                     im.point(T).convert('L').point(255 * [0] + [255])), ))
             #if isinstance(fn,str): im.save(fn+'_masked.gif','GIF')
         for a, d in ('resolution', self._dpi), ('resolution unit', 'inch'):
             configPIL[a] = configPIL.get(a, d)
     configPIL.setdefault('chops_invert', 0)
     if configPIL.pop('chops_invert'):
         from PIL import ImageChops
         im = ImageChops.invert(im)
     configPIL.setdefault('preSaveCB', None)
     preSaveCB = configPIL.pop('preSaveCB')
     if preSaveCB:
         im = preSaveCB(im)
     im.save(fn, fmt, **configPIL)
     if not hasattr(fn, 'write') and os.name == 'mac':
         from reportlab.lib.utils import markfilename
         markfilename(fn, ext=fmt)
Example #29
0
def test(outDir='pmout', shout=False):
    def ext(x):
        if x == 'tiff': x = 'tif'
        return x

    #grab all drawings from the test module and write out.
    #make a page of links in HTML to assist viewing.
    import os
    from reportlab.graphics import testshapes
    from reportlab.rl_config import verbose
    getAllTestDrawings = testshapes.getAllTestDrawings
    drawings = []
    if not os.path.isdir(outDir):
        os.mkdir(outDir)
    htmlTop = """<html><head><title>renderPM output results</title></head>
    <body>
    <h1>renderPM results of output</h1>
    """
    htmlBottom = """</body>
    </html>
    """
    html = [htmlTop]
    names = {}
    argv = sys.argv[1:]
    E = [a for a in argv if a.startswith('--ext=')]
    if not E:
        E = ['gif', 'tiff', 'png', 'jpg', 'pct', 'py', 'svg']
    else:
        for a in E:
            argv.remove(a)
        E = (','.join([a[6:] for a in E])).split(',')

    errs = []
    import traceback
    from xml.sax.saxutils import escape

    def handleError(name, fmt):
        msg = 'Problem drawing %s fmt=%s file' % (name, fmt)
        if shout or verbose > 2: print(msg)
        errs.append('<br/><h2 style="color:red">%s</h2>' % msg)
        buf = getStringIO()
        traceback.print_exc(file=buf)
        errs.append('<pre>%s</pre>' % escape(buf.getvalue()))

    #print in a loop, with their doc strings
    for (drawing, docstring,
         name) in getAllTestDrawings(doTTF=hasattr(_renderPM, 'ft_get_face')):
        i = names[name] = names.setdefault(name, 0) + 1
        if i > 1: name += '.%02d' % (i - 1)
        if argv and name not in argv: continue
        fnRoot = name
        w = int(drawing.width)
        h = int(drawing.height)
        html.append('<hr><h2>Drawing %s</h2>\n<pre>%s</pre>' %
                    (name, docstring))

        for k in E:
            if k in ['gif', 'png', 'jpg', 'pct']:
                html.append('<p>%s format</p>\n' % k.upper())
            try:
                filename = '%s.%s' % (fnRoot, ext(k))
                fullpath = os.path.join(outDir, filename)
                if os.path.isfile(fullpath):
                    os.remove(fullpath)
                if k == 'pct':
                    from reportlab.lib.colors import white
                    drawToFile(drawing,
                               fullpath,
                               fmt=k,
                               configPIL={'transparent': white})
                elif k in ['py', 'svg']:
                    drawing.save(formats=['py', 'svg'],
                                 outDir=outDir,
                                 fnRoot=fnRoot)
                else:
                    drawToFile(drawing, fullpath, fmt=k)
                if k in ['gif', 'png', 'jpg']:
                    html.append('<img src="%s" border="1"><br>\n' % filename)
                elif k == 'py':
                    html.append('<a href="%s">python source</a><br>\n' %
                                filename)
                elif k == 'svg':
                    html.append('<a href="%s">SVG</a><br>\n' % filename)
                if shout or verbose > 2: print('wrote %s' % ascii(fullpath))
            except AttributeError:
                handleError(name, k)
        if os.environ.get('RL_NOEPSPREVIEW', '0') == '1':
            drawing.__dict__['preview'] = 0
        for k in ('eps', 'pdf'):
            try:
                drawing.save(formats=[k], outDir=outDir, fnRoot=fnRoot)
            except:
                handleError(name, k)

    if errs:
        html[0] = html[0].replace(
            '</h1>', ' <a href="#errors" style="color: red">(errors)</a></h1>')
        html.append('<a name="errors"/>')
        html.extend(errs)
    html.append(htmlBottom)
    htmlFileName = os.path.join(outDir, 'pm-index.html')
    with open(htmlFileName, 'w') as f:
        f.writelines(html)
    if sys.platform == 'mac':
        from reportlab.lib.utils import markfilename
        markfilename(htmlFileName, ext='HTML')
    if shout or verbose > 2: print('wrote %s' % htmlFileName)
Example #30
0
 def testCalcChecksum(self):
     for func, kind in getFuncs('calcChecksum'):
         assert func(
             'test'
         ) == 1952805748, "%s calcChecksum('test')==1952805748 fails with value %s!" % (
             kind, ascii(func(rawBytes('test'))))
Example #31
0
def _patternSequenceCheck(pattern_sequence):
    allowedTypes = strTypes if isinstance(strTypes, tuple) else (strTypes,)
    allowedTypes = allowedTypes + (PDFObject,PDFPatternIf)
    for x in pattern_sequence:
        if not isinstance(x,allowedTypes):
            if len(x)!=1:
                raise ValueError("sequence elts must be strings/bytes/PDFPatternIfs or singletons containing strings: "+ascii(x))
            if not isinstance(x[0],strTypes):
                raise ValueError("Singletons must contain strings/bytes or PDFObject instances only: "+ascii(x[0]))
Example #32
0
 def testAsciiBase85Decode(self):
     for func, kind in getFuncs('asciiBase85Decode'):
         assert func(
             '6ul^K@;[2RDIdd%@f~>'
         ) == b'Dragan Andric', "%s asciiBase85Decode('6ul^K@;[2RDIdd%@f~>')=='Dragan Andric' fails with value %s!" % (
             kind, ascii(func('Dragan Andric')))
Example #33
0
 def testAsciiBase85RoundTrip(self):
     plain = 'What is the average velocity of a sparrow?'
     eFuncs = getFuncs('asciiBase85Encode')
     for i in xrange(256):
         for j, (dfunc, kind) in enumerate(getFuncs('asciiBase85Decode')):
             efunc = eFuncs[j][0]
             encoded = efunc(plain)
             decoded = dfunc(encoded)
             assert decoded == asBytes(
                 plain, 'latin1'
             ), "Round-trip AsciiBase85 failed for %s & %s\nplain=%s\nencoded=%s\ndecoded=%s" % (
                 ascii(efunc), ascii(dfunc), ascii(plain), ascii(encoded),
                 ascii(decoded))
             if not j:
                 enc0 = encoded
                 dec0 = decoded
             else:
                 assert encoded == enc0, " Python & C encodings differ failed for %s & %s\nplain=%s\nencode0=%s\nencoded=%s\ndecode0=%sdecoded=%s" % (
                     ascii(efunc), ascii(dfunc), ascii(plain), ascii(enc0),
                     ascii(encoded), ascii(dec0), ascii(decoded))
                 assert decoded == dec0, " Python & C decodings differ failed for %s & %s\nplain=%s\nencode0=%s\nencoded=%s\ndecode0=%sdecoded=%s" % (
                     ascii(efunc), ascii(dfunc), ascii(plain), ascii(enc0),
                     ascii(encoded), ascii(dec0), ascii(decoded))
         plain += chr(i)
Example #34
0
    def test0(self):
        "A basic document drawing some strings"
        c = Canvas(outputfile('test_multibyte_jpn.pdf'))
        c.setFont('Helvetica', 30)
        c.drawString(100, 700, 'Japanese Font Support')

        c.setStrokeColor(colors.red)

        #unicode font automatically supplies the encoding
        pdfmetrics.registerFont(UnicodeCIDFont('HeiseiMin-W3'))

        msg = u'\u6771\u4EAC : Unicode font, unicode input'
        self.hDraw(c, msg, 'HeiseiMin-W3', 100, 600)

        msg = u'\u6771\u4EAC : Unicode font, utf8 input'.encode('utf8')
        self.hDraw(c, msg, 'HeiseiMin-W3', 100, 575)

        # now try verticals - this is broken, not sure how to make it
        # work in post Unicode world.
        pdfmetrics.registerFont(CIDFont('HeiseiMin-W3', '90ms-RKSJ-V'))
        c.setFont('HeiseiMin-W3-90ms-RKSJ-V', 16)
        c.drawString(450, 650, '\223\214\213\236 vertical Shift-JIS')
        height = c.stringWidth('\223\214\213\236 vertical Shift-JIS',
                               'HeiseiMin-W3-90ms-RKSJ-V', 16)
        c.rect(450 - 8, 650, 16, -height)

        pdfmetrics.registerFont(CIDFont('HeiseiMin-W3', 'EUC-V'))
        c.setFont('HeiseiMin-W3-EUC-V', 16)
        c.drawString(475, 650, '\xC5\xEC\xB5\xFE vertical EUC')
        height = c.stringWidth('\xC5\xEC\xB5\xFE vertical EUC',
                               'HeiseiMin-W3-EUC-V', 16)
        c.rect(475 - 8, 650, 16, -height)

        from reportlab.platypus.paragraph import Paragraph
        from reportlab.lib.styles import ParagraphStyle
        jStyle = ParagraphStyle('jtext',
                                fontName='HeiseiMin-W3',
                                fontSize=12,
                                wordWrap="CJK")

        gatwickText = '\xe3\x82\xac\xe3\x83\x88\xe3\x82\xa6\xe3\x82\xa3\xe3\x83\x83\xe3\x82\xaf\xe7\xa9\xba\xe6\xb8\xaf\xe3\x81\xa8\xe9\x80\xa3\xe7\xb5\xa1\xe9\x80\x9a\xe8\xb7\xaf\xe3\x81\xa7\xe7\x9b\xb4\xe7\xb5\x90\xe3\x81\x95\xe3\x82\x8c\xe3\x81\xa6\xe3\x81\x84\xe3\x82\x8b\xe5\x94\xaf\xe4\xb8\x80\xe3\x81\xae\xe3\x83\x9b\xe3\x83\x86\xe3\x83\xab\xe3\x81\xa7\xe3\x81\x82\xe3\x82\x8b\xe5\xbd\x93\xe3\x83\x9b\xe3\x83\x86\xe3\x83\xab\xe3\x81\xaf\xe3\x80\x81\xe8\xa1\x97\xe3\x81\xae\xe4\xb8\xad\xe5\xbf\x83\xe9\x83\xa8\xe3\x81\x8b\xe3\x82\x8930\xe5\x88\x86\xe3\x81\xae\xe5\xa0\xb4\xe6\x89\x80\xe3\x81\xab\xe3\x81\x94\xe3\x81\x96\xe3\x81\x84\xe3\x81\xbe\xe3\x81\x99\xe3\x80\x82\xe5\x85\xa8\xe5\xae\xa2\xe5\xae\xa4\xe3\x81\xab\xe9\xab\x98\xe9\x80\x9f\xe3\x82\xa4\xe3\x83\xb3\xe3\x82\xbf\xe3\x83\xbc\xe3\x83\x8d\xe3\x83\x83\xe3\x83\x88\xe7\x92\xb0\xe5\xa2\x83\xe3\x82\x92\xe5\xae\x8c\xe5\x82\x99\xe3\x81\x97\xe3\x81\xa6\xe3\x81\x8a\xe3\x82\x8a\xe3\x81\xbe\xe3\x81\x99\xe3\x80\x82\xe3\x83\x95\xe3\x82\xa1\xe3\x83\x9f\xe3\x83\xaa\xe3\x83\xbc\xe3\x83\xab\xe3\x83\xbc\xe3\x83\xa0\xe3\x81\xaf5\xe5\x90\x8d\xe6\xa7\x98\xe3\x81\xbe\xe3\x81\xa7\xe3\x81\x8a\xe6\xb3\x8a\xe3\x82\x8a\xe3\x81\x84\xe3\x81\x9f\xe3\x81\xa0\xe3\x81\x91\xe3\x81\xbe\xe3\x81\x99\xe3\x80\x82\xe3\x81\xbe\xe3\x81\x9f\xe3\x80\x81\xe3\x82\xa8\xe3\x82\xb0\xe3\x82\xbc\xe3\x82\xaf\xe3\x83\x86\xe3\x82\xa3\xe3\x83\x96\xe3\x83\xab\xe3\x83\xbc\xe3\x83\xa0\xe3\x81\xae\xe3\x81\x8a\xe5\xae\xa2\xe6\xa7\x98\xe3\x81\xaf\xe3\x80\x81\xe3\x82\xa8\xe3\x82\xb0\xe3\x82\xbc\xe3\x82\xaf\xe3\x83\x86\xe3\x82\xa3\xe3\x83\x96\xe3\x83\xa9\xe3\x82\xa6\xe3\x83\xb3\xe3\x82\xb8\xe3\x82\x92\xe3\x81\x94\xe5\x88\xa9\xe7\x94\xa8\xe3\x81\x84\xe3\x81\x9f\xe3\x81\xa0\xe3\x81\x91\xe3\x81\xbe\xe3\x81\x99\xe3\x80\x82\xe4\xba\x8b\xe5\x89\x8d\xe3\x81\xab\xe3\x81\x94\xe4\xba\x88\xe7\xb4\x84\xe3\x81\x84\xe3\x81\x9f\xe3\x81\xa0\xe3\x81\x91\xe3\x82\x8b\xe3\x82\xbf\xe3\x82\xa4\xe3\x83\xa0\xe3\x83\x88\xe3\x82\xa5\xe3\x83\x95\xe3\x83\xa9\xe3\x82\xa4\xe3\x83\xbb\xe3\x83\x91\xe3\x83\x83\xe3\x82\xb1\xe3\x83\xbc\xe3\x82\xb8\xe3\x81\xab\xe3\x81\xaf\xe3\x80\x81\xe7\xa9\xba\xe6\xb8\xaf\xe3\x81\xae\xe9\xa7\x90\xe8\xbb\x8a\xe6\x96\x99\xe9\x87\x91\xe3\x81\x8c\xe5\x90\xab\xe3\x81\xbe\xe3\x82\x8c\xe3\x81\xa6\xe3\x81\x8a\xe3\x82\x8a\xe3\x81\xbe\xe3\x81\x99\xe3\x80\x82'
        gatwickText2 = '\xe3\x82\xac\xe3\x83\x88\xe3\x82\xa6\xe3\x82\xa3\xe3\x83\x83\xe3\x82\xaf<font color=red>\xe7\xa9\xba\xe6\xb8\xaf\xe3\x81\xa8\xe9\x80\xa3\xe7\xb5\xa1\xe9\x80\x9a\xe8\xb7\xaf\xe3\x81\xa7\xe7\x9b\xb4\xe7\xb5\x90</font>\xe3\x81\x95\xe3\x82\x8c\xe3\x81\xa6\xe3\x81\x84\xe3\x82\x8b\xe5\x94\xaf\xe4\xb8\x80\xe3\x81\xae\xe3\x83\x9b\xe3\x83\x86\xe3\x83\xab\xe3\x81\xa7\xe3\x81\x82\xe3\x82\x8b\xe5\xbd\x93\xe3\x83\x9b\xe3\x83\x86\xe3\x83\xab\xe3\x81\xaf\xe3\x80\x81\xe8\xa1\x97\xe3\x81\xae\xe4\xb8\xad\xe5\xbf\x83\xe9\x83\xa8\xe3\x81\x8b\xe3\x82\x8930\xe5\x88\x86\xe3\x81\xae\xe5\xa0\xb4\xe6\x89\x80\xe3\x81\xab\xe3\x81\x94\xe3\x81\x96\xe3\x81\x84\xe3\x81\xbe\xe3\x81\x99\xe3\x80\x82\xe5\x85\xa8\xe5\xae\xa2\xe5\xae\xa4\xe3\x81\xab\xe9\xab\x98\xe9\x80\x9f\xe3\x82\xa4\xe3\x83\xb3\xe3\x82\xbf\xe3\x83\xbc\xe3\x83\x8d\xe3\x83\x83\xe3\x83\x88<link fg="blue" href="http://www.reportlab.com">\xe7\x92\xb0\xe5\xa2\x83\xe3\x82\x92\xe5\xae\x8c\xe5\x82\x99</link>\xe3\x81\x97\xe3\x81\xa6<u>\xe3\x81\x8a\xe3\x82\x8a\xe3\x81\xbe\xe3\x81\x99</u>\xe3\x80\x82\xe3\x83\x95\xe3\x82\xa1\xe3\x83\x9f\xe3\x83\xaa\xe3\x83\xbc\xe3\x83\xab\xe3\x83\xbc\xe3\x83\xa0\xe3\x81\xaf5\xe5\x90\x8d\xe6\xa7\x98\xe3\x81\xbe\xe3\x81\xa7\xe3\x81\x8a\xe6\xb3\x8a\xe3\x82\x8a\xe3\x81\x84\xe3\x81\x9f\xe3\x81\xa0\xe3\x81\x91\xe3\x81\xbe\xe3\x81\x99\xe3\x80\x82\xe3\x81\xbe\xe3\x81\x9f\xe3\x80\x81\xe3\x82\xa8\xe3\x82\xb0\xe3\x82\xbc\xe3\x82\xaf\xe3\x83\x86\xe3\x82\xa3\xe3\x83\x96\xe3\x83\xab\xe3\x83\xbc\xe3\x83\xa0\xe3\x81\xae\xe3\x81\x8a\xe5\xae\xa2\xe6\xa7\x98\xe3\x81\xaf\xe3\x80\x81\xe3\x82\xa8\xe3\x82\xb0\xe3\x82\xbc\xe3\x82\xaf\xe3\x83\x86\xe3\x82\xa3\xe3\x83\x96\xe3\x83\xa9\xe3\x82\xa6\xe3\x83\xb3\xe3\x82\xb8\xe3\x82\x92\xe3\x81\x94\xe5\x88\xa9\xe7\x94\xa8\xe3\x81\x84\xe3\x81\x9f\xe3\x81\xa0\xe3\x81\x91\xe3\x81\xbe\xe3\x81\x99\xe3\x80\x82\xe4\xba\x8b\xe5\x89\x8d\xe3\x81\xab\xe3\x81\x94\xe4\xba\x88\xe7\xb4\x84\xe3\x81\x84\xe3\x81\x9f\xe3\x81\xa0\xe3\x81\x91\xe3\x82\x8b\xe3\x82\xbf\xe3\x82\xa4\xe3\x83\xa0\xe3\x83\x88\xe3\x82\xa5\xe3\x83\x95\xe3\x83\xa9\xe3\x82\xa4\xe3\x83\xbb\xe3\x83\x91\xe3\x83\x83\xe3\x82\xb1\xe3\x83\xbc\xe3\x82\xb8\xe3\x81\xab\xe3\x81\xaf\xe3\x80\x81\xe7\xa9\xba\xe6\xb8\xaf\xe3\x81\xae\xe9\xa7\x90\xe8\xbb\x8a\xe6\x96\x99\xe9\x87\x91\xe3\x81\x8c\xe5\x90\xab\xe3\x81\xbe\xe3\x82\x8c\xe3\x81\xa6\xe3\x81\x8a\xe3\x82\x8a\xe3\x81\xbe\xe3\x81\x99\xe3\x80\x82'

        c.setFont('HeiseiMin-W3', 12)
        jPara = Paragraph(gatwickText, jStyle)
        jPara.wrap(300, 200)
        jPara.drawOn(c, 100, 220)

        jPara = Paragraph(gatwickText2, jStyle)
        jPara.wrap(300, 200)
        jPara.drawOn(c, 100, 320)

        c.setFillColor(colors.purple)
        tx = c.beginText(100, 200)
        tx.setFont('Helvetica', 12)
        tx.textLines("""This document shows sample output in Japanese
        from the Reportlab PDF library.  This page shows the two fonts
        available and tests our ability to measure the width of glyphs
        in both horizontal and vertical writing, with proportional and
        fixed-width characters. The red boxes should be the same width
        (or height) as the character strings they surround.
        The next pages show more samples and information.
        """)
        c.drawText(tx)
        c.setFont('Helvetica', 10)
        c.drawCentredString(297, 36, 'Page %d' % c.getPageNumber())

        c.showPage()

        c.setFont('Helvetica', 30)
        c.drawString(100, 700, 'Japanese TrueType Font Support')
        msg = u'\u6771\u4EAC : Unicode font'.encode('utf8')
        msg2 = u'utf8 input 0123456789 ABCDEF'.encode('utf8')
        from reportlab.pdfbase.ttfonts import TTFont
        try:
            msmincho = TTFont('MS Mincho',
                              'msmincho.ttc',
                              subfontIndex=0,
                              asciiReadable=0)
            fn = ' file=msmincho.ttc subfont 0'
        except:
            try:
                msmincho = TTFont('MS Mincho', 'msmincho.ttf', asciiReadable=0)
                fn = 'file=msmincho.ttf'
            except:
                #Ubuntu - works on Lucid Lynx if xpdf-japanese installed
                try:
                    msmincho = TTFont('MS Mincho', 'ttf-japanese-mincho.ttf')
                    fn = 'file=msmincho.ttf'
                except:
                    msmincho = None
        if msmincho is None:
            c.setFont('Helvetica', 12)
            c.drawString(100, 600, 'Cannot find msmincho.ttf or msmincho.ttc')
        else:
            pdfmetrics.registerFont(msmincho)
            c.setFont('MS Mincho', 30)
            c.drawString(100, 600, msg)
            c.drawString(100, 570, msg2)
            c.drawString(100, 540, fn)
            if fn.endswith('0'):
                try:
                    msmincho1 = TTFont('MS Mincho 1',
                                       'msmincho.ttc',
                                       subfontIndex=1,
                                       asciiPreload=0)
                    pdfmetrics.registerFont(msmincho1)
                    fn = ' file=msmincho.ttc subfont 1'
                    c.setFont('MS Mincho 1', 30)
                    c.drawString(100, 500, msg + fn)
                except:
                    c.setFont('Helvetica', 30)
                    c.drawString(100, 500, msg)
                c.drawString(100, 470, msg2)
                c.drawString(100, 440, fn)
            #test a paragraph with CJK and <br/> tags
            u = u'''<font color=red>\u30ac\u30c8\u30a6\u30a3\u30c3</font><br/><font color=blue>\u30af\u7a7a\u6e2f\u3068\u9023\u7d61\u901a</font><br/>\u8def\u3067\u76f4\u7d50\u3055\u308c\u3066\u3044\u308b\u552f<br/>\u4e00\u306e\u30db\u30c6\u30eb\u3067\u3042\u308b\u5f53\u30db\u30c6\u30eb\u306f\u3001\u8857\u306e\u4e2d\u5fc3\u90e8\u304b\u308930\u5206\u306e\u5834\u6240\u306b\u3054\u3056\u3044\u307e\u3059\u3002\u5168\u5ba2\u5ba4\u306b\u9ad8\u901f\u30a4\u30f3\u30bf\u30fc\u30cd\u30c3\u30c8<br/>\u74b0\u5883\u3092\u5b8c\u5099\u3057\u3066\u304a\u308a\u307e\u3059\u3002\u30d5\u30a1\u30df\u30ea\u30fc\u30eb\u30fc\u30e0\u306f5\u540d\u69d8\u307e\u3067\u304a\u6cca\u308a\u3044\u305f\u3060\u3051\u307e\u3059\u3002\u307e\u305f\u3001\u30a8\u30b0\u30bc\u30af\u30c6\u30a3\u30d6\u30eb\u30fc\u30e0\u306e\u304a\u5ba2\u69d8\u306f\u3001\u30a8\u30b0\u30bc\u30af\u30c6\u30a3\u30d6\u30e9\u30a6\u30f3\u30b8\u3092\u3054\u5229\u7528\u3044\u305f\u3060\u3051\u307e\u3059\u3002\u4e8b\u524d\u306b\u3054\u4e88\u7d04\u3044\u305f\u3060\u3051\u308b\u30bf\u30a4\u30e0\u30c8\u30a5\u30d5\u30e9\u30a4\u30fb\u30d1\u30c3\u30b1\u30fc\u30b8\u306b\u306f\u3001\u7a7a\u6e2f\u306e\u99d0\u8eca\u6599\u91d1\u304c\u542b\u307e\u308c\u3066\u304a\u308a\u307e\u3059\u3002'''
            jPara = Paragraph(u, jStyle)
            jPara.wrap(300, 500)
            jPara.drawOn(c, 100, 300)

        c.showPage()

        # realistic text sample
        ##        sample = """Adobe Acrobat
        ##\x83h\x83L\x83\x85\x83\x81\x83\x93\x83g\x82\xaa\x8aJ\x82\xa9\x82\xc8\x82\xad\x82\xc4\x8d\xa2\x82\xc1\x82\xbd\x82\xb1\x82\xc6\x82\xcd
        ##\x82\xa0\x82\xe8\x82\xdc\x82\xb9\x82\xf1\x82\xa9\x81B\x8e\x96\x8b\xc6\x8cv\x89\xe6\x8f\x91\x81A\x89c\x8b\xc6\x83\x8c\x83|\x81[\x83g
        ##\x81A\x83J\x83^\x83\x8d\x83O\x82\xe2\x83p\x83\x93\x83t\x83\x8c\x83b\x83g\x82\xc8\x82\xc7\x90\xa7\x8d\xec\x95\xa8\x82\xcc\x8e\xed
        ##\x97\xde\x82\xc9\x82\xa9\x82\xa9\x82\xed\x82\xe7\x82\xb8\x81A
        ##\x83h\x83L\x83\x85\x83\x81\x83\x93\x83g\x82\xcdAdobe&reg; Acrobat&reg; 5.0\x82\xf0\x8eg\x82\xc1\x82\xc4Adobe PDF\x81iPortable Document
        ##Format\x81j\x83t\x83@\x83C\x83\x8b\x82\xc9\x95\xcf\x8a\xb7\x82\xb5\x82\xdc\x82\xb5\x82\xe5\x82\xa4\x81B\x96\xb3\x8f\x9e\x94z\x95z\x82\xcc
        ##Adobe Acrobat Reader\x82\xf0\x8eg\x82\xa6\x82\xce\x81A\x83n\x81[\x83h\x83E\x83F\x83A\x81A\x83\\\x83t\x83g\x83E\x83F\x83A\x82\xc9\x82\xa9
        ##\x82\xa9\x82\xed\x82\xe7\x82\xb8\x81A\x92N\x82\xc5\x82\xe0\x82\xa0\x82\xc8\x82\xbd\x82\xcc\x83h\x83L\x83\x85\x83\x81\x83\x93\x83g\x82\xf0
        ##\x83I\x83\x8a\x83W\x83i\x83\x8b\x82\xcc\x91\xcc\x8d\xd9\x82\xc5\x8aJ\x82\xad\x82\xb1\x82\xc6\x82\xaa\x82\xc5\x82\xab\x82\xdc\x82\xb7\x81B
        ##\x82\xa0\x82\xc8\x82\xbd\x82\xcc\x88\xd3\x90}\x82\xb5\x82\xbd\x82\xc6\x82\xa8\x82\xe8\x82\xc9\x8f\xee\x95\xf1\x82\xf0\x93`\x82\xa6\x82\xe9
        ##\x82\xb1\x82\xc6\x82\xaa\x82\xc5\x82\xab\x82\xdc\x82\xb7\x81B
        ##\x82\xb3\x82\xe7\x82\xc9\x81AAdobe Acrobat 5.0\x82\xc5\x82\xcd\x81AWeb\x83u\x83\x89\x83E\x83U\x82\xa9\x82\xe7\x83R\x83\x81\x83\x93\x83g\x82\xe2
        ##\x83}\x81[\x83N\x83A\x83b\x83v\x82\xf0\x8f\x91\x82\xab\x8d\x9e\x82\xf1\x82\xbe\x82\xe8\x81A\x93d\x8eq\x8f\x90\x96\xbc\x82\xf0\x8f\x91\x82\xab
        ##\x8d\x9e\x82\xdd\x81A\x8c\xb4\x96{\x82\xc6\x82\xb5\x82\xc4\x83\x8d\x81[\x83J\x83\x8b\x82\xc9\x95\xdb\x91\xb6\x82\xb7\x82\xe9\x82\xb1\x82\xc6\x82\xe0\x89\xc2\x94\\\x82\xc5\x82\xb7\x81B
        ##\x8a\xe9\x8b\xc6\x93\xe0\x82\xa0\x82\xe9\x82\xa2\x82\xcd\x8a\xe9\x8b\xc6\x82\xcc\x98g\x82\xf0\x92\xb4\x82\xa6\x82\xc4\x83`\x81[\x83\x80\x82\xc5
        ##\x82\xcc\x83h\x83L\x83\x85\x83\x81\x83\x93\x83g\x83\x8f\x81[\x83N\x82\xcc\x90\xb6\x8eY\x90\xab\x82\xf0\x8c\xfc\x8f\xe3\x82\xb3\x82\xb9\x82\xe9\x82\xb1\x82\xc6\x82\xaa\x82\xc5\x82\xab\x82\xdc\x82\xb7\x81B
        ##
        ##Adobe Acrobat 5.0\x82\xc5\x8d\xec\x90\xac\x82\xb5\x82\xbdAdobe PDF\x82\xcd\x81A(Acrobat 5.0\x82\xc5\x82\xcc\x82\xdd\x83T\x83|\x81[\x83g
        ##\x82\xb5\x82\xc4\x82\xa2\x82\xe9\x88\xc3\x8d\x86\x89\xbb\x90\xdd\x92\xe8\x82\xf0\x8f\x9c\x82\xa2\x82\xc4\x82\xcd)\x8f]\x97\x88\x82\xdc
        ##\x82\xc5\x82\xcc\x83o\x81[\x83W\x83\x87\x83\x93(3\x82\xa8\x82\xe6\x82\xd1\x82S)\x82\xccAcrobat Reader\x82\xc5\x82\xe0\x8aJ\x82\xad
        ##\x82\xb1\x82\xc6\x82\xaa\x82\xc5\x82\xab\x82\xdc\x82\xb7\x81B\x8f\xee\x95\xf1\x8b\xa4\x97L\x82\xcc\x83c\x81[\x83\x8b\x82\xc6\x82\xb5
        ##\x82\xc4\x81A\x82\xb3\x82\xe7\x82\xc9\x90i\x95\xe0\x82\xb5\x82\xbdAdobe Acrobat 5.0\x82\xf0\x81A\x8f]\x97\x88\x82\xcc\x8a\xc2\x8b\xab
        ##\x82\xc5\x82\xe0\x88\xc0\x90S\x82\xb5\x82\xc4\x82\xb2\x97\x98\x97p\x82\xa2\x82\xbd\x82\xbe\x82\xaf\x82\xdc\x82\xb7\x81B
        ##
        ##\x96{\x90\xbb\x95i\x82\xf0\x83l\x83b\x83g\x83\x8f\x81[\x83N\x82\xc8\x82\xc7\x82\xf0\x89\xee\x82\xb5\x82\xc4\x92\xbc\x90\xda\x82\xa0\x82\xe9
        ##\x82\xa2\x82\xcd\x8a\xd4\x90\xda\x82\xc9\x95\xa1\x90\x94\x82\xcc\x92[\x96\x96\x82\xa9\x82\xe7\x8eg\x97p\x82\xb7\x82\xe9\x8f\xea\x8d\x87\x81A
        ##\x82\xbb\x82\xcc\x92[\x96\x96\x82\xc6\x93\xaf\x90\x94\x82\xcc\x83\x89\x83C\x83Z\x83\x93\x83X\x82\xf0\x82\xb2\x8dw\x93\xfc\x82\xad\x82\xbe
        ##\x82\xb3\x82\xa2\x81B\x96{\x90\xbb\x95i\x82\xcd\x83N\x83\x89\x83C\x83A\x83\x93\x83g\x97p\x83\\\x83t\x83g\x83E\x83F\x83A\x82\xc5\x82\xa0\x82\xe8
        ##\x81A\x83T\x81[\x83o\x97p\x83\\\x83t\x83g\x83E\x83F\x83A\x82\xc6\x82\xb5\x82\xc4\x82\xa8\x8eg\x82\xa2\x82\xa2\x82\xbd\x82\xbe\x82\xad\x82\xb1\x82\xc6
        ##\x82\xcd\x81A\x8f\xe3\x8bL\x95\xfb\x96@\x82\xc9\x82\xe6\x82\xe9\x88\xc8\x8aO\x81A\x8b\x96\x91\xf8\x82\xb3\x82\xea\x82\xc4\x82\xa2\x82\xdc\x82\xb9
        ##\x82\xf1\x81B\x95\xa1\x90\x94\x82\xcc\x83\x89\x83C\x83Z\x83\x93\x83X\x82\xf0\x82\xb2\x8dw\x93\xfc\x82\xb3\x82\xea\x82\xe9\x8f\xea\x8d\x87\x82\xc9
        ##\x82\xcd\x83\x89\x83C\x83Z\x83\x93\x83X\x83v\x83\x8d\x83O\x83\x89\x83\x80\x82\xf0\x82\xb2\x97\x98\x97p\x82\xc9\x82\xc8\x82\xe9\x82\xc6\x82\xa8\x93\xbe\x82\xc5\x82\xb7\x81B
        ##
        ##
        ##\x81y\x82\xa8\x92m\x82\xe7\x82\xb9\x81zMicrosoft Office XP\x82\xa9\x82\xe7PDF\x82\xf0\x8d\xec\x90\xac\x82\xb7\x82\xe9\x82\xc9\x82\xcd
        ##"""
        ##        c.setFont('Helvetica', 24)
        ##        c.drawString(100,750, "Sample text from Adobe's web site")
        ##        tx = c.beginText(100,700)
        ##        tx.setFont('Helvetica', 10)
        ##        tx.textLine('Note: line wrapping has not been preserved and some lines may be wrapped in mid-word.')
        ##        tx.textLine('We are just testing that we see Japanese and not random characters!')
        ##        tx.setFont('HeiseiMin-W3-90ms-RKSJ-H',6)
        ##        tx.textLines(sample)
        ##        tx.setFont('Helvetica', 8)
        ##        tx.textLine()
        ##        tx.textLine()
        ##        tx.textLines("""
        ##            This test document shows Japanese output from the Reportlab PDF Library.
        ##            You may use two fonts, HeiseiMin-W3 and HeiseiKakuGo-W5, and a number of
        ##            different encodings.
        ##
        ##            The available encoding names (with comments from the PDF specification) are:
        ##            encodings_jpn = [
        ##                # official encoding names, comments taken verbatim from PDF Spec
        ##                '83pv-RKSJ-H',      #Macintosh, JIS X 0208 character set with KanjiTalk6
        ##                                    #extensions, Shift-JIS encoding, Script Manager code 1
        ##                '90ms-RKSJ-H',      #Microsoft Code Page 932 (lfCharSet 0x80), JIS X 0208
        ##                                    #character set with NEC and IBM extensions
        ##                '90ms-RKSJ-V',      #Vertical version of 90ms-RKSJ-H
        ##                '90msp-RKSJ-H',     #Same as 90ms-RKSJ-H, but replaces half-width Latin
        ##                                    #characters with proportional forms
        ##                '90msp-RKSJ-V',     #Vertical version of 90msp-RKSJ-H
        ##                '90pv-RKSJ-H',      #Macintosh, JIS X 0208 character set with KanjiTalk7
        ##                                    #extensions, Shift-JIS encoding, Script Manager code 1
        ##                'Add-RKSJ-H',       #JIS X 0208 character set with Fujitsu FMR extensions,
        ##                                    #Shift-JIS encoding
        ##                'Add-RKSJ-V',       #Vertical version of Add-RKSJ-H
        ##                'EUC-H',            #JIS X 0208 character set, EUC-JP encoding
        ##                'EUC-V',            #Vertical version of EUC-H
        ##                'Ext-RKSJ-H',       #JIS C 6226 (JIS78) character set with NEC extensions,
        ##                                    #Shift-JIS encoding
        ##                'Ext-RKSJ-V',       #Vertical version of Ext-RKSJ-H
        ##                'H',                #JIS X 0208 character set, ISO-2022-JP encoding,
        ##                'V',                #Vertical version of H
        ##                'UniJIS-UCS2-H',    #Unicode (UCS-2) encoding for the Adobe-Japan1 character
        ##                                    #collection
        ##                'UniJIS-UCS2-V',    #Vertical version of UniJIS-UCS2-H
        ##                'UniJIS-UCS2-HW-H', #Same as UniJIS-UCS2-H, but replaces proportional Latin
        ##                                    #characters with half-width forms
        ##                'UniJIS-UCS2-HW-V'  #Vertical version of UniJIS-UCS2-HW-H
        ##                ]
        ##
        ##            The next few pages show the complete character set available in the encoding
        ##            "90ms-RKSJ-H" - Shift-JIS with the standard Microsoft extensions.
        ##            """)
        ##        c.drawText(tx)
        ##
        ##        c.setFont('Helvetica',10)
        ##        c.drawCentredString(297, 36, 'Page %d' % c.getPageNumber())
        ##
        ##
        ##
        ##        c.showPage()

        from reportlab.lib import textsplit

        c.setFont('HeiseiMin-W3', 14)
        y = 700
        c.drawString(70, y, 'cannot end line')
        y -= 20
        for group in textsplit.CANNOT_START_LINE:
            c.drawString(70, y, group)
            y -= 20
            c.setFont('Helvetica', 10)
            c.drawString(70, y, ' '.join([ascii(x)[4:-1] for x in group]))
            c.setFont('HeiseiMin-W3', 14)
            y -= 20

        y -= 20
        c.drawString(70, y, 'cannot end line')
        y -= 20
        for group in textsplit.CANNOT_END_LINE:
            c.drawString(70, y, group)
            y -= 20
            c.setFont('Helvetica', 10)
            c.drawString(70, y, ' '.join([ascii(x)[2:] for x in group]))
            c.setFont('HeiseiMin-W3', 14)
            y -= 20

        c.showPage()

        #utf8 encoded paragraph
        sample2_uni = u'''\u30ac\u30c8\u30a6\u30a3\u30c3\u30af\u7a7a\u6e2f\u3068\u9023\u7d61\u901a
        \u8def\u3067\u76f4\u7d50\u3055\u308c\u3066\u3044\u308b\u552f\u4e00\u306e\u30db\u30c6\u30eb
        \u3067\u3042\u308b\u5f53\u30db\u30c6\u30eb\u306f\u3001\u8857\u306e\u4e2d\u5fc3\u90e8\u304b
        \u308930\u5206\u306e\u5834\u6240\u306b\u3054\u3056\u3044\u307e\u3059\u3002\u5168\u5ba2\u5ba4
        \u306b\u9ad8\u901f\u30a4\u30f3\u30bf\u30fc\u30cd\u30c3\u30c8\u74b0\u5883\u3092\u5b8c\u5099
        \u3057\u3066\u304a\u308a\u307e\u3059\u3002\u30d5\u30a1\u30df\u30ea\u30fc\u30eb\u30fc\u30e0
        \u306f5\u540d\u69d8\u307e\u3067\u304a\u6cca\u308a\u3044\u305f\u3060\u3051\u307e\u3059\u3002
        \u307e\u305f\u3001\u30a8\u30b0\u30bc\u30af\u30c6\u30a3\u30d6\u30eb\u30fc\u30e0\u306e\u304a
        \u5ba2\u69d8\u306f\u3001\u30a8\u30b0\u30bc\u30af\u30c6\u30a3\u30d6\u30e9\u30a6\u30f3\u30b8
        \u3092\u3054\u5229\u7528\u3044\u305f\u3060\u3051\u307e\u3059\u3002\u4e8b\u524d\u306b\u3054
        \u4e88\u7d04\u3044\u305f\u3060\u3051\u308b\u30bf\u30a4\u30e0\u30c8\u30a5\u30d5\u30e9\u30a4
        \u30fb\u30d1\u30c3\u30b1\u30fc\u30b8\u306b\u306f\u3001\u7a7a\u6e2f\u306e\u99d0\u8eca\u6599
        \u91d1\u304c\u542b\u307e\u308c\u3066\u304a\u308a\u307e\u3059\u3002'''

        oneline_uni = u''.join(sample2_uni.split())
        sample2_utf8 = oneline_uni.encode('utf8')

        from reportlab.platypus import Paragraph
        from reportlab.lib.styles import ParagraphStyle
        jsty = ParagraphStyle('japanese',
                              fontName='HeiseiMin-W3',
                              wordWrap='CJK')
        jpara = Paragraph(oneline_uni, style=jsty)

        c.drawString(
            100, 710,
            'Try to wrap a paragraph using a style with wordWrap="CJK"')
        w, h = jpara.wrap(400, 400)
        jpara.drawOn(c, 100, 700 - h)

        #now try to split it...
        c.drawString(100, 510,
                     'Now try to split a paragraph as if over a page break')

        topPara, bottomPara = jpara.split(400, 30)
        w1, h1 = topPara.wrap(400, 30)
        topPara.drawOn(c, 100, 450)

        w2, h2 = bottomPara.wrap(400, 30)
        bottomPara.drawOn(c, 100, 400)
        #print 'split into heights %0.2f, %0.2f' % (topPara.height, bottomPara.height)

        ##        c.showPage()
        ##
        ##
        ##        # full kuten chart in EUC
        ##        c.setFont('Helvetica', 24)
        ##        c.drawString(72,750, 'Characters available in JIS 0208-1997')
        ##        y = 600
        ##        for row in range(1, 95):
        ##            KutenRowCodeChart(row, 'HeiseiMin-W3','EUC-H').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.showPage()

        #try with Unicode truetype - Mincho for starters
        ##        import time
        ##        started = time.clock()
        ##        c.showPage()
        ##        c.setFont('Helvetica',16)
        ##        c.drawString(100,750, 'About to say Tokyo in MS Gothic...')
        ##
        ##        from reportlab.pdfbase.ttfonts import TTFont, TTFontFile
        ##        f = TTFontFile("msgothic.ttf")
        ##        print f.name
        ##
        ##        pdfmetrics.registerFont(TTFont(f.name, f))
        ##
        ##        utfText = u'Andr\202'.encode('utf8')
        ##        c.setFont(f.name,16)
        ##        c.drawString(100,700, utfText)
        ##
        ##
        ##        #tokyoUCS2 = '\x67\x71\x4E\xAC'
        ##        finished = time.clock()

        c.save()

        if VERBOSE:
            print('saved test_multibyte_jpn.pdf')
Example #35
0
    def test0(self):
        "A basic document drawing some strings"
        c = Canvas(outputfile('test_multibyte_jpn.pdf'))
        c.setFont('Helvetica', 30)
        c.drawString(100,700, 'Japanese Font Support')

        c.setStrokeColor(colors.red)


        #unicode font automatically supplies the encoding
        pdfmetrics.registerFont(UnicodeCIDFont('HeiseiMin-W3'))

        
        msg = u'\u6771\u4EAC : Unicode font, unicode input'
        self.hDraw(c, msg, 'HeiseiMin-W3', 100, 600)

        msg = u'\u6771\u4EAC : Unicode font, utf8 input'.encode('utf8')
        self.hDraw(c, msg, 'HeiseiMin-W3', 100, 575)




        # now try verticals - this is broken, not sure how to make it
        # work in post Unicode world.
        pdfmetrics.registerFont(CIDFont('HeiseiMin-W3','90ms-RKSJ-V'))
        c.setFont('HeiseiMin-W3-90ms-RKSJ-V', 16)
        c.drawString(450, 650, '\223\214\213\236 vertical Shift-JIS')
        height = c.stringWidth('\223\214\213\236 vertical Shift-JIS', 'HeiseiMin-W3-90ms-RKSJ-V', 16)
        c.rect(450-8,650,16,-height)

        pdfmetrics.registerFont(CIDFont('HeiseiMin-W3','EUC-V'))
        c.setFont('HeiseiMin-W3-EUC-V', 16)
        c.drawString(475, 650, '\xC5\xEC\xB5\xFE vertical EUC')
        height = c.stringWidth('\xC5\xEC\xB5\xFE vertical EUC', 'HeiseiMin-W3-EUC-V', 16)
        c.rect(475-8,650,16,-height)



        from reportlab.platypus.paragraph import Paragraph
        from reportlab.lib.styles import ParagraphStyle
        jStyle = ParagraphStyle('jtext',
                                fontName='HeiseiMin-W3',
                                fontSize=12,
                                wordWrap="CJK"
                                )
        
        gatwickText = '\xe3\x82\xac\xe3\x83\x88\xe3\x82\xa6\xe3\x82\xa3\xe3\x83\x83\xe3\x82\xaf\xe7\xa9\xba\xe6\xb8\xaf\xe3\x81\xa8\xe9\x80\xa3\xe7\xb5\xa1\xe9\x80\x9a\xe8\xb7\xaf\xe3\x81\xa7\xe7\x9b\xb4\xe7\xb5\x90\xe3\x81\x95\xe3\x82\x8c\xe3\x81\xa6\xe3\x81\x84\xe3\x82\x8b\xe5\x94\xaf\xe4\xb8\x80\xe3\x81\xae\xe3\x83\x9b\xe3\x83\x86\xe3\x83\xab\xe3\x81\xa7\xe3\x81\x82\xe3\x82\x8b\xe5\xbd\x93\xe3\x83\x9b\xe3\x83\x86\xe3\x83\xab\xe3\x81\xaf\xe3\x80\x81\xe8\xa1\x97\xe3\x81\xae\xe4\xb8\xad\xe5\xbf\x83\xe9\x83\xa8\xe3\x81\x8b\xe3\x82\x8930\xe5\x88\x86\xe3\x81\xae\xe5\xa0\xb4\xe6\x89\x80\xe3\x81\xab\xe3\x81\x94\xe3\x81\x96\xe3\x81\x84\xe3\x81\xbe\xe3\x81\x99\xe3\x80\x82\xe5\x85\xa8\xe5\xae\xa2\xe5\xae\xa4\xe3\x81\xab\xe9\xab\x98\xe9\x80\x9f\xe3\x82\xa4\xe3\x83\xb3\xe3\x82\xbf\xe3\x83\xbc\xe3\x83\x8d\xe3\x83\x83\xe3\x83\x88\xe7\x92\xb0\xe5\xa2\x83\xe3\x82\x92\xe5\xae\x8c\xe5\x82\x99\xe3\x81\x97\xe3\x81\xa6\xe3\x81\x8a\xe3\x82\x8a\xe3\x81\xbe\xe3\x81\x99\xe3\x80\x82\xe3\x83\x95\xe3\x82\xa1\xe3\x83\x9f\xe3\x83\xaa\xe3\x83\xbc\xe3\x83\xab\xe3\x83\xbc\xe3\x83\xa0\xe3\x81\xaf5\xe5\x90\x8d\xe6\xa7\x98\xe3\x81\xbe\xe3\x81\xa7\xe3\x81\x8a\xe6\xb3\x8a\xe3\x82\x8a\xe3\x81\x84\xe3\x81\x9f\xe3\x81\xa0\xe3\x81\x91\xe3\x81\xbe\xe3\x81\x99\xe3\x80\x82\xe3\x81\xbe\xe3\x81\x9f\xe3\x80\x81\xe3\x82\xa8\xe3\x82\xb0\xe3\x82\xbc\xe3\x82\xaf\xe3\x83\x86\xe3\x82\xa3\xe3\x83\x96\xe3\x83\xab\xe3\x83\xbc\xe3\x83\xa0\xe3\x81\xae\xe3\x81\x8a\xe5\xae\xa2\xe6\xa7\x98\xe3\x81\xaf\xe3\x80\x81\xe3\x82\xa8\xe3\x82\xb0\xe3\x82\xbc\xe3\x82\xaf\xe3\x83\x86\xe3\x82\xa3\xe3\x83\x96\xe3\x83\xa9\xe3\x82\xa6\xe3\x83\xb3\xe3\x82\xb8\xe3\x82\x92\xe3\x81\x94\xe5\x88\xa9\xe7\x94\xa8\xe3\x81\x84\xe3\x81\x9f\xe3\x81\xa0\xe3\x81\x91\xe3\x81\xbe\xe3\x81\x99\xe3\x80\x82\xe4\xba\x8b\xe5\x89\x8d\xe3\x81\xab\xe3\x81\x94\xe4\xba\x88\xe7\xb4\x84\xe3\x81\x84\xe3\x81\x9f\xe3\x81\xa0\xe3\x81\x91\xe3\x82\x8b\xe3\x82\xbf\xe3\x82\xa4\xe3\x83\xa0\xe3\x83\x88\xe3\x82\xa5\xe3\x83\x95\xe3\x83\xa9\xe3\x82\xa4\xe3\x83\xbb\xe3\x83\x91\xe3\x83\x83\xe3\x82\xb1\xe3\x83\xbc\xe3\x82\xb8\xe3\x81\xab\xe3\x81\xaf\xe3\x80\x81\xe7\xa9\xba\xe6\xb8\xaf\xe3\x81\xae\xe9\xa7\x90\xe8\xbb\x8a\xe6\x96\x99\xe9\x87\x91\xe3\x81\x8c\xe5\x90\xab\xe3\x81\xbe\xe3\x82\x8c\xe3\x81\xa6\xe3\x81\x8a\xe3\x82\x8a\xe3\x81\xbe\xe3\x81\x99\xe3\x80\x82'
        gatwickText2= '\xe3\x82\xac\xe3\x83\x88\xe3\x82\xa6\xe3\x82\xa3\xe3\x83\x83\xe3\x82\xaf<font color=red>\xe7\xa9\xba\xe6\xb8\xaf\xe3\x81\xa8\xe9\x80\xa3\xe7\xb5\xa1\xe9\x80\x9a\xe8\xb7\xaf\xe3\x81\xa7\xe7\x9b\xb4\xe7\xb5\x90</font>\xe3\x81\x95\xe3\x82\x8c\xe3\x81\xa6\xe3\x81\x84\xe3\x82\x8b\xe5\x94\xaf\xe4\xb8\x80\xe3\x81\xae\xe3\x83\x9b\xe3\x83\x86\xe3\x83\xab\xe3\x81\xa7\xe3\x81\x82\xe3\x82\x8b\xe5\xbd\x93\xe3\x83\x9b\xe3\x83\x86\xe3\x83\xab\xe3\x81\xaf\xe3\x80\x81\xe8\xa1\x97\xe3\x81\xae\xe4\xb8\xad\xe5\xbf\x83\xe9\x83\xa8\xe3\x81\x8b\xe3\x82\x8930\xe5\x88\x86\xe3\x81\xae\xe5\xa0\xb4\xe6\x89\x80\xe3\x81\xab\xe3\x81\x94\xe3\x81\x96\xe3\x81\x84\xe3\x81\xbe\xe3\x81\x99\xe3\x80\x82\xe5\x85\xa8\xe5\xae\xa2\xe5\xae\xa4\xe3\x81\xab\xe9\xab\x98\xe9\x80\x9f\xe3\x82\xa4\xe3\x83\xb3\xe3\x82\xbf\xe3\x83\xbc\xe3\x83\x8d\xe3\x83\x83\xe3\x83\x88<link fg="blue" href="http://www.reportlab.com">\xe7\x92\xb0\xe5\xa2\x83\xe3\x82\x92\xe5\xae\x8c\xe5\x82\x99</link>\xe3\x81\x97\xe3\x81\xa6<u>\xe3\x81\x8a\xe3\x82\x8a\xe3\x81\xbe\xe3\x81\x99</u>\xe3\x80\x82\xe3\x83\x95\xe3\x82\xa1\xe3\x83\x9f\xe3\x83\xaa\xe3\x83\xbc\xe3\x83\xab\xe3\x83\xbc\xe3\x83\xa0\xe3\x81\xaf5\xe5\x90\x8d\xe6\xa7\x98\xe3\x81\xbe\xe3\x81\xa7\xe3\x81\x8a\xe6\xb3\x8a\xe3\x82\x8a\xe3\x81\x84\xe3\x81\x9f\xe3\x81\xa0\xe3\x81\x91\xe3\x81\xbe\xe3\x81\x99\xe3\x80\x82\xe3\x81\xbe\xe3\x81\x9f\xe3\x80\x81\xe3\x82\xa8\xe3\x82\xb0\xe3\x82\xbc\xe3\x82\xaf\xe3\x83\x86\xe3\x82\xa3\xe3\x83\x96\xe3\x83\xab\xe3\x83\xbc\xe3\x83\xa0\xe3\x81\xae\xe3\x81\x8a\xe5\xae\xa2\xe6\xa7\x98\xe3\x81\xaf\xe3\x80\x81\xe3\x82\xa8\xe3\x82\xb0\xe3\x82\xbc\xe3\x82\xaf\xe3\x83\x86\xe3\x82\xa3\xe3\x83\x96\xe3\x83\xa9\xe3\x82\xa6\xe3\x83\xb3\xe3\x82\xb8\xe3\x82\x92\xe3\x81\x94\xe5\x88\xa9\xe7\x94\xa8\xe3\x81\x84\xe3\x81\x9f\xe3\x81\xa0\xe3\x81\x91\xe3\x81\xbe\xe3\x81\x99\xe3\x80\x82\xe4\xba\x8b\xe5\x89\x8d\xe3\x81\xab\xe3\x81\x94\xe4\xba\x88\xe7\xb4\x84\xe3\x81\x84\xe3\x81\x9f\xe3\x81\xa0\xe3\x81\x91\xe3\x82\x8b\xe3\x82\xbf\xe3\x82\xa4\xe3\x83\xa0\xe3\x83\x88\xe3\x82\xa5\xe3\x83\x95\xe3\x83\xa9\xe3\x82\xa4\xe3\x83\xbb\xe3\x83\x91\xe3\x83\x83\xe3\x82\xb1\xe3\x83\xbc\xe3\x82\xb8\xe3\x81\xab\xe3\x81\xaf\xe3\x80\x81\xe7\xa9\xba\xe6\xb8\xaf\xe3\x81\xae\xe9\xa7\x90\xe8\xbb\x8a\xe6\x96\x99\xe9\x87\x91\xe3\x81\x8c\xe5\x90\xab\xe3\x81\xbe\xe3\x82\x8c\xe3\x81\xa6\xe3\x81\x8a\xe3\x82\x8a\xe3\x81\xbe\xe3\x81\x99\xe3\x80\x82'

        c.setFont('HeiseiMin-W3', 12)
        jPara = Paragraph(gatwickText, jStyle)
        jPara.wrap(300, 200)
        jPara.drawOn(c, 100, 220)

        jPara = Paragraph(gatwickText2, jStyle)
        jPara.wrap(300, 200)
        jPara.drawOn(c, 100, 320)

        c.setFillColor(colors.purple)
        tx = c.beginText(100, 200)
        tx.setFont('Helvetica', 12)
        tx.textLines("""This document shows sample output in Japanese
        from the Reportlab PDF library.  This page shows the two fonts
        available and tests our ability to measure the width of glyphs
        in both horizontal and vertical writing, with proportional and
        fixed-width characters. The red boxes should be the same width
        (or height) as the character strings they surround.
        The next pages show more samples and information.
        """)
        c.drawText(tx)
        c.setFont('Helvetica',10)
        c.drawCentredString(297, 36, 'Page %d' % c.getPageNumber())



        c.showPage()

        c.setFont('Helvetica', 30)
        c.drawString(100,700, 'Japanese TrueType Font Support')
        msg = u'\u6771\u4EAC : Unicode font'.encode('utf8')
        msg2 = u'utf8 input 0123456789 ABCDEF'.encode('utf8')
        from reportlab.pdfbase.ttfonts import TTFont
        try:
            msmincho = TTFont('MS Mincho','msmincho.ttc',subfontIndex=0,asciiReadable=0)
            fn = ' file=msmincho.ttc subfont 0'
        except:
            try:
                msmincho = TTFont('MS Mincho','msmincho.ttf',asciiReadable=0)
                fn = 'file=msmincho.ttf'
            except:
                #Ubuntu - works on Lucid Lynx if xpdf-japanese installed
                try:
                    msmincho = TTFont('MS Mincho','ttf-japanese-mincho.ttf')
                    fn = 'file=msmincho.ttf'
                except:
                    msmincho = None
        if msmincho is None:
            c.setFont('Helvetica', 12)
            c.drawString(100,600, 'Cannot find msmincho.ttf or msmincho.ttc')
        else:
            pdfmetrics.registerFont(msmincho)
            c.setFont('MS Mincho', 30)
            c.drawString(100,600, msg)
            c.drawString(100,570, msg2)
            c.drawString(100,540, fn)
            if fn.endswith('0'):
                try:
                    msmincho1 = TTFont('MS Mincho 1','msmincho.ttc',subfontIndex=1,asciiPreload=0)
                    pdfmetrics.registerFont(msmincho1)
                    fn = ' file=msmincho.ttc subfont 1'
                    c.setFont('MS Mincho 1',30)
                    c.drawString(100,500,msg+fn)
                except:
                    c.setFont('Helvetica',30)
                    c.drawString(100,500,msg)
                c.drawString(100,470, msg2)
                c.drawString(100,440, fn)
            #test a paragraph with CJK and <br/> tags
            u = u'''<font color=red>\u30ac\u30c8\u30a6\u30a3\u30c3</font><br/><font color=blue>\u30af\u7a7a\u6e2f\u3068\u9023\u7d61\u901a</font><br/>\u8def\u3067\u76f4\u7d50\u3055\u308c\u3066\u3044\u308b\u552f<br/>\u4e00\u306e\u30db\u30c6\u30eb\u3067\u3042\u308b\u5f53\u30db\u30c6\u30eb\u306f\u3001\u8857\u306e\u4e2d\u5fc3\u90e8\u304b\u308930\u5206\u306e\u5834\u6240\u306b\u3054\u3056\u3044\u307e\u3059\u3002\u5168\u5ba2\u5ba4\u306b\u9ad8\u901f\u30a4\u30f3\u30bf\u30fc\u30cd\u30c3\u30c8<br/>\u74b0\u5883\u3092\u5b8c\u5099\u3057\u3066\u304a\u308a\u307e\u3059\u3002\u30d5\u30a1\u30df\u30ea\u30fc\u30eb\u30fc\u30e0\u306f5\u540d\u69d8\u307e\u3067\u304a\u6cca\u308a\u3044\u305f\u3060\u3051\u307e\u3059\u3002\u307e\u305f\u3001\u30a8\u30b0\u30bc\u30af\u30c6\u30a3\u30d6\u30eb\u30fc\u30e0\u306e\u304a\u5ba2\u69d8\u306f\u3001\u30a8\u30b0\u30bc\u30af\u30c6\u30a3\u30d6\u30e9\u30a6\u30f3\u30b8\u3092\u3054\u5229\u7528\u3044\u305f\u3060\u3051\u307e\u3059\u3002\u4e8b\u524d\u306b\u3054\u4e88\u7d04\u3044\u305f\u3060\u3051\u308b\u30bf\u30a4\u30e0\u30c8\u30a5\u30d5\u30e9\u30a4\u30fb\u30d1\u30c3\u30b1\u30fc\u30b8\u306b\u306f\u3001\u7a7a\u6e2f\u306e\u99d0\u8eca\u6599\u91d1\u304c\u542b\u307e\u308c\u3066\u304a\u308a\u307e\u3059\u3002'''
            jPara = Paragraph(u, jStyle)
            jPara.wrap(300, 500)
            jPara.drawOn(c, 100, 300)

        c.showPage()

        # realistic text sample
##        sample = """Adobe Acrobat
##\x83h\x83L\x83\x85\x83\x81\x83\x93\x83g\x82\xaa\x8aJ\x82\xa9\x82\xc8\x82\xad\x82\xc4\x8d\xa2\x82\xc1\x82\xbd\x82\xb1\x82\xc6\x82\xcd
##\x82\xa0\x82\xe8\x82\xdc\x82\xb9\x82\xf1\x82\xa9\x81B\x8e\x96\x8b\xc6\x8cv\x89\xe6\x8f\x91\x81A\x89c\x8b\xc6\x83\x8c\x83|\x81[\x83g
##\x81A\x83J\x83^\x83\x8d\x83O\x82\xe2\x83p\x83\x93\x83t\x83\x8c\x83b\x83g\x82\xc8\x82\xc7\x90\xa7\x8d\xec\x95\xa8\x82\xcc\x8e\xed
##\x97\xde\x82\xc9\x82\xa9\x82\xa9\x82\xed\x82\xe7\x82\xb8\x81A
##\x83h\x83L\x83\x85\x83\x81\x83\x93\x83g\x82\xcdAdobe&reg; Acrobat&reg; 5.0\x82\xf0\x8eg\x82\xc1\x82\xc4Adobe PDF\x81iPortable Document
##Format\x81j\x83t\x83@\x83C\x83\x8b\x82\xc9\x95\xcf\x8a\xb7\x82\xb5\x82\xdc\x82\xb5\x82\xe5\x82\xa4\x81B\x96\xb3\x8f\x9e\x94z\x95z\x82\xcc
##Adobe Acrobat Reader\x82\xf0\x8eg\x82\xa6\x82\xce\x81A\x83n\x81[\x83h\x83E\x83F\x83A\x81A\x83\\\x83t\x83g\x83E\x83F\x83A\x82\xc9\x82\xa9
##\x82\xa9\x82\xed\x82\xe7\x82\xb8\x81A\x92N\x82\xc5\x82\xe0\x82\xa0\x82\xc8\x82\xbd\x82\xcc\x83h\x83L\x83\x85\x83\x81\x83\x93\x83g\x82\xf0
##\x83I\x83\x8a\x83W\x83i\x83\x8b\x82\xcc\x91\xcc\x8d\xd9\x82\xc5\x8aJ\x82\xad\x82\xb1\x82\xc6\x82\xaa\x82\xc5\x82\xab\x82\xdc\x82\xb7\x81B
##\x82\xa0\x82\xc8\x82\xbd\x82\xcc\x88\xd3\x90}\x82\xb5\x82\xbd\x82\xc6\x82\xa8\x82\xe8\x82\xc9\x8f\xee\x95\xf1\x82\xf0\x93`\x82\xa6\x82\xe9
##\x82\xb1\x82\xc6\x82\xaa\x82\xc5\x82\xab\x82\xdc\x82\xb7\x81B
##\x82\xb3\x82\xe7\x82\xc9\x81AAdobe Acrobat 5.0\x82\xc5\x82\xcd\x81AWeb\x83u\x83\x89\x83E\x83U\x82\xa9\x82\xe7\x83R\x83\x81\x83\x93\x83g\x82\xe2
##\x83}\x81[\x83N\x83A\x83b\x83v\x82\xf0\x8f\x91\x82\xab\x8d\x9e\x82\xf1\x82\xbe\x82\xe8\x81A\x93d\x8eq\x8f\x90\x96\xbc\x82\xf0\x8f\x91\x82\xab
##\x8d\x9e\x82\xdd\x81A\x8c\xb4\x96{\x82\xc6\x82\xb5\x82\xc4\x83\x8d\x81[\x83J\x83\x8b\x82\xc9\x95\xdb\x91\xb6\x82\xb7\x82\xe9\x82\xb1\x82\xc6\x82\xe0\x89\xc2\x94\\\x82\xc5\x82\xb7\x81B
##\x8a\xe9\x8b\xc6\x93\xe0\x82\xa0\x82\xe9\x82\xa2\x82\xcd\x8a\xe9\x8b\xc6\x82\xcc\x98g\x82\xf0\x92\xb4\x82\xa6\x82\xc4\x83`\x81[\x83\x80\x82\xc5
##\x82\xcc\x83h\x83L\x83\x85\x83\x81\x83\x93\x83g\x83\x8f\x81[\x83N\x82\xcc\x90\xb6\x8eY\x90\xab\x82\xf0\x8c\xfc\x8f\xe3\x82\xb3\x82\xb9\x82\xe9\x82\xb1\x82\xc6\x82\xaa\x82\xc5\x82\xab\x82\xdc\x82\xb7\x81B
##
##Adobe Acrobat 5.0\x82\xc5\x8d\xec\x90\xac\x82\xb5\x82\xbdAdobe PDF\x82\xcd\x81A(Acrobat 5.0\x82\xc5\x82\xcc\x82\xdd\x83T\x83|\x81[\x83g
##\x82\xb5\x82\xc4\x82\xa2\x82\xe9\x88\xc3\x8d\x86\x89\xbb\x90\xdd\x92\xe8\x82\xf0\x8f\x9c\x82\xa2\x82\xc4\x82\xcd)\x8f]\x97\x88\x82\xdc
##\x82\xc5\x82\xcc\x83o\x81[\x83W\x83\x87\x83\x93(3\x82\xa8\x82\xe6\x82\xd1\x82S)\x82\xccAcrobat Reader\x82\xc5\x82\xe0\x8aJ\x82\xad
##\x82\xb1\x82\xc6\x82\xaa\x82\xc5\x82\xab\x82\xdc\x82\xb7\x81B\x8f\xee\x95\xf1\x8b\xa4\x97L\x82\xcc\x83c\x81[\x83\x8b\x82\xc6\x82\xb5
##\x82\xc4\x81A\x82\xb3\x82\xe7\x82\xc9\x90i\x95\xe0\x82\xb5\x82\xbdAdobe Acrobat 5.0\x82\xf0\x81A\x8f]\x97\x88\x82\xcc\x8a\xc2\x8b\xab
##\x82\xc5\x82\xe0\x88\xc0\x90S\x82\xb5\x82\xc4\x82\xb2\x97\x98\x97p\x82\xa2\x82\xbd\x82\xbe\x82\xaf\x82\xdc\x82\xb7\x81B
##
##\x96{\x90\xbb\x95i\x82\xf0\x83l\x83b\x83g\x83\x8f\x81[\x83N\x82\xc8\x82\xc7\x82\xf0\x89\xee\x82\xb5\x82\xc4\x92\xbc\x90\xda\x82\xa0\x82\xe9
##\x82\xa2\x82\xcd\x8a\xd4\x90\xda\x82\xc9\x95\xa1\x90\x94\x82\xcc\x92[\x96\x96\x82\xa9\x82\xe7\x8eg\x97p\x82\xb7\x82\xe9\x8f\xea\x8d\x87\x81A
##\x82\xbb\x82\xcc\x92[\x96\x96\x82\xc6\x93\xaf\x90\x94\x82\xcc\x83\x89\x83C\x83Z\x83\x93\x83X\x82\xf0\x82\xb2\x8dw\x93\xfc\x82\xad\x82\xbe
##\x82\xb3\x82\xa2\x81B\x96{\x90\xbb\x95i\x82\xcd\x83N\x83\x89\x83C\x83A\x83\x93\x83g\x97p\x83\\\x83t\x83g\x83E\x83F\x83A\x82\xc5\x82\xa0\x82\xe8
##\x81A\x83T\x81[\x83o\x97p\x83\\\x83t\x83g\x83E\x83F\x83A\x82\xc6\x82\xb5\x82\xc4\x82\xa8\x8eg\x82\xa2\x82\xa2\x82\xbd\x82\xbe\x82\xad\x82\xb1\x82\xc6
##\x82\xcd\x81A\x8f\xe3\x8bL\x95\xfb\x96@\x82\xc9\x82\xe6\x82\xe9\x88\xc8\x8aO\x81A\x8b\x96\x91\xf8\x82\xb3\x82\xea\x82\xc4\x82\xa2\x82\xdc\x82\xb9
##\x82\xf1\x81B\x95\xa1\x90\x94\x82\xcc\x83\x89\x83C\x83Z\x83\x93\x83X\x82\xf0\x82\xb2\x8dw\x93\xfc\x82\xb3\x82\xea\x82\xe9\x8f\xea\x8d\x87\x82\xc9
##\x82\xcd\x83\x89\x83C\x83Z\x83\x93\x83X\x83v\x83\x8d\x83O\x83\x89\x83\x80\x82\xf0\x82\xb2\x97\x98\x97p\x82\xc9\x82\xc8\x82\xe9\x82\xc6\x82\xa8\x93\xbe\x82\xc5\x82\xb7\x81B
##
##
##\x81y\x82\xa8\x92m\x82\xe7\x82\xb9\x81zMicrosoft Office XP\x82\xa9\x82\xe7PDF\x82\xf0\x8d\xec\x90\xac\x82\xb7\x82\xe9\x82\xc9\x82\xcd
##"""
##        c.setFont('Helvetica', 24)
##        c.drawString(100,750, "Sample text from Adobe's web site")
##        tx = c.beginText(100,700)
##        tx.setFont('Helvetica', 10)
##        tx.textLine('Note: line wrapping has not been preserved and some lines may be wrapped in mid-word.')
##        tx.textLine('We are just testing that we see Japanese and not random characters!')
##        tx.setFont('HeiseiMin-W3-90ms-RKSJ-H',6)
##        tx.textLines(sample)
##        tx.setFont('Helvetica', 8)
##        tx.textLine()
##        tx.textLine()
##        tx.textLines("""
##            This test document shows Japanese output from the Reportlab PDF Library.
##            You may use two fonts, HeiseiMin-W3 and HeiseiKakuGo-W5, and a number of
##            different encodings.
##
##            The available encoding names (with comments from the PDF specification) are:
##            encodings_jpn = [
##                # official encoding names, comments taken verbatim from PDF Spec
##                '83pv-RKSJ-H',      #Macintosh, JIS X 0208 character set with KanjiTalk6
##                                    #extensions, Shift-JIS encoding, Script Manager code 1
##                '90ms-RKSJ-H',      #Microsoft Code Page 932 (lfCharSet 0x80), JIS X 0208
##                                    #character set with NEC and IBM extensions
##                '90ms-RKSJ-V',      #Vertical version of 90ms-RKSJ-H
##                '90msp-RKSJ-H',     #Same as 90ms-RKSJ-H, but replaces half-width Latin
##                                    #characters with proportional forms
##                '90msp-RKSJ-V',     #Vertical version of 90msp-RKSJ-H
##                '90pv-RKSJ-H',      #Macintosh, JIS X 0208 character set with KanjiTalk7
##                                    #extensions, Shift-JIS encoding, Script Manager code 1
##                'Add-RKSJ-H',       #JIS X 0208 character set with Fujitsu FMR extensions,
##                                    #Shift-JIS encoding
##                'Add-RKSJ-V',       #Vertical version of Add-RKSJ-H
##                'EUC-H',            #JIS X 0208 character set, EUC-JP encoding
##                'EUC-V',            #Vertical version of EUC-H
##                'Ext-RKSJ-H',       #JIS C 6226 (JIS78) character set with NEC extensions,
##                                    #Shift-JIS encoding
##                'Ext-RKSJ-V',       #Vertical version of Ext-RKSJ-H
##                'H',                #JIS X 0208 character set, ISO-2022-JP encoding,
##                'V',                #Vertical version of H
##                'UniJIS-UCS2-H',    #Unicode (UCS-2) encoding for the Adobe-Japan1 character
##                                    #collection
##                'UniJIS-UCS2-V',    #Vertical version of UniJIS-UCS2-H
##                'UniJIS-UCS2-HW-H', #Same as UniJIS-UCS2-H, but replaces proportional Latin
##                                    #characters with half-width forms
##                'UniJIS-UCS2-HW-V'  #Vertical version of UniJIS-UCS2-HW-H
##                ]
##
##            The next few pages show the complete character set available in the encoding
##            "90ms-RKSJ-H" - Shift-JIS with the standard Microsoft extensions.
##            """)
##        c.drawText(tx)
##
##        c.setFont('Helvetica',10)
##        c.drawCentredString(297, 36, 'Page %d' % c.getPageNumber())
##
##
##
##        c.showPage()

        from reportlab.lib import textsplit
        
        c.setFont('HeiseiMin-W3', 14)
        y = 700
        c.drawString(70, y, 'cannot end line')
        y -= 20
        for group in textsplit.CANNOT_START_LINE:
            c.drawString(70, y, group)
            y -= 20
            c.setFont('Helvetica',10)
            c.drawString(70, y, ' '.join([ascii(x)[4:-1] for x in group]))
            c.setFont('HeiseiMin-W3', 14)
            y -= 20



        y -= 20            
        c.drawString(70, y, 'cannot end line')
        y -= 20
        for group in textsplit.CANNOT_END_LINE:
            c.drawString(70, y, group)
            y -= 20
            c.setFont('Helvetica',10)
            c.drawString(70, y, ' '.join([ascii(x)[2:] for x in group]))
            c.setFont('HeiseiMin-W3', 14)
            y -= 20

        c.showPage()

        #utf8 encoded paragraph
        sample2_uni = u'''\u30ac\u30c8\u30a6\u30a3\u30c3\u30af\u7a7a\u6e2f\u3068\u9023\u7d61\u901a
        \u8def\u3067\u76f4\u7d50\u3055\u308c\u3066\u3044\u308b\u552f\u4e00\u306e\u30db\u30c6\u30eb
        \u3067\u3042\u308b\u5f53\u30db\u30c6\u30eb\u306f\u3001\u8857\u306e\u4e2d\u5fc3\u90e8\u304b
        \u308930\u5206\u306e\u5834\u6240\u306b\u3054\u3056\u3044\u307e\u3059\u3002\u5168\u5ba2\u5ba4
        \u306b\u9ad8\u901f\u30a4\u30f3\u30bf\u30fc\u30cd\u30c3\u30c8\u74b0\u5883\u3092\u5b8c\u5099
        \u3057\u3066\u304a\u308a\u307e\u3059\u3002\u30d5\u30a1\u30df\u30ea\u30fc\u30eb\u30fc\u30e0
        \u306f5\u540d\u69d8\u307e\u3067\u304a\u6cca\u308a\u3044\u305f\u3060\u3051\u307e\u3059\u3002
        \u307e\u305f\u3001\u30a8\u30b0\u30bc\u30af\u30c6\u30a3\u30d6\u30eb\u30fc\u30e0\u306e\u304a
        \u5ba2\u69d8\u306f\u3001\u30a8\u30b0\u30bc\u30af\u30c6\u30a3\u30d6\u30e9\u30a6\u30f3\u30b8
        \u3092\u3054\u5229\u7528\u3044\u305f\u3060\u3051\u307e\u3059\u3002\u4e8b\u524d\u306b\u3054
        \u4e88\u7d04\u3044\u305f\u3060\u3051\u308b\u30bf\u30a4\u30e0\u30c8\u30a5\u30d5\u30e9\u30a4
        \u30fb\u30d1\u30c3\u30b1\u30fc\u30b8\u306b\u306f\u3001\u7a7a\u6e2f\u306e\u99d0\u8eca\u6599
        \u91d1\u304c\u542b\u307e\u308c\u3066\u304a\u308a\u307e\u3059\u3002'''

        oneline_uni = u''.join(sample2_uni.split())
        sample2_utf8 = oneline_uni.encode('utf8')

        from reportlab.platypus import Paragraph
        from reportlab.lib.styles import ParagraphStyle
        jsty = ParagraphStyle('japanese',fontName='HeiseiMin-W3', wordWrap='CJK')
        jpara = Paragraph(oneline_uni, style=jsty)

        c.drawString(100, 710, 'Try to wrap a paragraph using a style with wordWrap="CJK"')
        w, h = jpara.wrap(400,400)
        jpara.drawOn(c, 100, 700 - h)

        #now try to split it...
        c.drawString(100, 510, 'Now try to split a paragraph as if over a page break')

        topPara, bottomPara = jpara.split(400, 30)
        w1, h1 = topPara.wrap(400, 30)
        topPara.drawOn(c, 100, 450)

        w2, h2 = bottomPara.wrap(400, 30)
        bottomPara.drawOn(c, 100, 400)
        #print 'split into heights %0.2f, %0.2f' % (topPara.height, bottomPara.height) 
        
    


##        c.showPage()
##
##
##        # full kuten chart in EUC
##        c.setFont('Helvetica', 24)
##        c.drawString(72,750, 'Characters available in JIS 0208-1997')
##        y = 600
##        for row in range(1, 95):
##            KutenRowCodeChart(row, 'HeiseiMin-W3','EUC-H').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.showPage()


        #try with Unicode truetype - Mincho for starters
##        import time
##        started = time.clock()
##        c.showPage()
##        c.setFont('Helvetica',16)
##        c.drawString(100,750, 'About to say Tokyo in MS Gothic...')
##
##        from reportlab.pdfbase.ttfonts import TTFont, TTFontFile
##        f = TTFontFile("msgothic.ttf")
##        print f.name
##        
##        pdfmetrics.registerFont(TTFont(f.name, f))
##        
##        utfText = u'Andr\202'.encode('utf8')
##        c.setFont(f.name,16)
##        c.drawString(100,700, utfText)
##
##
##        #tokyoUCS2 = '\x67\x71\x4E\xAC'
##        finished = time.clock()
        
        



        c.save()


        if VERBOSE:
            print('saved test_multibyte_jpn.pdf')
Example #36
0
def _patternSequenceCheck(pattern_sequence):
    allowedTypes = strTypes if isinstance(strTypes, tuple) else (strTypes,)
    allowedTypes = allowedTypes + (PDFObject,PDFPatternIf)
    for x in pattern_sequence:
        if not isinstance(x,allowedTypes):
            if len(x)!=1:
                raise ValueError("sequence elts must be strings/bytes/PDFPatternIfs or singletons containing strings: "+ascii(x))
            if not isinstance(x[0],strTypes):
                raise ValueError("Singletons must contain strings/bytes or PDFObject instances only: "+ascii(x[0]))