def embedded_font_demo():
    my_canvas = canvas.Canvas("embed_font.pdf",
                              pagesize=letter)
    reportlab_folder = os.path.dirname(reportlab.__file__)
    fonts_folder = os.path.join(reportlab_folder, 'fonts')
    print('ReportLab font folder is located at {}'.format(
        fonts_folder))

    afm = os.path.join(fonts_folder, 'DarkGardenMK.afm')
    pfb = os.path.join(fonts_folder, 'DarkGardenMK.pfb')

    # Register the font so we can use it
    font_face = pdfmetrics.EmbeddedType1Face(afm, pfb)
    pdfmetrics.registerTypeFace(font_face)

    face_name = 'DarkGardenMK'
    font = pdfmetrics.Font('DarkGardenMK',
                           face_name,
                           'WinAnsiEncoding')
    pdfmetrics.registerFont(font)

    # Use the font!
    my_canvas.setFont('DarkGardenMK', 40)
    my_canvas.drawString(10, 730, 'The DarkGardenMK font')
    my_canvas.save()
Exemplo n.º 2
0
def register_font(font_name, family=""):
    try:
        return _registered_font_names[font_name]
    except KeyError:
        pass

    found = ff.getFontsWithAttributes(name=font_name)
    if not found:
        # print '%(font_name)s not found, loading default for rl_config %(res)s' % locals()
        res = rl_config.defaultGraphicsFontName
    else:
        descr = found[0]
        if descr.typeCode == "ttf":
            font = TTFont(descr.name, descr.fileName)
        else:
            face = pdfmetrics.EmbeddedType1Face(descr.metricsFileName, descr.fileName)
            pdfmetrics.registerTypeFace(face)
            font = pdfmetrics.Font(font_name, font_name, rl_config.defaultEncoding)
        pdfmetrics.registerFont(font)
        res = font_name
    if 10:
        from reportlab.lib.fonts import addMapping

        bold = int("Bold" in font_name)
        italic = int("Italic" in font_name)
        addMapping(family or font_name, bold, italic, font_name)
    _registered_font_names[font_name] = res
    return res
Exemplo n.º 3
0
 def __makeParaStyles(self):
     psn = '_%s__paraStyles' % self.__class__.__name__
     if not hasattr(self.__class__,psn):
         from reportlab.pdfbase import pdfmetrics
         fontDir = self.getFontDir()
         if fontDir is None:
             fontName = 'Helvetica-Bold'
         else:
             face = pdfmetrics.EmbeddedType1Face(os.path.join(fontDir,'eurosbe2.afm'),os.path.join(fontDir,'eurosbe2.pfb'))
             pdfmetrics.registerTypeFace(face)
             fontName = "Eurostile-BoldExtendedTwo"
         from reportlab.lib.enums import TA_LEFT, TA_CENTER, TA_RIGHT, TA_JUSTIFY
         from reportlab.lib.colors import white, PCMYKColor
         from reportlab.lib import colors
         colors.fidblue = fidblue = PCMYKColor(60,40,0,20,spotName='FidelityBlue',density=100)
         colors.fidlightblue = PCMYKColor(12.1568,8.2353,0,3.9216,spotName='FidelityLightBlue',density=100)
         S = []
         a = S.append
         normal = getSampleStyleSheet()['Normal']
         a(ParagraphStyle('ct0',normal, fontName=fontName, fontSize=12,leading=14.4, spaceAfter=6, spacebefore=6,textColor=fidblue))
         a(ParagraphStyle('ct1',normal, alignment=TA_CENTER, fontName="Helvetica-Bold", fontSize=7, textColor=white, leading=1.2*7))
         a(ParagraphStyle('ct2',normal, alignment=TA_CENTER, fontName="Helvetica", fontSize=6, leading=8))
         a(ParagraphStyle('ct3',normal, alignment=TA_JUSTIFY, fontName="Helvetica", fontSize=5.5, leading=6))
         a(ParagraphStyle('ct4',normal, fontName="Helvetica-Bold", fontSize=7, textColor=white,leading=7*1.2))
         a(ParagraphStyle('ct5',normal, alignment=TA_LEFT, fontName="Helvetica", fontSize=5, leading=5.5))
         a(ParagraphStyle('ct6',normal, alignment=TA_RIGHT, fontName="Helvetica", fontSize=5, leading=5.5))
         a(ParagraphStyle('ct7',normal, alignment=TA_CENTER, fontName="Helvetica", fontSize=5, leading=5.5))
         a(ParagraphStyle('ct8',normal, alignment=TA_JUSTIFY, fontName="Helvetica", fontSize=5.5, leading=6.0))
         a(ParagraphStyle('ct9',normal, alignment=TA_CENTER, fontName="Helvetica-Bold", fontSize=6, leading=1.2*6))
         setattr(self.__class__,psn,S)
Exemplo n.º 4
0
    def __init__(self, path, margin_x=48, margin_y=60, file_name='Untitled.pdf',
                 file_name_S3='Untitled.pdf', is_landscape=False, author=None, title=None):
        self.path = path
        self.margin_x = self.origin_x = margin_x
        self.margin_y = self.origin_y = margin_y
        self.file_name = file_name
        self.is_landscape = is_landscape
        self.author = author
        self.title = title

        # embeds "Hand of Sean" font:
        afmFile = os.path.join(settings.FONT_ROOT, 'HandOfSean.afm')
        pfbFile = os.path.join(settings.FONT_ROOT, 'HandOfSean.pfb')
        ttfFile = os.path.join(settings.FONT_ROOT, 'handsean.ttf')
        justFace = pdfmetrics.EmbeddedType1Face(afmFile, pfbFile) #embeds font
        faceName = 'HandOfSean' # pulled from AFM file
        pdfmetrics.registerTypeFace(justFace)
        justFont = pdfmetrics.Font('HandSean', faceName, 'WinAnsiEncoding')
        pdfmetrics.registerFont(justFont)
        pdfmetrics.registerFont(TTFont('HandSean', ttfFile))

        response = HttpResponse(content_type='application/pdf')
        response['Content-Disposition'] = 'attachment; filename=' + self.file_name

        self.set_orientation(self.is_landscape)

        self.canvas = canvas.Canvas(self.path + '/' + self.file_name,
                               pagesize=(self.page_width, self.page_height))
        if self.author is not None:
            self.canvas.setAuthor(self.author)
        if self.title is not None:
            self.canvas.setTitle(self.title)
Exemplo n.º 5
0
def set_cyr_font():
    # fname - the font file name without extension
    fname = 'a010013l'

    # faceName - view a010013l.AFM file as a plain text and look at
    # row beginning with 'FontName' word (it's usually the fourth row).
    # The word after 'FontName' is the faceName ('URWGothicL-Book' in this case).
    faceName = 'URWGothicL-Book'

    # Define new Type 1 font
    cyrFace = pdfmetrics.EmbeddedType1Face(fname + '.afm', fname + '.pfb')

    # Create a new encoding called 'CP1251'
    cyrenc = pdfmetrics.Encoding('CP1251')

    # Fill in the tuple with Unicode glyphs in accordance with cp1251 (win1251)
    # encoding
    cp1251 = (
        'afii10051', 'afii10052', 'quotesinglbase', 'afii10100', 'quotedblbase',
        'ellipsis', 'dagger', 'daggerdbl', 'Euro', 'perthousand', 'afii10058',
        'guilsinglleft', 'afii10059', 'afii10061', 'afii10060', 'afii10145',
        'afii10099', 'quoteleft', 'quoteright', 'quotedblleft', 'quotedblright',
        'bullet', 'endash', 'emdash', 'tilde', 'trademark', 'afii10106',
        'guilsinglright', 'afii10107', 'afii10109', 'afii10108', 'afii10193',
        'space', 'afii10062', 'afii10110', 'afii10057', 'currency', 'afii10050',
        'brokenbar', 'section', 'afii10023', 'copyright', 'afii10053',
        'guillemotleft', 'logicalnot', 'hyphen', 'registered', 'afii10056',
        'degree', 'plusminus', 'afii10055', 'afii10103', 'afii10098', 'mu1',
        'paragraph', 'periodcentered', 'afii10071', 'afii61352', 'afii10101',
        'guillemotright', 'afii10105', 'afii10054', 'afii10102', 'afii10104',
        'afii10017', 'afii10018', 'afii10019', 'afii10020', 'afii10021',
        'afii10022', 'afii10024', 'afii10025', 'afii10026', 'afii10027',
        'afii10028', 'afii10029', 'afii10030', 'afii10031', 'afii10032',
        'afii10033', 'afii10034', 'afii10035', 'afii10036', 'afii10037',
        'afii10038', 'afii10039', 'afii10040', 'afii10041', 'afii10042',
        'afii10043', 'afii10044', 'afii10045', 'afii10046', 'afii10047',
        'afii10048', 'afii10049', 'afii10065', 'afii10066', 'afii10067',
        'afii10068', 'afii10069', 'afii10070', 'afii10072', 'afii10073',
        'afii10074', 'afii10075', 'afii10076', 'afii10077', 'afii10078',
        'afii10079', 'afii10080', 'afii10081', 'afii10082', 'afii10083',
        'afii10084', 'afii10085', 'afii10086', 'afii10087', 'afii10088',
        'afii10089', 'afii10090', 'afii10091', 'afii10092', 'afii10093',
        'afii10094', 'afii10095', 'afii10096', 'afii10097'
    )

    # Replace glyphs from code 128 to code 256 with cp1251 values
    for i in range(128, 256):
        cyrenc[i] = cp1251[i - 128]

    # Register newly created encoding
    pdfmetrics.registerEncoding(cyrenc)

    # Register type face
    pdfmetrics.registerTypeFace(cyrFace)

    # Register the font with adding '1251' to its name
    pdfmetrics.registerFont(pdfmetrics.Font(faceName + '1251', faceName, 'CP1251'))

    return faceName + '1251'  # def set_cyr_font
Exemplo n.º 6
0
 def _register_fonts(self):
     afmfile, pfbfile, fontname = self.TITLE_FONT
     registerTypeFace(EmbeddedType1Face(afmfile, pfbfile))
     registerFont(Font(fontname, fontname, 'WinAnsiEncoding'))
     
     for suffix in ['', '-Bold', '-Oblique', '-BoldOblique']:
         registerFont(TTFont(self.MONO_FONT[0].format(suffix), 
                             self.MONO_FONT[1].format(suffix)))
     registerFontFamily('Mono', normal='Mono', bold='Mono-Bold', 
                        italic='Mono-Oblique', boldItalic='Mono-BoldOblique')
Exemplo n.º 7
0
 def embed_font(self, path, face_name):
     """
     Register a font face with ReportLab an (if used) embed in the target PDF.
     """
     ## Based on snippet from http://www.reportlab.org/devfaq.html
     afm = os.path.join(path, face_name + '.afm')
     pfb = os.path.join(path, face_name + '.pfb')
     face = pdfmetrics.EmbeddedType1Face(afm, pfb)         
     pdfmetrics.registerTypeFace(face)
     font = pdfmetrics.Font(face_name, face_name, 'WinAnsiEncoding')
     pdfmetrics.registerFont(font)
Exemplo n.º 8
0
def reg_font_afm(head,root):
    afmFile = os.path.join(head,root+".afm")
    pfbFile = os.path.join(head,root+".pfb")

    (topLevel, glyphData) = pdfmetrics.parseAFMFile(afmFile)
    faceName=topLevel['FontName']

    justFace = pdfmetrics.EmbeddedType1Face(afmFile, pfbFile)
    pdfmetrics.registerTypeFace(justFace)
    justFont = pdfmetrics.Font(faceName, faceName, 'WinAnsiEncoding')
    pdfmetrics.registerFont(justFont)
    return
Exemplo n.º 9
0
    def font_start(self, name, ttf=None, afm=None, pfb=None):

        # True Type Fonts
        if ttf:
            font_path = os.path.join(self.font_dir, ttf)
            pdfmetrics.registerFont(TTFont(name, font_path))
            return

        # Type 1
        face = pdfmetrics.EmbeddedType1Face(afm, pfb)
        pdfmetrics.registerTypeFace(face) 
        font = pdfmetrics.Font(name, name, 'WinAnsiEncoding')
        pdfmetrics.registerFont(font) 
Exemplo n.º 10
0
    def _register_fonts(self):
        afmfile, pfbfile, fontname = self.TITLE_FONT
        registerTypeFace(EmbeddedType1Face(afmfile, pfbfile))
        registerFont(Font(fontname, fontname, 'WinAnsiEncoding'))

        for suffix in ['', '-Bold', '-Oblique', '-BoldOblique']:
            registerFont(
                TTFont(self.MONO_FONT[0].format(suffix),
                       self.MONO_FONT[1].format(suffix)))
        registerFontFamily('Mono',
                           normal='Mono',
                           bold='Mono-Bold',
                           italic='Mono-Oblique',
                           boldItalic='Mono-BoldOblique')
Exemplo n.º 11
0
def register_type1_font():
    """This function is a maintenence function that registers new Type 1 font for PDF use
    This only need be run on new installations and when installing new fonts. Does not need to be
    run every time a program starts up. This modifies the ReportLab installation."""

    # Define the location of the font to be registered
    folder = os.path.dirname(reportlab.__file__) + os.sep + "fonts"
    afmFile = os.path.join(folder, "DarkGardenMK.afm")
    pfbFile = os.path.join(folder, "DarkGardenMK.pfb")
    justFace = pdfmetrics.EmbeddedType1Face(afmFile, pfbFile)
    faceName = "DarkGardenMK"
    pdfmetrics.registerTypeFace(justFace)
    justFont = pdfmetrics.Font("DarkGardenMK", faceName, "WinAnsiEncoding")
    pdfmetrics.registerFont(justFont)
Exemplo n.º 12
0
    def import_pdf_font(self, base_name, face_name):
        if self.fonts.get(face_name, None) is None:
            afm = find(base_name + '.afm')
            pfb = find(base_name + '.pfb')

            try:
                face = pdfmetrics.EmbeddedType1Face(afm, pfb)

                pdfmetrics.registerTypeFace(face)
                font = pdfmetrics.Font(face_name, face_name, 'WinAnsiEncoding')
                pdfmetrics.registerFont(font)
            except:
                pass
        else:
            self.fonts[face_name] = True
Exemplo n.º 13
0
def registerFont0(sourceFile, name, path):
    "Register Type-1 font for future use, simple version."

    rl_config.warnOnMissingFontGlyphs = 0

    p = os.path.join(os.path.dirname(sourceFile), path)
    afmFiles = glob.glob(p + '.[aA][fF][mM]')
    pfbFiles = glob.glob(p + '.[pP][fF][bB]')
    assert len(afmFiles) == len(pfbFiles) == 1, FontFilesNotFoundError

    T1face = pdfmetrics.EmbeddedType1Face(afmFiles[0], pfbFiles[0])
    T1faceName = name
    pdfmetrics.registerTypeFace(T1face)
    T1font = pdfmetrics.Font(name, T1faceName, 'WinAnsiEncoding')
    pdfmetrics.registerFont(T1font)
Exemplo n.º 14
0
    def import_pdf_font(self, base_name, face_name):
        if self.fonts.get(face_name, None) is None:
            afm = find(base_name + '.afm')
            pfb = find(base_name + '.pfb')

            try:
                face = pdfmetrics.EmbeddedType1Face(afm, pfb)

                pdfmetrics.registerTypeFace(face)
                font = pdfmetrics.Font(face_name, face_name, 'WinAnsiEncoding')
                pdfmetrics.registerFont(font)
            except:
                pass
        else:
            self.fonts[face_name] = True
Exemplo n.º 15
0
def installfont(fontname):
    """Registers a typeface and font based on the given name."""
    fontdir_afm = Path(CONFIG['fonts']['fontdir_afm'])
    fontdir_pfb = Path(CONFIG['fonts']['fontdir_pfb'])
    fontfile_stem = fontname
    afm = (fontdir_afm / fontfile_stem).with_suffix('.afm')
    pfb = (fontdir_pfb / fontfile_stem).with_suffix('.pfb')

    try:
        pdfmetrics.registerTypeFace(pdfmetrics.EmbeddedType1Face(afm, pfb))
        pdfmetrics.registerFont(
            pdfmetrics.Font(fontname, fontname, 'WinAnsiEncoding'))
    except AssertionError:
        raise FontFileNotFound(f'Cannot install font {fontname}. '
                               'Does its .afm and .pfb files exist?')
Exemplo n.º 16
0
def registerFont0(sourceFile, name, path):
    "Register Type-1 font for future use, simple version."

    rl_config.warnOnMissingFontGlyphs = 0

    p = os.path.join(os.path.dirname(sourceFile), path)
    afmFiles = glob.glob(p + ".[aA][fF][mM]")
    pfbFiles = glob.glob(p + ".[pP][fF][bB]")
    assert len(afmFiles) == len(pfbFiles) == 1, FontFilesNotFoundError

    T1face = pdfmetrics.EmbeddedType1Face(afmFiles[0], pfbFiles[0])
    T1faceName = name
    pdfmetrics.registerTypeFace(T1face)
    T1font = pdfmetrics.Font(name, T1faceName, "WinAnsiEncoding")
    pdfmetrics.registerFont(T1font)
Exemplo n.º 17
0
def register_fonts():
    # Font name : file name
    # File name should be the same as internal font name
    fonts = {
        'HugoHandwriting': 'Hugohandwriting-Regular'
    }

    font_dir = Path.cwd() / 'tests' / 'data' / 'fonts'
    for font_name, font_file in fonts.items():
        font_path_afm = font_dir / (font_file + '.afm')
        font_path_pfb = font_dir / (font_file + '.pfb')

        face = pdfmetrics.EmbeddedType1Face(font_path_afm, font_path_pfb)
        pdfmetrics.registerTypeFace(face)

        font = pdfmetrics.Font(font_name, font_file, 'WinAnsiEncoding')
        pdfmetrics.registerFont(font)
Exemplo n.º 18
0
 def import_pdf_font(self, base_name, face_name):
     import os
     import reportlab
     from reportlab.pdfbase import pdfmetrics
     
     if self.fonts.get(face_name, None) is None:
         afm = os.path.join(settings.MEDIA_ROOT, base_name + '.afm')
         pfb = os.path.join(settings.MEDIA_ROOT, base_name + '.pfb')
     
         try:
             face = pdfmetrics.EmbeddedType1Face(afm, pfb)
     
             pdfmetrics.registerTypeFace(face)
             font = pdfmetrics.Font(face_name, face_name, 'WinAnsiEncoding')
             pdfmetrics.registerFont(font)
         except:
             pass
     else:
         self.fonts[face_name] = True
Exemplo n.º 19
0
    def import_pdf_font(self, base_name, face_name):
        if self.fonts.get(face_name, None) is None:
            afm = find(base_name + '.afm')
            pfb = find(base_name + '.pfb')
            ttf = find(base_name + '.ttf')

            if afm:
                try:
                    face = pdfmetrics.EmbeddedType1Face(afm, pfb)

                    pdfmetrics.registerTypeFace(face)
                    font = pdfmetrics.Font(face_name, face_name, 'WinAnsiEncoding')
                    pdfmetrics.registerFont(font)
                except:
                    pass
            elif ttf:
                pdfmetrics.registerFont(TTFont(face_name, ttf))
            else:
                raise Exception('Cannot find font %s (tried .afm, .pfb and .ttf)' % base_name)
        else:
            self.fonts[face_name] = True
Exemplo n.º 20
0
 def cyrillic(c, n):
     fname = 'font'
     faceName = 'TimesNewRomanPSMT'
     cyrFace = pdfmetrics.EmbeddedType1Face(fname + '.afm', fname + '.pfb')
     cyrEnc = pdfmetrics.Encoding('CP1251')
     cp1251 = (
         'afii10051', 'afii10052', 'quotesinglbase', 'afii10100',
         'quotedblbase', 'ellipsis', 'dagger', 'daggerdbl', 'Euro',
         'perthousand', 'afii10058', 'guilsinglleft', 'afii10059',
         'afii10061', 'afii10060', 'afii10145', 'afii10099', 'quoteleft',
         'quoteright', 'quotedblleft', 'quotedblright', 'bullet', 'endash',
         'emdash', 'tilde', 'trademark', 'afii10106', 'guilsinglright',
         'afii10107', 'afii10109', 'afii10108', 'afii10193', 'space',
         'afii10062', 'afii10110', 'afii10057', 'currency', 'afii10050',
         'brokenbar', 'section', 'afii10023', 'copyright', 'afii10053',
         'guillemotleft', 'logicalnot', 'hyphen', 'registered', 'afii10056',
         'degree', 'plusminus', 'afii10055', 'afii10103', 'afii10098',
         'mu1', 'paragraph', 'periodcentered', 'afii10071', 'afii61352',
         'afii10101', 'guillemotright', 'afii10105', 'afii10054',
         'afii10102', 'afii10104', 'afii10017', 'afii10018', 'afii10019',
         'afii10020', 'afii10021', 'afii10022', 'afii10024', 'afii10025',
         'afii10026', 'afii10027', 'afii10028', 'afii10029', 'afii10030',
         'afii10031', 'afii10032', 'afii10033', 'afii10034', 'afii10035',
         'afii10036', 'afii10037', 'afii10038', 'afii10039', 'afii10040',
         'afii10041', 'afii10042', 'afii10043', 'afii10044', 'afii10045',
         'afii10046', 'afii10047', 'afii10048', 'afii10049', 'afii10065',
         'afii10066', 'afii10067', 'afii10068', 'afii10069', 'afii10070',
         'afii10072', 'afii10073', 'afii10074', 'afii10075', 'afii10076',
         'afii10077', 'afii10078', 'afii10079', 'afii10080', 'afii10081',
         'afii10082', 'afii10083', 'afii10084', 'afii10085', 'afii10086',
         'afii10087', 'afii10088', 'afii10089', 'afii10090', 'afii10091',
         'afii10092', 'afii10093', 'afii10094', 'afii10095', 'afii10096',
         'afii10097')
     for i in range(128, 256):
         cyrEnc[i] = cp1251[i - 128]
     pdfmetrics.registerEncoding(cyrEnc)
     pdfmetrics.registerTypeFace(cyrFace)
     pdfmetrics.registerFont(
         pdfmetrics.Font(faceName + '1251', faceName, 'CP1251'))
     c.setFont(faceName + '1251', n)
Exemplo n.º 21
0
   def get(self):
      text = self.request.get('t')
      if text:
         pdfmetrics.registerTypeFace(pdfmetrics.EmbeddedType1Face(
            os.path.join(folderFonts, 'DarkGardenMK.afm'),
            os.path.join(folderFonts, 'DarkGardenMK.pfb')))
         pdfmetrics.registerFont(pdfmetrics.Font(
            'DarkGardenMK', 'DarkGardenMK', 'WinAnsiEncoding'))

         p = canvas.Canvas(self.response.out)
         p.drawImage('dog.jpg', 150, 400)
         p.drawString(50, 700, 'The text you entered: ' + text)
         p.setFont('DarkGardenMK', 16)
         p.drawString(50, 600, 'DarkGarden font loaded from reportlab.zip')
         p.showPage()

         self.response.headers['Content-Type'] = 'application/pdf'
         self.response.headers['Content-Disposition'] = 'filename=testpdf.pdf'

         p.save()
      else:
         self.response.out.write(template.render('testpdf.html', {}))
Exemplo n.º 22
0
def registerFont(faceName, afm, pfb):
    """
    Helvetica BUT AS AFM

    The below section is NOT equal to::

        _baseFontName  ='Helvetica'
        _baseFontNameB ='Helvetica-Bold'
        _baseFontNameI ='Helvetica-Oblique'
        _baseFontNameBI='Helvetica-BoldOblique'

    we will mapp afm files from matplotlib with pfb files from reportlab

    this will give embedded Type1 Face Fonts

    """
    afm = os.path.join(__font_dir__, "".join(afm, ".afm"))
    pfb = os.path.join(__font_dir__, "".join(pfb, ".pfb"))

    face = pdfmetrics.EmbeddedType1Face(afm, pfb)
    pdfmetrics.registerTypeFace(face)
    font = pdfmetrics.Font(faceName, faceName, 'WinAnsiEncoding')
    pdfmetrics.registerFont(font)
Exemplo n.º 23
0
    def import_pdf_font(self, base_name, face_name):
        if self.fonts.get(face_name, None) is None:
            afm = find(base_name + '.afm')
            pfb = find(base_name + '.pfb')
            ttf = find(base_name + '.ttf')

            if afm:
                try:
                    face = pdfmetrics.EmbeddedType1Face(afm, pfb)

                    pdfmetrics.registerTypeFace(face)
                    font = pdfmetrics.Font(face_name, face_name,
                                           'WinAnsiEncoding')
                    pdfmetrics.registerFont(font)
                except:
                    pass
            elif ttf:
                pdfmetrics.registerFont(TTFont(face_name, ttf))
            else:
                raise Exception(
                    'Cannot find font %s (tried .afm, .pfb and .ttf)' %
                    base_name)
        else:
            self.fonts[face_name] = True
Exemplo n.º 24
0
    def _setup_font(self, fontname, locale):
        registerTypeFace(TypeFace('Times-Roman'))

        if fontname != '(auto)':
            if fontname not in self._stdfonts \
                    and fontname not in self._cidfonts:
                fontname = '(auto)'

        if fontname == '(auto)':
            lang = None
            if locale:
                lang = str(locale).split('_', 1)[0]
            fontname = {'ja': 'HeiseiKakuGo-W5',
                        'ko': 'HYGothic-Medium',
                        'zh': 'STSong-Light'}.get(lang, 'Helvetica')

        if fontname in self._stdfonts:
            font = TypeFace(fontname)
            registerTypeFace(font)
        elif fontname in self._cidfonts:
            font = UnicodeCIDFont(fontname)
            registerFont(font)

        return fontname
Exemplo n.º 25
0
def mkpdf(ds, sample=False):
    """
    Return a pdf made from the passed dataset.
    Sample - True when creating a sample badge, 
             includes graphics and perf lines.
    """

    try: from cStringIO import StringIO
    except: err_missing('cStringIO library not installed;')

    try:
	from reportlab.pdfbase import pdfmetrics
	from reportlab.pdfbase.ttfonts import TTFont
    except: err_missing('python-reportlab library missing;')

    try: from dabo.dReportWriter import dReportWriter
    except: err_missing('Dabo Reportwriter not installed.')

    import os

    static_path = '%sstatic/badges/'% request.folder
    xmlfile  = '%s/badge_full.rfxml' % static_path

    # buffer to create pdf in
    buffer = StringIO()

    # register fonts (hardcoded is lame.)  
    # reportlab has some code, trying to figure out how to use it.)
    
    # check the fonts are installed on the system;  error page if not:

    if not (os.access(TRUETYPE_PATH,os.R_OK)|os.access(GSFONTS_PATH,os.R_OK)):
	err_missing('Missing fonts; unable to generate badge(s).')
                 
    pdfmetrics.registerFont(TTFont("FreeSans", "%s/FreeSans.ttf" % TRUETYPE_PATH))

# what happens here if these font paths don't exist?
#  will pdfmetrics handle the error gracefully, or do you need try/except here?
    afmFile = os.path.join(GSFONTS_PATH, 'n019004l.afm')
    pfbFile = os.path.join(GSFONTS_PATH, 'n019004l.pfb')
    justFace = pdfmetrics.EmbeddedType1Face(afmFile, pfbFile)
    faceName = 'NimbusSanL-Bold' # pulled from AFM file
    pdfmetrics.registerTypeFace(justFace)
    justFont = pdfmetrics.Font('NimbusSanL-Bold',
                               faceName,
                               'WinAnsiEncoding')
    pdfmetrics.registerFont(justFont) 

    afmFile = os.path.join(GSFONTS_PATH, 'n019003l.afm')
    pfbFile = os.path.join(GSFONTS_PATH, 'n019003l.pfb')
    justFace = pdfmetrics.EmbeddedType1Face(afmFile, pfbFile)
    faceName = 'NimbusSanL-Regu' # pulled from AFM file
    pdfmetrics.registerTypeFace(justFace)
    justFont = pdfmetrics.Font('NimbusSanL-Regu',
                               faceName,
                               'WinAnsiEncoding')
    pdfmetrics.registerFont(justFont) 
    # end of register fonts code.

    for row in ds:

        # make a barcode for each row, add it to the dataset
        wad=ds_to_wad(row)
        row['barcode']=mk_barcode(wad)
    
        # bod: badge on demand.  
        # set bod in each row
        row['bod']=not sample


    # generate the pdf in the buffer, using the layout and data
    try:
        rw = dReportWriter(OutputFile=buffer, ReportFormFile=xmlfile, Cursor=ds)
        rw.write()
    except:
        err_missing('ReportWriter write failing... ')

    # get the pdf out of the buffer
    pdf = buffer.getvalue()
    buffer.close()

    return pdf
Exemplo n.º 26
0
          'afii10068', 'afii10069', 'afii10070', 'afii10072', 'afii10073',
          'afii10074', 'afii10075', 'afii10076', 'afii10077', 'afii10078',
          'afii10079', 'afii10080', 'afii10081', 'afii10082', 'afii10083',
          'afii10084', 'afii10085', 'afii10086', 'afii10087', 'afii10088',
          'afii10089', 'afii10090', 'afii10091', 'afii10092', 'afii10093',
          'afii10094', 'afii10095', 'afii10096', 'afii10097')

# Replace glyphs from code 128 to code 256 with cp1251 values
for i in range(128, 256):
    cyrenc[i] = cp1251[i - 128]

# Register newly created encoding
pdfmetrics.registerEncoding(cyrenc)

# Register type face
pdfmetrics.registerTypeFace(cyrFace)

# Register the font with adding '1251' to its name
pdfmetrics.registerFont(pdfmetrics.Font(faceName + '1251', faceName, 'CP1251'))

# Use this font and set font size
c.setFont(faceName + '1251', 90)

# hello - 'Hello!' in Ukrainian. If you have Cyrillic keyboard layout and
# cp1251 system encoding just type Cyrillic text instead of its hexadecimal
# equivalent
hello = '\xcf\xf0\xe8\xe2\xb3\xf2!'

# Draw this text at last
c.drawString(125, 700, hello)
                 fontSize=36))

    d.add(String(150, 160, 'Hello World',
                 fontName='DarkGardenMK',
                 fontSize=36))
"""
)

from reportlab.pdfbase import pdfmetrics
from reportlab import rl_config

rl_config.warnOnMissingFontGlyphs = 0
afmFile, pfbFile = getJustFontPaths()
T1face = pdfmetrics.EmbeddedType1Face(afmFile, pfbFile)
T1faceName = "DarkGardenMK"
pdfmetrics.registerTypeFace(T1face)
T1font = pdfmetrics.Font(T1faceName, T1faceName, "WinAnsiEncoding")
pdfmetrics.registerFont(T1font)

d = Drawing(400, 200)
for size in range(12, 36, 4):
    d.add(String(10 + size * 2, 10 + size * 2, "Hello World", fontName="Times-Roman", fontSize=size))

d.add(String(130, 120, "Hello World", fontName="Courier", fontSize=36))

d.add(String(150, 160, "Hello World", fontName="DarkGardenMK", fontSize=36))

draw(d, "fancy font example")


heading3("""Paths""")
Exemplo n.º 28
0
    def loadFont(self, names, src, encoding="WinAnsiEncoding", bold=0, italic=0):
        
        # XXX Just works for local filenames!        
        if names and src: # and src.local:
            
            file = src
            src = file.uri
            
            log.debug("Load font %r", src)
            
            if type(names) is types.ListType:
                fontAlias = names
            else:
                fontAlias = [x.lower().strip() for x in names.split(",") if x]
            
            # XXX Problems with unicode here 
            fontAlias = [str(x) for x in fontAlias]            
            
            fontName = fontAlias[0]
            parts = src.split(".")                
            baseName, suffix = ".".join(parts[: - 1]), parts[ - 1]
            suffix = suffix.lower()
                        
            try:
                
                if suffix == "ttf":

                    # determine full font name according to weight and style
                    fullFontName = "%s_%d%d" % (fontName, bold, italic)                    

                    # check if font has already been registered
                    if fullFontName in self.fontList:
                        log.warn(self.warning("Repeated font embed for %s, skip new embed ", fullFontName))
                    else:
                                                
                        # Register TTF font and special name 
                        filename = file.getNamedFile()
                        pdfmetrics.registerFont(TTFont(fullFontName, filename))
                        
                        # Add or replace missing styles
                        for bold in (0, 1):
                            for italic in (0, 1):                                                                
                                if ("%s_%d%d" % (fontName, bold, italic)) not in self.fontList:
                                    addMapping(fontName, bold, italic, fullFontName)

                        # Register "normal" name and the place holder for style                                                
                        self.registerFont(fontName, fontAlias + [fullFontName])
                                         
                elif suffix in ("afm", "pfb"):
                    
                    if suffix == "afm":
                        afm = file.getNamedFile()
                        tfile = pisaFileObject(baseName + ".pfb")
                        pfb = tfile.getNamedFile()
                    else:
                        pfb  = file.getNamedFile()
                        tfile = pisaFileObject(baseName + ".afm")
                        afm = tfile.getNamedFile()
                        
                    #afm = baseName + ".afm"
                    #pfb = baseName + ".pfb"

                    # determine full font name according to weight and style
                    fullFontName = "%s_%d%d" % (fontName, bold, italic)   
                        
                    #fontNameOriginal = ""
                    #for line in open(afm).readlines()[:-1]:
                    #    if line[:16] == 'StartCharMetrics':
                    #        self.error("Font name not found")
                    #    if line[:8] == 'FontName':
                    #        fontNameOriginal = line[9:].strip()
                    #        break
                                   
                    # check if font has already been registered
                    if fullFontName in self.fontList:
                        log.warn(self.warning("Repeated font embed for %s, skip new embed", fontName))
                    else:                                              
                        
                        # Include font                 
                        face = pdfmetrics.EmbeddedType1Face(afm, pfb)                        
                        fontNameOriginal = face.name
                        pdfmetrics.registerTypeFace(face)
                        # print fontName, fontNameOriginal, fullFontName
                        justFont = pdfmetrics.Font(fullFontName, fontNameOriginal, encoding)
                        pdfmetrics.registerFont(justFont)
                        
                        # Add or replace missing styles
                        for bold in (0, 1):
                            for italic in (0, 1):                                                                
                                if ("%s_%d%d" % (fontName, bold, italic)) not in self.fontList:
                                    addMapping(fontName, bold, italic, fontNameOriginal)
                        
                        # Register "normal" name and the place holder for style                                                
                        self.registerFont(fontName, fontAlias + [fullFontName, fontNameOriginal])
    
                        #import pprint
                        #pprint.pprint(self.fontList)
    
                else:
                    log.warning(self.warning("wrong attributes for <pdf:font>"))
    
            except Exception:
                log.warn(self.warning("Loading font '%s'", fontName), exc_info=1)                
Exemplo n.º 29
0
    def test0(self):
        """Make documents with embedded fonts.

        Just vam Rossum has kindly donated a font which we may use
        for testing purposes.  You need to contact him at [email protected]
        if you want to use it for real."""

        # LettError fonts should always be there.  The others are voluntary.

        ok = 1

        c = Canvas(outputfile("test_pdfbase_fontembed.pdf"))
        c.setPageCompression(0)
        c.setFont("Helvetica", 12)
        c.drawString(100, 700, "This is Helvetica.  The text below should be different fonts...")

        if os.path.isfile("GDB_____.AFM") and os.path.isfile("GDB_____.PFB"):
            # a normal text font
            garaFace = pdfmetrics.EmbeddedType1Face("GDB_____.AFM", "GDB_____.PFB")
            faceName = "AGaramond-Bold"  # pulled from AFM file
            pdfmetrics.registerTypeFace(garaFace)

            garaFont = pdfmetrics.Font("MyGaramondBold", faceName, "WinAnsiEncoding")
            pdfmetrics.registerFont(garaFont)

            c.setFont("AGaramond-Bold", 12)
            c.drawString(100, 650, "This should be in AGaramond-Bold")

        if os.path.isfile("CR______.AFM") and os.path.isfile("CR______.PFB"):

            # one with a custom encoding
            cartaFace = pdfmetrics.EmbeddedType1Face("CR______.AFM", "CR______.PFB")
            faceName = "Carta"  # pulled from AFM file
            pdfmetrics.registerTypeFace(cartaFace)

            cartaFont = pdfmetrics.Font("Carta", "Carta", "CartaEncoding")
            pdfmetrics.registerFont(cartaFont)

            text = "This should be in Carta, a map symbol font:"
            c.setFont("Helvetica", 12)
            c.drawString(100, 600, text)
            w = c.stringWidth(text, "Helvetica", 12)

            c.setFont("Carta", 12)
            c.drawString(100 + w, 600, " Hello World")

        # LettError sample - creates on demand, we hope
        y = 550
        ##        dgmkFace = pdfmetrics.EmbeddedType1Face('DarkGardenMK.afm','DarkGardenMK.PFB')
        ##
        ##        faceName = 'DarkGardenMK'  # pulled from AFM file
        ##        pdfmetrics.registerTypeFace(dgmkFace)
        ##
        ##        dgmkFont = pdfmetrics.Font('DarkGardenMK', faceName, 'WinAnsiEncoding')
        ##        pdfmetrics.registerFont(dgmk)

        c.setFont("DarkGardenMK", 12)
        c.drawString(100, y, "This should be in DarkGardenMK")

        def testNamedFont(canv, fontName):
            canv.showPage()
            makeWidthTestForAllGlyphs(canv, fontName, outlining=0)

        testNamedFont(c, "DarkGardenMK")

        c.save()
Exemplo n.º 30
0
    def test0(self):
        """Make documents with embedded fonts.

        Just vam Rossum has kindly donated a font which we may use
        for testing purposes.  You need to contact him at [email protected]
        if you want to use it for real."""

        #LettError fonts should always be there.  The others are voluntary.

        ok = 1

        c = Canvas(outputfile('test_pdfbase_fontembed.pdf'))
        c.setPageCompression(0)
        c.setFont('Helvetica', 12)
        c.drawString(100, 700, 'This is Helvetica.  The text below should be different fonts...')

        if os.path.isfile('GDB_____.AFM') and os.path.isfile('GDB_____.PFB'):
            # a normal text font
            garaFace = pdfmetrics.EmbeddedType1Face('GDB_____.AFM','GDB_____.PFB')
            faceName = 'AGaramond-Bold'  # pulled from AFM file
            pdfmetrics.registerTypeFace(garaFace)

            garaFont = pdfmetrics.Font('MyGaramondBold', faceName, 'WinAnsiEncoding')
            pdfmetrics.registerFont(garaFont)

            c.setFont('AGaramond-Bold', 12)
            c.drawString(100, 650, 'This should be in AGaramond-Bold')

        if os.path.isfile('CR______.AFM') and os.path.isfile('CR______.PFB'):

            # one with a custom encoding
            cartaFace = pdfmetrics.EmbeddedType1Face('CR______.AFM','CR______.PFB')
            faceName = 'Carta'  # pulled from AFM file
            pdfmetrics.registerTypeFace(cartaFace)

            cartaFont = pdfmetrics.Font('Carta', 'Carta', 'CartaEncoding')
            pdfmetrics.registerFont(cartaFont)

            text = 'This should be in Carta, a map symbol font:'
            c.setFont('Helvetica', 12)
            c.drawString(100, 600, text)
            w = c.stringWidth(text, 'Helvetica', 12)

            c.setFont('Carta', 12)
            c.drawString(100+w, 600, ' Hello World')

        # LettError sample - creates on demand, we hope
        y = 550
##        justFace = pdfmetrics.EmbeddedType1Face('LeERC___.AFM','LeERC___.PFB')
##
##        faceName = 'LettErrorRobot-Chrome'  # pulled from AFM file
##        pdfmetrics.registerTypeFace(justFace)
##
##        justFont = pdfmetrics.Font('LettErrorRobot-Chrome', faceName, 'WinAnsiEncoding')
##        pdfmetrics.registerFont(justFont)

        c.setFont('LettErrorRobot-Chrome', 12)
        c.drawString(100, y, 'This should be in LettErrorRobot-Chrome')

        def testNamedFont(canv, fontName):
            canv.showPage()
            makeWidthTestForAllGlyphs(canv, fontName, outlining=0)

        testNamedFont(c, 'LettErrorRobot-Chrome')

        c.save()
Exemplo n.º 31
0
    def loadFont(self, names, src, encoding="WinAnsiEncoding", bold=0, italic=0):

        # XXX Just works for local filenames!
        if names and src:

            file = src
            src = file.uri

            log.debug("Load font %r", src)

            if type(names) is list:
                fontAlias = names
            else:
                fontAlias = (x.lower().strip() for x in names.split(",") if x)

            # XXX Problems with unicode here
            fontAlias = [str(x) for x in fontAlias]

            fontName = fontAlias[0]
            parts = src.split(bytes(".", 'utf-8'))
            baseName, suffix = bytes(".", 'utf-8').join(parts[: - 1]), parts[- 1]
            suffix = suffix.lower()

            if suffix in ["ttc", "ttf"]:

                # determine full font name according to weight and style
                fullFontName = "%s_%d%d" % (fontName, bold, italic)

                # check if font has already been registered
                if fullFontName in self.fontList:
                    log.warning(self.warning("Repeated font embed for %s, skip new embed ", fullFontName))
                else:

                    # Register TTF font and special name
                    filename = file.getNamedFile()
                    pdfmetrics.registerFont(TTFont(fullFontName, filename))

                    # Add or replace missing styles
                    for bold in (0, 1):
                        for italic in (0, 1):
                            if ("%s_%d%d" % (fontName, bold, italic)) not in self.fontList:
                                addMapping(fontName, bold, italic, fullFontName)

                    # Register "normal" name and the place holder for style
                    self.registerFont(fontName, fontAlias + [fullFontName])

            elif suffix in ("afm", "pfb"):

                if suffix == "afm":
                    afm = file.getNamedFile()
                    tfile = pisaFileObject(baseName + ".pfb")
                    pfb = tfile.getNamedFile()
                else:
                    pfb = file.getNamedFile()
                    tfile = pisaFileObject(baseName + ".afm")
                    afm = tfile.getNamedFile()

                # determine full font name according to weight and style
                fullFontName = "%s_%d%d" % (fontName, bold, italic)

                # check if font has already been registered
                if fullFontName in self.fontList:
                    log.warning(self.warning("Repeated font embed for %s, skip new embed", fontName))
                else:

                    # Include font
                    face = pdfmetrics.EmbeddedType1Face(afm, pfb)
                    fontNameOriginal = face.name
                    pdfmetrics.registerTypeFace(face)
                    # print fontName, fontNameOriginal, fullFontName
                    justFont = pdfmetrics.Font(fullFontName, fontNameOriginal, encoding)
                    pdfmetrics.registerFont(justFont)

                    # Add or replace missing styles
                    for bold in (0, 1):
                        for italic in (0, 1):
                            if ("%s_%d%d" % (fontName, bold, italic)) not in self.fontList:
                                addMapping(fontName, bold, italic, fontNameOriginal)

                    # Register "normal" name and the place holder for style
                    self.registerFont(fontName, fontAlias + [fullFontName, fontNameOriginal])
            else:
                log.warning(self.warning("wrong attributes for <pdf:font>"))
    d.add(String(130, 120, 'Hello World',
                 fontName='Courier',
                 fontSize=36))

    d.add(String(150, 160, 'Hello World',
                 fontName='DarkGardenMK',
                 fontSize=36))
""")

from reportlab.pdfbase import pdfmetrics
from reportlab import rl_config
rl_config.warnOnMissingFontGlyphs = 0
afmFile, pfbFile = getJustFontPaths()
T1face = pdfmetrics.EmbeddedType1Face(afmFile, pfbFile)
T1faceName = 'DarkGardenMK'
pdfmetrics.registerTypeFace(T1face)
T1font = pdfmetrics.Font(T1faceName, T1faceName, 'WinAnsiEncoding')
pdfmetrics.registerFont(T1font)

d = Drawing(400, 200)
for size in range(12, 36, 4):
    d.add(
        String(10 + size * 2,
               10 + size * 2,
               'Hello World',
               fontName='Times-Roman',
               fontSize=size))

d.add(String(130, 120, 'Hello World', fontName='Courier', fontSize=36))

d.add(String(150, 160, 'Hello World', fontName='DarkGardenMK', fontSize=36))
Exemplo n.º 33
0
def autoEmbed(fname):
    """Given a font name, does a best-effort of embedding
    said font and its variants.

    Returns a list of the font names it registered with ReportLab.

    """
    log.info("Trying to embed %s" % fname)
    fontList = []
    variants = []
    f = findFont(fname)
    if f:  # We have this font located
        if f[0].lower().endswith(".afm"):  # Type 1 font
            family = families[f[2]]

            # Register the whole family of faces
            faces = [
                pdfmetrics.EmbeddedType1Face(*fonts[fn.lower()][:2]) for fn in family
            ]
            for face in faces:
                pdfmetrics.registerTypeFace(face)

            for face, name in zip(faces, family):
                fontList.append(name)
                font = pdfmetrics.Font(face, name, "WinAnsiEncoding")
                log.info("Registering font: %s from %s" % (name, face.getFontFiles()))
                pdfmetrics.registerFont(font)

            # Map the variants
            regular, italic, bold, bolditalic = family
            for n in fname, regular:
                addMapping(n, 0, 0, regular)
                addMapping(n, 0, 1, italic)
                addMapping(n, 1, 0, bold)
                addMapping(n, 1, 1, bolditalic)
            log.info("Embedding as %s" % fontList)
            return fontList
        else:  # A TTF font
            variants = [fonts[x.lower()][0] for x in families[f[2]]]
    if not variants:  # Try fc-match
        variants = findTTFont(fname)
    # It is a TT Font and we found it using fc-match (or found *something*)
    if variants:
        for variant in variants:
            vname = os.path.basename(variant)[:-4]
            try:
                if vname not in pdfmetrics._fonts:
                    _font = TTFont(vname, variant)
                    log.info("Registering font: %s from %s" % (vname, variant))
                    pdfmetrics.registerFont(_font)
            except TTFError:
                log.error("Error registering font: %s from %s" % (vname, variant))
            else:
                fontList.append(vname)
        regular, bold, italic, bolditalic = [
            os.path.basename(variant)[:-4] for variant in variants
        ]
        addMapping(regular, 0, 0, regular)
        addMapping(regular, 0, 1, italic)
        addMapping(regular, 1, 0, bold)
        addMapping(regular, 1, 1, bolditalic)
        log.info("Embedding via findTTFont as %s" % fontList)
    return fontList
Exemplo n.º 34
0
def getExamples():
    """Returns all the example flowable objects"""
    styleSheet = getSampleStyleSheet()

    story = []

    #make a style with indents and spacing
    sty = ParagraphStyle('obvious', None)
    sty.leftIndent = 18
    sty.rightIndent = 18
    sty.firstLineIndent = 18
    sty.spaceBefore = 6
    sty.spaceAfter = 6
    story.append(Paragraph("""Now for some demo stuff - we need some on this page,
        even before we explain the concepts fully""", styleSheet['BodyText']))
    p = Paragraph("""
        Platypus is all about fitting objects into frames on the page.  You
        are looking at a fairly simple Platypus paragraph in Debug mode.
        It has some gridlines drawn around it to show the left and right indents,
        and the space before and after, all of which are attributes set in
        the style sheet.  To be specific, this paragraph has left and
        right indents of 18 points, a first line indent of 36 points,
        and 6 points of space before and after itself.  A paragraph
        object fills the width of the enclosing frame, as you would expect.""", sty)

    p.debug = 1   #show me the borders
    story.append(p)

    story.append(Paragraph("""Same but with justification 1.5 extra leading and green text.""", styleSheet['BodyText']))
    p = Paragraph("""
        <para align=justify leading=+1.5 fg=green><font color=red>Platypus</font> is all about fitting objects into frames on the page.  You
        are looking at a fairly simple Platypus paragraph in Debug mode.
        It has some gridlines drawn around it to show the left and right indents,
        and the space before and after, all of which are attributes set in
        the style sheet.  To be specific, this paragraph has left and
        right indents of 18 points, a first line indent of 36 points,
        and 6 points of space before and after itself.  A paragraph
        object fills the width of the enclosing frame, as you would expect.</para>""", sty)

    p.debug = 1   #show me the borders
    story.append(p)

    story.append(platypus.XBox(4*inch, 0.75*inch,
            'This is a box with a fixed size'))

    story.append(Paragraph("""
        All of this is being drawn within a text frame which was defined
        on the page.  This frame is in 'debug' mode so you can see the border,
        and also see the margins which it reserves.  A frame does not have
        to have margins, but they have been set to 6 points each to create
        a little space around the contents.
        """, styleSheet['BodyText']))

    story.append(FrameBreak())

    #######################################################################
    #     Examples Page 2
    #######################################################################

    story.append(Paragraph("""
        Here's the base class for Flowable...
        """, styleSheet['Italic']))

    code = '''class Flowable:
        """Abstract base class for things to be drawn.  Key concepts:
    1. It knows its size
    2. It draws in its own coordinate system (this requires the
        base API to provide a translate() function.
        """
    def __init__(self):
        self.width = 0
        self.height = 0
        self.wrapped = 0

    def drawOn(self, canvas, x, y):
        "Tell it to draw itself on the canvas.  Do not override"
        self.canv = canvas
        self.canv.saveState()
        self.canv.translate(x, y)

        self.draw()   #this is the bit you overload

        self.canv.restoreState()
        del self.canv

    def wrap(self, availWidth, availHeight):
        """This will be called by the enclosing frame before objects
        are asked their size, drawn or whatever.  It returns the
        size actually used."""
        return (self.width, self.height)
    '''

    story.append(Preformatted(code, styleSheet['Code'], dedent=4))
    story.append(FrameBreak())
    #######################################################################
    #     Examples Page 3
    #######################################################################

    story.append(Paragraph(
                "Here are some examples of the remaining objects above.",
                styleSheet['Italic']))

    story.append(Paragraph("This is a bullet point", styleSheet['Bullet'], bulletText='O'))
    story.append(Paragraph("Another bullet point", styleSheet['Bullet'], bulletText='O'))


    story.append(Paragraph("""Here is a Table, which takes all kinds of formatting options...""",
                styleSheet['Italic']))
    story.append(platypus.Spacer(0, 12))

    g = platypus.Table(
            (('','North','South','East','West'),
             ('Quarter 1',100,200,300,400),
             ('Quarter 2',100,200,300,400),
             ('Total',200,400,600,800)),
            (72,36,36,36,36),
            (24, 16,16,18)
            )
    style = platypus.TableStyle([('ALIGN', (1,1), (-1,-1), 'RIGHT'),
                               ('ALIGN', (0,0), (-1,0), 'CENTRE'),
                               ('GRID', (0,0), (-1,-1), 0.25, colors.black),
                               ('LINEBELOW', (0,0), (-1,0), 2, colors.black),
                               ('LINEBELOW',(1,-1), (-1, -1), 2, (0.5, 0.5, 0.5)),
                               ('TEXTCOLOR', (0,1), (0,-1), colors.black),
                               ('BACKGROUND', (0,0), (-1,0), (0,0.7,0.7))
                               ])
    g.setStyle(style)
    story.append(g)
    story.append(FrameBreak())

    #######################################################################
    #     Examples Page 4 - custom fonts
    #######################################################################
    # custom font with LettError-Robot font
    import reportlab.rl_config
    reportlab.rl_config.warnOnMissingFontGlyphs = 0

    from reportlab.pdfbase import pdfmetrics
    fontDir = os.path.join(os.path.dirname(reportlab.__file__),'fonts')
    face = pdfmetrics.EmbeddedType1Face(os.path.join(fontDir,'LeERC___.AFM'),os.path.join(fontDir,'LeERC___.PFB'))
    faceName = face.name  # should be 'LettErrorRobot-Chrome'
    pdfmetrics.registerTypeFace(face)
    font = pdfmetrics.Font(faceName, faceName, 'WinAnsiEncoding')
    pdfmetrics.registerFont(font)


    # put it inside a paragraph.
    story.append(Paragraph(
        """This is an ordinary paragraph, which happens to contain
        text in an embedded font:
        <font name="LettErrorRobot-Chrome">LettErrorRobot-Chrome</font>.
        Now for the real challenge...""", styleSheet['Normal']))


    styRobot = ParagraphStyle('Robot', styleSheet['Normal'])
    styRobot.fontSize = 16
    styRobot.leading = 20
    styRobot.fontName = 'LettErrorRobot-Chrome'

    story.append(Paragraph(
                "This whole paragraph is 16-point Letterror-Robot-Chrome.",
                styRobot))
    story.append(FrameBreak())

    if _GIF:
        story.append(Paragraph("Here is an Image flowable obtained from a string filename.",styleSheet['Italic']))
        story.append(platypus.Image(_GIF))
        story.append(Paragraph( "Here is an Image flowable obtained from a utf8 filename.", styleSheet['Italic']))
        story.append(platypus.Image(_GIF.encode('utf8')))
        story.append(Paragraph("Here is an Image flowable obtained from a string file url.",styleSheet['Italic']))
        story.append(platypus.Image(getFurl(_GIF)))
        story.append(Paragraph("Here is an Image flowable obtained from an open file.",styleSheet['Italic']))
        story.append(platypus.Image(open_for_read(_GIF,'b')))
        story.append(FrameBreak())
        try:
            img = platypus.Image('http://www.reportlab.com/rsrc/encryption.gif')
            story.append(Paragraph("Here is an Image flowable obtained from a string http url.",styleSheet['Italic']))
            story.append(img)
        except:
            story.append(Paragraph("The image could not be obtained from a string http url.",styleSheet['Italic']))
        story.append(FrameBreak())

    if _JPG:
        img = platypus.Image(_JPG)
        story.append(Paragraph("Here is an JPEG Image flowable obtained from a filename.",styleSheet['Italic']))
        story.append(img)
        story.append(Paragraph("Here is an JPEG Image flowable obtained from an open file.",styleSheet['Italic']))
        img = platypus.Image(open_for_read(_JPG,'b'))
        story.append(img)
        story.append(FrameBreak())


    return story
Exemplo n.º 35
0
    def test0(self):
        """Make documents with embedded fonts.

        Just vam Rossum has kindly donated a font which we may use
        for testing purposes.  You need to contact him at [email protected]
        if you want to use it for real."""

        #LettError fonts should always be there.  The others are voluntary.

        ok = 1

        c = Canvas(outputfile('test_pdfbase_fontembed.pdf'))
        c.setPageCompression(0)
        c.setFont('Helvetica', 12)
        c.drawString(
            100, 700,
            'This is Helvetica.  The text below should be different fonts...')

        if os.path.isfile('GDB_____.AFM') and os.path.isfile('GDB_____.PFB'):
            # a normal text font
            garaFace = pdfmetrics.EmbeddedType1Face('GDB_____.AFM',
                                                    'GDB_____.PFB')
            faceName = 'AGaramond-Bold'  # pulled from AFM file
            pdfmetrics.registerTypeFace(garaFace)

            garaFont = pdfmetrics.Font('MyGaramondBold', faceName,
                                       'WinAnsiEncoding')
            pdfmetrics.registerFont(garaFont)

            c.setFont('AGaramond-Bold', 12)
            c.drawString(100, 650, 'This should be in AGaramond-Bold')

        if os.path.isfile('CR______.AFM') and os.path.isfile('CR______.PFB'):

            # one with a custom encoding
            cartaFace = pdfmetrics.EmbeddedType1Face('CR______.AFM',
                                                     'CR______.PFB')
            faceName = 'Carta'  # pulled from AFM file
            pdfmetrics.registerTypeFace(cartaFace)

            cartaFont = pdfmetrics.Font('Carta', 'Carta', 'CartaEncoding')
            pdfmetrics.registerFont(cartaFont)

            text = 'This should be in Carta, a map symbol font:'
            c.setFont('Helvetica', 12)
            c.drawString(100, 600, text)
            w = c.stringWidth(text, 'Helvetica', 12)

            c.setFont('Carta', 12)
            c.drawString(100 + w, 600, ' Hello World')

        # LettError sample - creates on demand, we hope
        y = 550
        ##        dgmkFace = pdfmetrics.EmbeddedType1Face('DarkGardenMK.afm','DarkGardenMK.PFB')
        ##
        ##        faceName = 'DarkGardenMK'  # pulled from AFM file
        ##        pdfmetrics.registerTypeFace(dgmkFace)
        ##
        ##        dgmkFont = pdfmetrics.Font('DarkGardenMK', faceName, 'WinAnsiEncoding')
        ##        pdfmetrics.registerFont(dgmk)

        c.setFont('DarkGardenMK', 12)
        c.drawString(100, y, 'This should be in DarkGardenMK')

        def testNamedFont(canv, fontName):
            canv.showPage()
            makeWidthTestForAllGlyphs(canv, fontName, outlining=0)

        testNamedFont(c, 'DarkGardenMK')

        c.save()
Exemplo n.º 36
0
    def loadFont(self, names, src, encoding="WinAnsiEncoding", bold=0, italic=0):

        if names and src:
            if type(names) is types.ListType:
                fontAlias = names
            else:
                fontAlias = [x.lower().strip() for x in names.split(",") if x]

            # XXX Problems with unicode here
            fontAlias = [str(x) for x in fontAlias]
            src = str(src)

            fontName = fontAlias[0]
            baseName, suffix = src.rsplit(".", 1)
            suffix = suffix.lower()

            try:

                if suffix == "ttf":

                    # determine full font name according to weight and style
                    fullFontName = "%s_%d%d" % (fontName, bold, italic)

                    # check if font has already been registered
                    if fullFontName in self.fontList:
                        self.warning("Repeated font embed for %s, skip new embed " % fullFontName)
                    else:

                        # Register TTF font and special name
                        pdfmetrics.registerFont(TTFont(fullFontName, src))

                        # Add or replace missing styles
                        for bold in (0, 1):
                            for italic in (0, 1):
                                if ("%s_%d%d" % (fontName, bold, italic)) not in self.fontList:
                                    addMapping(fontName, bold, italic, fullFontName)

                        # Register "normal" name and the place holder for style
                        self.registerFont(fontName, fontAlias + [fullFontName])

                elif suffix in ("afm", "pfb"):

                    afm = baseName + ".afm"
                    pfb = baseName + ".pfb"

                    # determine full font name according to weight and style
                    fullFontName = "%s_%d%d" % (fontName, bold, italic)

                    # fontNameOriginal = ""
                    # for line in open(afm).readlines()[:-1]:
                    #    if line[:16] == 'StartCharMetrics':
                    #        self.error("Font name not found")
                    #    if line[:8] == 'FontName':
                    #        fontNameOriginal = line[9:].strip()
                    #        break

                    # check if font has already been registered
                    if fullFontName in self.fontList:
                        self.warning("Repeated font embed for %s, skip new embed" % fontName)
                    else:

                        # Include font
                        face = pdfmetrics.EmbeddedType1Face(afm, pfb)
                        fontNameOriginal = face.name
                        pdfmetrics.registerTypeFace(face)
                        # print fontName, fontNameOriginal, fullFontName
                        justFont = pdfmetrics.Font(fullFontName, fontNameOriginal, encoding)
                        pdfmetrics.registerFont(justFont)

                        # Add or replace missing styles
                        for bold in (0, 1):
                            for italic in (0, 1):
                                if ("%s_%d%d" % (fontName, bold, italic)) not in self.fontList:
                                    addMapping(fontName, bold, italic, fontNameOriginal)

                        # Register "normal" name and the place holder for style
                        self.registerFont(fontName, fontAlias + [fullFontName, fontNameOriginal])

                        # import pprint
                        # pprint.pprint(self.fontList)

                else:
                    self.error("wrong attributes for <pdf:font>")

            except Exception, e:
                self.warning(ErrorMsg())
Exemplo n.º 37
0
    def test0(self):
        """Make documents with embedded fonts.

        Just vam Rossum has kindly donated a font which we may use
        for testing purposes.  You need to contact him at [email protected]
        if you want to use it for real."""

        #LettError fonts should always be there.  The others are voluntary.

        ok = 1

        c = Canvas(outputfile('test_pdfbase_fontembed.pdf'))
        c.setPageCompression(0)
        c.setFont('Helvetica', 12)
        c.drawString(100, 700, 'This is Helvetica.  The text below should be different fonts...')

        if os.path.isfile('GDB_____.AFM') and os.path.isfile('GDB_____.PFB'):
            # a normal text font
            garaFace = pdfmetrics.EmbeddedType1Face('GDB_____.AFM','GDB_____.PFB')
            faceName = 'AGaramond-Bold'  # pulled from AFM file
            pdfmetrics.registerTypeFace(garaFace)

            garaFont = pdfmetrics.Font('MyGaramondBold', faceName, 'WinAnsiEncoding')
            pdfmetrics.registerFont(garaFont)

            c.setFont('AGaramond-Bold', 12)
            c.drawString(100, 650, 'This should be in AGaramond-Bold')

        if os.path.isfile('CR______.AFM') and os.path.isfile('CR______.PFB'):

            # one with a custom encoding
            cartaFace = pdfmetrics.EmbeddedType1Face('CR______.AFM','CR______.PFB')
            faceName = 'Carta'  # pulled from AFM file
            pdfmetrics.registerTypeFace(cartaFace)

            cartaFont = pdfmetrics.Font('Carta', 'Carta', 'CartaEncoding')
            pdfmetrics.registerFont(cartaFont)

            text = 'This should be in Carta, a map symbol font:'
            c.setFont('Helvetica', 12)
            c.drawString(100, 600, text)
            w = c.stringWidth(text, 'Helvetica', 12)

            c.setFont('Carta', 12)
            c.drawString(100+w, 600, ' Hello World')

        # LettError sample - creates on demand, we hope
        y = 550
##        dgmkFace = pdfmetrics.EmbeddedType1Face('DarkGardenMK.afm','DarkGardenMK.PFB')
##
##        faceName = 'DarkGardenMK'  # pulled from AFM file
##        pdfmetrics.registerTypeFace(dgmkFace)
##
##        dgmkFont = pdfmetrics.Font('DarkGardenMK', faceName, 'WinAnsiEncoding')
##        pdfmetrics.registerFont(dgmk)

        c.setFont('DarkGardenMK', 12)
        c.drawString(100, y, 'This should be in DarkGardenMK')

        def testNamedFont(canv, fontName):
            canv.showPage()
            makeWidthTestForAllGlyphs(canv, fontName, outlining=0)

        testNamedFont(c, 'DarkGardenMK')
        c.showPage()

        #this tests FontSpecificEncoding
        afmFile = 'callig15.afm'
        pfbFile = 'callig15.pfb'
        face = pdfmetrics.EmbeddedType1Face(afmFile, pfbFile)
        faceName = 'CALLIG15'
        pdfmetrics.registerTypeFace(face)
        font = pdfmetrics.Font(faceName, faceName, face.requiredEncoding,
                            substitutionFonts = pdfmetrics.standardT1SubstitutionFonts)
        pdfmetrics.registerFont(font)

        c.setFont('CALLIG15', 20)
        c.drawString(10, y, 'This should be in CALLIG15')
        c.drawString(10, y-24, b'This should be drawn in')
        c.drawString(10, y-48, u'This should be drawn in')
        c.drawString(10, y-72, 'the font Callig15')

        testNamedFont(c, 'CALLIG15')

        c.save()
Exemplo n.º 38
0
from pychron import pychron_constants
# ============= local library imports  ==========================
from pychron.core.helpers.filetools import view_file, add_extension
from pychron.core.pdf.options import BasePDFOptions, PDFLayoutView
from pychron.core.pdf.pdf_graphics_context import PdfPlotGraphicsContext

for face in pychron_constants.TTF_FONTS:
    for face_name in (face, face.lower()):
        family = face_name
        font = findfont(
            FontProperties(family=face_name, style='normal', weight='normal'))
        try:
            tf = TTFont(face_name, font)
            pdfmetrics.registerFont(tf)
            pdfmetrics.registerTypeFace(TypeFace(face_name))
        except TTFError as e:
            print('invalid font', font, e)


class myPdfPlotGraphicsContext(PdfPlotGraphicsContext):
    def get_full_text_extent(self, textstring):
        fontname = self.gc._fontname
        fontsize = self.gc._fontsize

        try:
            ascent, descent = _fontdata.ascent_descent[fontname]
        except KeyError:
            ascent, descent = (718, -207)

        # get the AGG extent (we just care about the descent)
Exemplo n.º 39
0
 'afii10074', 'afii10075', 'afii10076', 'afii10077', 'afii10078',
 'afii10079', 'afii10080', 'afii10081', 'afii10082', 'afii10083',
 'afii10084', 'afii10085', 'afii10086', 'afii10087', 'afii10088',
 'afii10089', 'afii10090', 'afii10091', 'afii10092', 'afii10093',
 'afii10094', 'afii10095', 'afii10096', 'afii10097'
)

# Replace glyphs from code 128 to code 256 with cp1251 values
for i in range(128,256):
    cyrenc[i] = cp1251[i-128]

# Register newly created encoding
pdfmetrics.registerEncoding(cyrenc)

# Register type face
pdfmetrics.registerTypeFace(cyrFace)

# Register the font with adding '1251' to its name
pdfmetrics.registerFont(pdfmetrics.Font(faceName+'1251', faceName, 'CP1251'))

# Use this font and set font size
c.setFont(faceName+'1251', 90)

# hello - 'Hello!' in Ukrainian. If you have Cyrillic keyboard layout and
# cp1251 system encoding just type Cyrillic text instead of its hexadecimal
# equivalent
hello = '\xcf\xf0\xe8\xe2\xb3\xf2!' 

# Draw this text at last
c.drawString(125, 700, hello)
Exemplo n.º 40
0
    def loadFont(self,
                 names,
                 src,
                 encoding="WinAnsiEncoding",
                 bold=0,
                 italic=0):

        if names and src:
            if type(names) is types.ListType:
                fontAlias = names
            else:
                fontAlias = [x.lower().strip() for x in names.split(",") if x]

            # XXX Problems with unicode here
            fontAlias = [str(x) for x in fontAlias]
            src = str(src)

            fontName = fontAlias[0]
            parts = src.split(".")
            baseName, suffix = ".".join(parts[:-1]), parts[-1]
            suffix = suffix.lower()

            try:

                if suffix == "ttf":

                    # determine full font name according to weight and style
                    fullFontName = "%s_%d%d" % (fontName, bold, italic)

                    # check if font has already been registered
                    if fullFontName in self.fontList:
                        log.warn(
                            self.warning(
                                "Repeated font embed for %s, skip new embed ",
                                fullFontName))
                    else:

                        # Register TTF font and special name
                        pdfmetrics.registerFont(TTFont(fullFontName, src))

                        # Add or replace missing styles
                        for bold in (0, 1):
                            for italic in (0, 1):
                                if ("%s_%d%d" % (fontName, bold,
                                                 italic)) not in self.fontList:
                                    addMapping(fontName, bold, italic,
                                               fullFontName)

                        # Register "normal" name and the place holder for style
                        self.registerFont(fontName, fontAlias + [fullFontName])

                elif suffix in ("afm", "pfb"):

                    afm = baseName + ".afm"
                    pfb = baseName + ".pfb"

                    # determine full font name according to weight and style
                    fullFontName = "%s_%d%d" % (fontName, bold, italic)

                    #fontNameOriginal = ""
                    #for line in open(afm).readlines()[:-1]:
                    #    if line[:16] == 'StartCharMetrics':
                    #        self.error("Font name not found")
                    #    if line[:8] == 'FontName':
                    #        fontNameOriginal = line[9:].strip()
                    #        break

                    # check if font has already been registered
                    if fullFontName in self.fontList:
                        log.warn(
                            self.warning(
                                "Repeated font embed for %s, skip new embed",
                                fontName))
                    else:

                        # Include font
                        face = pdfmetrics.EmbeddedType1Face(afm, pfb)
                        fontNameOriginal = face.name
                        pdfmetrics.registerTypeFace(face)
                        # print fontName, fontNameOriginal, fullFontName
                        justFont = pdfmetrics.Font(fullFontName,
                                                   fontNameOriginal, encoding)
                        pdfmetrics.registerFont(justFont)

                        # Add or replace missing styles
                        for bold in (0, 1):
                            for italic in (0, 1):
                                if ("%s_%d%d" % (fontName, bold,
                                                 italic)) not in self.fontList:
                                    addMapping(fontName, bold, italic,
                                               fontNameOriginal)

                        # Register "normal" name and the place holder for style
                        self.registerFont(
                            fontName,
                            fontAlias + [fullFontName, fontNameOriginal])

                        #import pprint
                        #pprint.pprint(self.fontList)

                else:
                    log.warning(
                        self.warning("wrong attributes for <pdf:font>"))

            except Exception, e:
                log.warn(self.warning("Loading font '%s'", fontName),
                         exc_info=1)
Exemplo n.º 41
0
def autoEmbed(fname):
    """Given a font name, does a best-effort of embedding
    said font and its variants.

    Returns a list of the font names it registered with ReportLab.

    """
    log.info('Trying to embed %s' % fname)
    fontList = []
    f = findFont(fname)
    if f:  # It's a Type 1 font, and we have it
        family = families[f[2]]

        # Register the whole family of faces
        faces = [pdfmetrics.EmbeddedType1Face(*fonts[fn][:2]) for fn in family]
        for face in faces:
            pdfmetrics.registerTypeFace(face)

        for face, name in zip(faces, family):
            fontList.append(name)
            font = pdfmetrics.Font(face, name, "WinAnsiEncoding")
            log.info('Registering font: %s from %s'%\
                        (face,name))
            pdfmetrics.registerFont(font)

        # Map the variants
        regular, italic, bold, bolditalic = family
        addMapping(fname, 0, 0, regular)
        addMapping(fname, 0, 1, italic)
        addMapping(fname, 1, 0, bold)
        addMapping(fname, 1, 1, bolditalic)
        addMapping(regular, 0, 0, regular)
        addMapping(regular, 0, 1, italic)
        addMapping(regular, 1, 0, bold)
        addMapping(regular, 1, 1, bolditalic)
        log.info('Embedding as %s' % fontList)
        return fontList

    variants = findTTFont(fname)
    # It is a TT Font and we found it using fc-match (or found *something*)
    if variants:
        for variant in variants:
            vname = os.path.basename(variant)[:-4]
            try:
                if vname not in pdfmetrics._fonts:
                    _font = TTFont(vname, variant, validate=1)
                    log.info('Registering font: %s from %s'%\
                            (vname,variant))
                    pdfmetrics.registerFont(_font)
            except TTFError:
                log.error('Error registering font: %s from %s' %
                          (vname, variant))
            else:
                fontList.append(vname)
        regular, bold, italic, bolditalic = [
            os.path.basename(variant)[:-4] for variant in variants
        ]
        addMapping(regular, 0, 0, regular)
        addMapping(regular, 0, 1, italic)
        addMapping(regular, 1, 0, bold)
        addMapping(regular, 1, 1, bolditalic)
        log.info('Embedding via findTTFont as %s' % fontList)
    return fontList
Exemplo n.º 42
0
def getExamples():
    """Returns all the example flowable objects"""
    styleSheet = getSampleStyleSheet()

    story = []

    #make a style with indents and spacing
    sty = ParagraphStyle('obvious', None)
    sty.leftIndent = 18
    sty.rightIndent = 18
    sty.firstLineIndent = 18
    sty.spaceBefore = 6
    sty.spaceAfter = 6
    story.append(
        Paragraph(
            """Now for some demo stuff - we need some on this page,
        even before we explain the concepts fully""", styleSheet['BodyText']))
    p = Paragraph(
        """
        Platypus is all about fitting objects into frames on the page.  You
        are looking at a fairly simple Platypus paragraph in Debug mode.
        It has some gridlines drawn around it to show the left and right indents,
        and the space before and after, all of which are attributes set in
        the style sheet.  To be specific, this paragraph has left and
        right indents of 18 points, a first line indent of 36 points,
        and 6 points of space before and after itself.  A paragraph
        object fills the width of the enclosing frame, as you would expect.""",
        sty)

    p.debug = 1  #show me the borders
    story.append(p)

    story.append(
        Paragraph(
            """Same but with justification 1.5 extra leading and green text.""",
            styleSheet['BodyText']))
    p = Paragraph(
        """
        <para align=justify leading="+1.5" fg=green><font color=red>Platypus</font> is all about fitting objects into frames on the page.  You
        are looking at a fairly simple Platypus paragraph in Debug mode.
        It has some gridlines drawn around it to show the left and right indents,
        and the space before and after, all of which are attributes set in
        the style sheet.  To be specific, this paragraph has left and
        right indents of 18 points, a first line indent of 36 points,
        and 6 points of space before and after itself.  A paragraph
        object fills the width of the enclosing frame, as you would expect.</para>""",
        sty)

    p.debug = 1  #show me the borders
    story.append(p)

    story.append(
        platypus.XBox(4 * inch, 0.75 * inch,
                      'This is a box with a fixed size'))

    story.append(
        Paragraph(
            """
        All of this is being drawn within a text frame which was defined
        on the page.  This frame is in 'debug' mode so you can see the border,
        and also see the margins which it reserves.  A frame does not have
        to have margins, but they have been set to 6 points each to create
        a little space around the contents.
        """, styleSheet['BodyText']))

    story.append(FrameBreak())

    #######################################################################
    #     Examples Page 2
    #######################################################################

    story.append(
        Paragraph(
            """
        Here's the base class for Flowable...
        """, styleSheet['Italic']))

    code = '''class Flowable:
        """Abstract base class for things to be drawn.  Key concepts:
    1. It knows its size
    2. It draws in its own coordinate system (this requires the
        base API to provide a translate() function.
        """
    def __init__(self):
        self.width = 0
        self.height = 0
        self.wrapped = 0

    def drawOn(self, canvas, x, y):
        "Tell it to draw itself on the canvas.  Do not override"
        self.canv = canvas
        self.canv.saveState()
        self.canv.translate(x, y)

        self.draw()   #this is the bit you overload

        self.canv.restoreState()
        del self.canv

    def wrap(self, availWidth, availHeight):
        """This will be called by the enclosing frame before objects
        are asked their size, drawn or whatever.  It returns the
        size actually used."""
        return (self.width, self.height)
    '''

    story.append(Preformatted(code, styleSheet['Code'], dedent=4))
    story.append(FrameBreak())
    #######################################################################
    #     Examples Page 3
    #######################################################################

    story.append(
        Paragraph("Here are some examples of the remaining objects above.",
                  styleSheet['Italic']))

    story.append(
        Paragraph("This is a bullet point",
                  styleSheet['Bullet'],
                  bulletText='O'))
    story.append(
        Paragraph("Another bullet point", styleSheet['Bullet'],
                  bulletText='O'))

    story.append(
        Paragraph(
            """Here is a Table, which takes all kinds of formatting options...""",
            styleSheet['Italic']))
    story.append(platypus.Spacer(0, 12))

    g = platypus.Table(
        (('', 'North', 'South', 'East', 'West'),
         ('Quarter 1', 100, 200, 300, 400), ('Quarter 2', 100, 200, 300, 400),
         ('Total', 200, 400, 600, 800)), (72, 36, 36, 36, 36),
        (24, 16, 16, 18))
    style = platypus.TableStyle([
        ('ALIGN', (1, 1), (-1, -1), 'RIGHT'),
        ('ALIGN', (0, 0), (-1, 0), 'CENTRE'),
        ('GRID', (0, 0), (-1, -1), 0.25, colors.black),
        ('LINEBELOW', (0, 0), (-1, 0), 2, colors.black),
        ('LINEBELOW', (1, -1), (-1, -1), 2, (0.5, 0.5, 0.5)),
        ('TEXTCOLOR', (0, 1), (0, -1), colors.black),
        ('BACKGROUND', (0, 0), (-1, 0), (0, 0.7, 0.7))
    ])
    g.setStyle(style)
    story.append(g)
    story.append(FrameBreak())

    #######################################################################
    #     Examples Page 4 - custom fonts
    #######################################################################
    # custom font with LettError-Robot font
    import reportlab.rl_config
    reportlab.rl_config.warnOnMissingFontGlyphs = 0

    from reportlab.pdfbase import pdfmetrics
    fontDir = os.path.join(_RL_DIR, 'fonts')
    face = pdfmetrics.EmbeddedType1Face(
        os.path.join(fontDir, 'DarkGardenMK.afm'),
        os.path.join(fontDir, 'DarkGardenMK.pfb'))
    faceName = face.name  # should be 'DarkGardenMK'
    pdfmetrics.registerTypeFace(face)
    font = pdfmetrics.Font(faceName, faceName, 'WinAnsiEncoding')
    pdfmetrics.registerFont(font)

    # put it inside a paragraph.
    story.append(
        Paragraph(
            """This is an ordinary paragraph, which happens to contain
        text in an embedded font:
        <font name="DarkGardenMK">DarkGardenMK</font>.
        Now for the real challenge...""", styleSheet['Normal']))

    styRobot = ParagraphStyle('Robot', styleSheet['Normal'])
    styRobot.fontSize = 16
    styRobot.leading = 20
    styRobot.fontName = 'DarkGardenMK'

    story.append(
        Paragraph("This whole paragraph is 16-point DarkGardenMK.", styRobot))
    story.append(FrameBreak())

    if _GIF:
        story.append(
            Paragraph(
                "Here is an Image flowable obtained from a string filename.",
                styleSheet['Italic']))
        story.append(platypus.Image(_GIF))
        story.append(
            Paragraph(
                "Here is an Image flowable obtained from a utf8 filename.",
                styleSheet['Italic']))
        #story.append(platypus.Image(fileName2FSEnc(_GIF)))
        story.append(
            Paragraph(
                "Here is an Image flowable obtained from a string file url.",
                styleSheet['Italic']))
        story.append(platypus.Image(getFurl(_GIF)))
        story.append(
            Paragraph("Here is an Image flowable obtained from an open file.",
                      styleSheet['Italic']))
        story.append(platypus.Image(open_for_read(_GIF, 'b')))
        story.append(FrameBreak())
        try:
            img = platypus.Image(
                'http://www.reportlab.com/rsrc/encryption.gif')
            story.append(
                Paragraph(
                    "Here is an Image flowable obtained from a string http url.",
                    styleSheet['Italic']))
            story.append(img)
        except:
            story.append(
                Paragraph(
                    "The image could not be obtained from a string http url.",
                    styleSheet['Italic']))
        story.append(FrameBreak())

    if _JPG:
        img = platypus.Image(_JPG)
        story.append(
            Paragraph(
                "Here is an JPEG Image flowable obtained from a filename.",
                styleSheet['Italic']))
        story.append(img)
        story.append(
            Paragraph(
                "Here is an JPEG Image flowable obtained from an open file.",
                styleSheet['Italic']))
        img = platypus.Image(open_for_read(_JPG, 'b'))
        story.append(img)
        story.append(FrameBreak())

    return story
Exemplo n.º 43
0
def autoEmbed(fname):
    """Given a font name, does a best-effort of embedding
    said font and its variants.

    Returns a list of the font names it registered with ReportLab.

    """
    log.info('Trying to embed %s'%fname)
    fontList = []
    variants=[]
    f = findFont(fname)
    if f : # We have this font located
        if f[0].lower()[-4:]=='.afm': #Type 1 font
            family = families[f[2]]

            # Register the whole family of faces
            faces = [pdfmetrics.EmbeddedType1Face(*fonts[fn.lower()][:2]) for fn in family]
            for face in faces:
                pdfmetrics.registerTypeFace(face)

            for face, name in zip(faces, family):
                fontList.append(name)
                font = pdfmetrics.Font(face, name, "WinAnsiEncoding")
                log.info('Registering font: %s from %s'%\
                            (face,name))
                pdfmetrics.registerFont(font)

            # Map the variants
            regular, italic, bold, bolditalic = family
            addMapping(fname, 0, 0, regular)
            addMapping(fname, 0, 1, italic)
            addMapping(fname, 1, 0, bold)
            addMapping(fname, 1, 1, bolditalic)
            addMapping(regular, 0, 0, regular)
            addMapping(regular, 0, 1, italic)
            addMapping(regular, 1, 0, bold)
            addMapping(regular, 1, 1, bolditalic)
            log.info('Embedding as %s'%fontList)
            return fontList
        else: # A TTF font
            variants = [fonts[f.lower()][0] for f in families[f[2]]]
    if not variants: # Try fc-match
        variants = findTTFont(fname)
    # It is a TT Font and we found it using fc-match (or found *something*)
    if variants:
        for variant in variants:
            vname = os.path.basename(variant)[:-4]
            try:
                if vname not in pdfmetrics._fonts:
                    _font=TTFont(vname, variant)
                    log.info('Registering font: %s from %s'%\
                            (vname,variant))
                    pdfmetrics.registerFont(_font)
            except TTFError:
                log.error('Error registering font: %s from %s'%(vname,variant))
            else:
                fontList.append(vname)
        regular, bold, italic, bolditalic = [
            os.path.basename(variant)[:-4] for variant in variants]
        addMapping(regular, 0, 0, regular)
        addMapping(regular, 0, 1, italic)
        addMapping(regular, 1, 0, bold)
        addMapping(regular, 1, 1, bolditalic)
        log.info('Embedding via findTTFont as %s'%fontList)
    return fontList
Exemplo n.º 44
0
    def loadFont(self,
                 names,
                 src,
                 encoding="WinAnsiEncoding",
                 bold=0,
                 italic=0):

        # XXX Just works for local filenames!
        if names and src:

            file = src
            src = file.uri

            log.debug("Load font %r", src)

            if type(names) is types.ListType:
                fontAlias = names
            else:
                fontAlias = (x.lower().strip() for x in names.split(",") if x)

            # XXX Problems with unicode here
            fontAlias = [str(x) for x in fontAlias]

            fontName = fontAlias[0]
            parts = src.split(".")
            baseName, suffix = ".".join(parts[:-1]), parts[-1]
            suffix = suffix.lower()

            if suffix in ["ttc", "ttf"]:

                # determine full font name according to weight and style
                fullFontName = "%s_%d%d" % (fontName, bold, italic)

                # check if font has already been registered
                if fullFontName in self.fontList:
                    log.warn(
                        self.warning(
                            "Repeated font embed for %s, skip new embed ",
                            fullFontName))
                else:

                    # Register TTF font and special name
                    filename = file.getNamedFile()
                    pdfmetrics.registerFont(TTFont(fullFontName, filename))

                    # Add or replace missing styles
                    for bold in (0, 1):
                        for italic in (0, 1):
                            if ("%s_%d%d" %
                                (fontName, bold, italic)) not in self.fontList:
                                addMapping(fontName, bold, italic,
                                           fullFontName)

                    # Register "normal" name and the place holder for style
                    self.registerFont(fontName, fontAlias + [fullFontName])

            elif suffix in ("afm", "pfb"):

                if suffix == "afm":
                    afm = file.getNamedFile()
                    tfile = pisaFileObject(baseName + ".pfb")
                    pfb = tfile.getNamedFile()
                else:
                    pfb = file.getNamedFile()
                    tfile = pisaFileObject(baseName + ".afm")
                    afm = tfile.getNamedFile()

                # determine full font name according to weight and style
                fullFontName = "%s_%d%d" % (fontName, bold, italic)

                # check if font has already been registered
                if fullFontName in self.fontList:
                    log.warn(
                        self.warning(
                            "Repeated font embed for %s, skip new embed",
                            fontName))
                else:

                    # Include font
                    face = pdfmetrics.EmbeddedType1Face(afm, pfb)
                    fontNameOriginal = face.name
                    pdfmetrics.registerTypeFace(face)
                    # print fontName, fontNameOriginal, fullFontName
                    justFont = pdfmetrics.Font(fullFontName, fontNameOriginal,
                                               encoding)
                    pdfmetrics.registerFont(justFont)

                    # Add or replace missing styles
                    for bold in (0, 1):
                        for italic in (0, 1):
                            if ("%s_%d%d" %
                                (fontName, bold, italic)) not in self.fontList:
                                addMapping(fontName, bold, italic,
                                           fontNameOriginal)

                    # Register "normal" name and the place holder for style
                    self.registerFont(
                        fontName, fontAlias + [fullFontName, fontNameOriginal])
            else:
                log.warning(self.warning("wrong attributes for <pdf:font>"))
Exemplo n.º 45
0
import os
import reportlab
from reportlab.lib.pagesizes import A4                                      # Importa el formato de página A4 ( 595.2755905511812, 841.8897637795277 ) puntos

from reportlab.pdfgen import canvas                                         # Importa el módulo de canvas para generar archivos en .PDF
canvas = canvas.Canvas("Ejemplo12.pdf", pagesize = A4)                 # Crea el archivo "InformeGMP.pdf" en formato .PDF con las dimensiones de una hoja A4


folder = os.path.dirname(reportlab.__file__) + os.sep + 'fonts'
afmFile = os.path.join(folder, 'DarkGardenMK.afm')
pfbFile = os.path.join(folder, 'DarkGardenMK.pfb')
from reportlab.pdfbase import pdfmetrics
justFace = pdfmetrics.EmbeddedType1Face(afmFile, pfbFile)
faceName = 'DarkGardenMK' # pulled from AFM file
pdfmetrics.registerTypeFace(justFace)
justFont = pdfmetrics.Font('DarkGardenMK', faceName, 'WinAnsiEncoding')
pdfmetrics.registerFont(justFont)
canvas.setFont('DarkGardenMK', 32)
canvas.drawString(10, 150, 'This should be in')
canvas.drawString(10, 100, 'DarkGardenMK')
canvas.save( )                                                        # 
Exemplo n.º 46
0
 def process(self):
     args = self.getAttributeValues(valuesOnly=True)
     face = pdfmetrics.EmbeddedType1Face(*args)
     pdfmetrics.registerTypeFace(face)
Exemplo n.º 47
0
def __registerFont__(fontname, afmFilename, pfbFilename):
    justFace = pdfmetrics.EmbeddedType1Face(afmFilename, pfbFilename)
    pdfmetrics.registerTypeFace(justFace)
    justFont = pdfmetrics.Font(fontname, fontname, 'WinAnsiEncoding')
    pdfmetrics.registerFont(justFont)