Esempio n. 1
0
    def _doPrintingPdf(self):
        if self.printFile:
            pdf_file_name = self.printFile
        elif self.printDir:
            pdf_file_name = self._getNextSpoolFile(extension='pdf')
        else:
            pdf_file_name = tempfile.mktemp(".pdf")
        # print("Printing to: %s" % (pdf_file_name))

        # ## FONT # ##
        from reportlab.pdfbase import pdfmetrics
        from reportlab.pdfbase.ttfonts import TTFont
        pdfmetrics.registerFont(
            TTFont('Epson1', self._getFontPath('fonts/epson1.ttf')))
        pdfmetrics.registerFontFamily('Epson1', normal='Epson1')
        # ## FONT # ##

        styles = getSampleStyleSheet()
        code = styles["Code"]
        pre = code.clone('Pre', leftIndent=0, fontName='Epson1')
        normal = styles["Normal"]
        styles.add(pre)

        doc = SimpleDocTemplate(pdf_file_name)
        story = [Preformatted(open(self.source_file_name).read(), pre)]
        doc.build(story)
        # win32api.ShellExecute (0, "print", pdf_file_name, None, ".", 0)
        return pdf_file_name
Esempio n. 2
0
def register_fonts():

    for variation in list(FONT_INFO.keys()):
        pdfmetrics.registerFont(TTFont(FONT_INFO[variation][0], FONT_DIR+FONT_INFO[variation][1]))

    pdfmetrics.registerFontFamily(
        FONT_FAMILY,
        normal=FONT_INFO['normal'][0],
        bold=FONT_INFO['bold'][0],
        italic=FONT_INFO['italic'][0],
        boldItalic=FONT_INFO['boldItalic'][0])


    for key in list(CHESS_FONTS.keys()):
        pdfmetrics.registerFont(TTFont(CHESS_FONTS[key][0], CHESS_FONTS[key][1]))
        pdfmetrics.registerFontFamily(key, normal=key, bold=key, italic=key, boldItalic=key)
        styles = getSampleStyleSheet()
        styles.add(
            ParagraphStyle(
                name='chess'+key,
                wordWrap=False,
                fontName=CHESS_FONTS[key][0],
                fontSize=FONT_SIZE['chess'],
                spaceAfter=0))
        CHESS_FONT_STYLES[key] = styles['chess'+key]
Esempio n. 3
0
    def _configure_fonts(self, font):
        self.normal = font
        self.italic = '{}It'.format(self.normal)
        self.bold = '{}Bd'.format(self.normal)
        self.bold_italic = '{}BdIt'.format(self.normal)

        fonts_path = os.path.join(os.path.dirname(os.path.realpath(__file__)),
                                  'resources', 'fonts')

        pdfmetrics.registerFont(
            TTFont(self.normal, os.path.join(fonts_path, 'DejaVuSans.ttf')))
        pdfmetrics.registerFont(
            TTFont(self.italic,
                   os.path.join(fonts_path, 'DejaVuCondensedSansOblique.ttf')))
        pdfmetrics.registerFont(
            TTFont(self.bold, os.path.join(fonts_path, 'DejaVuSansBold.ttf')))
        pdfmetrics.registerFont(
            TTFont(self.bold_italic,
                   os.path.join(fonts_path, 'DejaVuSansBoldOblique.ttf')))

        registerFontFamily(self.normal,
                           normal=self.normal,
                           bold=self.bold,
                           italic=self.italic,
                           boldItalic=self.bold_italic)
Esempio n. 4
0
 def __init__(self, session, config, parent):
     AccumulatingDocumentFactory.__init__(self, session, config, parent)
     # text to use as header and footer plus switch for columns or not
     self.headerString = self.get_setting(session, 'header', None)
     self.footerString = self.get_setting(session, 'footer', None)
     self.columns = int(self.get_setting(session, 'columns', 0))
     
     #font crap       
     #psfont can either be helvetica (default), courier or times-roman
     #TTfonts need to be installed on the system and all 4 font types need to be specified with a path to their installed location (needed for some obscure accented characters outside - Latin 1 and 2 I think)
     self.psfont = self.get_setting(session, 'psfont', 'helvetica')
     self.ttfontNormal = self.get_setting(session, 'ttfontNormal', None)        
     self.ttfontBold = self.get_setting(session, 'ttfontBold', None)        
     self.ttfontItalic = self.get_setting(session, 'ttfontItalic', None)        
     self.ttfontBoldItalic = self.get_setting(session, 'ttfontBoldItalic', None)
     if self.ttfontNormal is not None:
         self.normaltag = self.ttfontNormal[self.ttfontNormal.rfind('/')+1:self.ttfontNormal.rfind('.')]
         self.boldtag = self.ttfontBold[self.ttfontBold.rfind('/')+1:self.ttfontBold.rfind('.')]
         self.italictag = self.ttfontItalic[self.ttfontItalic.rfind('/')+1:self.ttfontItalic.rfind('.')]
         self.bolditalictag = self.ttfontBoldItalic[self.ttfontBoldItalic.rfind('/')+1:self.ttfontBoldItalic.rfind('.')]
          
         pdfmetrics.registerFont(TTFont(self.normaltag, self.ttfontNormal))
         pdfmetrics.registerFont(TTFont(self.boldtag, self.ttfontBold))
         pdfmetrics.registerFont(TTFont(self.italictag, self.ttfontItalic))
         pdfmetrics.registerFont(TTFont(self.bolditalictag, self.ttfontBoldItalic))               
         registerFontFamily(self.normaltag,normal=self.normaltag,bold=self.boldtag,italic=self.italictag,boldItalic=self.bolditalictag)
         ParagraphStyle.fontName = self.normaltag
     else:
         ParagraphStyle.fontName = self.psfont
Esempio n. 5
0
    def _doPrintingPdf(self):
        if self.printDir:
           pdf_file_name = tempfile.mktemp (".pdf", self.printDir)
        else:
           pdf_file_name = tempfile.mktemp (".pdf")
        print("Printing to: %s" % (pdf_file_name))

        ### FONT ###
        from reportlab.pdfbase import pdfmetrics
        from reportlab.pdfbase.ttfonts import TTFont
        pdfmetrics.registerFont(TTFont('Epson1', 'fonts/epson1.ttf'))
        pdfmetrics.registerFontFamily('Epson1',normal='Epson1')
        ### FONT ###


        styles = getSampleStyleSheet ()
        code = styles["Code"]
        pre = code.clone('Pre', leftIndent=0, fontName='Epson1')
        normal = styles["Normal"]
        styles.add(pre)



        doc = SimpleDocTemplate (pdf_file_name)
        story=[Preformatted(open (self.source_file_name).read(), pre)]
        doc.build (story)
        #win32api.ShellExecute (0, "print", pdf_file_name, None, ".", 0)
        return pdf_file_name
Esempio n. 6
0
    def generate_pdf(self):
        response = HttpResponse(content_type="application/pdf")
        pdf_name = self.generate_filename(".pdf")
        response["Content-Disposition"] = "attachment; filename=%s" % pdf_name

        buff = BytesIO()
        pdfmetrics.registerFont(
            TTFont(
                "Calibri",
                "/var/local/copernicus/insitu/static/fonts/CalibriRegular.ttf",
            ))
        pdfmetrics.registerFont(
            TTFont(
                "Calibri-Bold",
                "/var/local/copernicus/insitu/static/fonts/CalibriBold.ttf",
            ))
        pdfmetrics.registerFontFamily("Calibri",
                                      normal="Calibri",
                                      bold="CalibriBold")

        menu_pdf = SimpleDocTemplate(
            buff,
            rightMargin=10,
            pagesize=landscape(A4),
            leftMargin=10,
            topMargin=30,
            bottomMargin=10,
        )

        self.generate_pdf_file(menu_pdf)
        response.write(buff.getvalue())
        buff.close()
        return response
Esempio n. 7
0
    def _init_font_family(self):
        """Register the desired font with :py:mod:`reportlab`

        This ensures that `<i></i>` and `<b></b>` as cell content work well.
        """
        # Set root of fonts to the folder containing this file.
        path_to_fonts = PurePath(__file__).parent.joinpath("fonts")

        # Finally lead and register fonts with reportlab.
        registerFont(
            TTFont("normal_font", path_to_fonts.joinpath(self._font.normal)))
        registerFont(
            TTFont("bold_font", path_to_fonts.joinpath(self._font.bold)))
        registerFont(
            TTFont("italic_font", path_to_fonts.joinpath(self._font.italic)))
        registerFont(
            TTFont("bolditalic_font",
                   path_to_fonts.joinpath(self._font.bolditalic)))
        registerFontFamily(
            "custom_font",
            normal="normal_font",
            bold="bold_font",
            italic="italic_font",
            boldItalic="bolditalic_font",
        )
Esempio n. 8
0
def register_fonts():
    """
    Register fonts used for generation of PDF documents.
    """

    reportlab.rl_config.warnOnMissingFontGlyphs = 0

    registerFont(TTFont(
        'Bookman',
        join(FONT_DIR, 'URWBookman-Regular.ttf')))

    registerFont(TTFont(
        'BookmanB',
        join(FONT_DIR, 'URWBookman-Bold.ttf')))

    registerFont(TTFont(
        'BookmanI',
        join(FONT_DIR, 'URWBookman-Italic.ttf')))

    registerFont(TTFont(
        'BookmanBI',
        join(FONT_DIR, 'URWBookman-BoldItalic.ttf')))

    registerFontFamily(
        'Bookman',
        normal='Bookman',
        bold='BookmanB',
        italic='BookmanI',
        boldItalic='BookmanBI')
Esempio n. 9
0
def load_ttf_font(font_name, variants):
    '''Try to load TTF font.

    :param variants: dictionary of variants and corresponding file names.

    It tries to find the font in all directories reportlab looks in (+ few others).
    It uses a few different extensions (ttf, otf, ttc + caps alternatives)
    '''
    kwargs = {}
    for key, file_name in variants.items():
        if file_name:
            for extension in ".ttf", ".otf", ".ttc", ".TTF", ".OTF", ".TTC":
                try:
                    registered_name = _get_font_name(font_name, key)
                    # print file_name + extension
                    pdfmetrics.registerFont(TTFont(registered_name, file_name + extension))
                    kwargs[key] = registered_name
                    break
                except TTFError as e:
                    # if 'postscript outlines are not supported' in e.:
                    #     print(e)
                    pass
                except Exception as e:
                    # print e
                    pass
    try:
        if len(kwargs):
            print("Font '%s' found (%s)" % (font_name, ", ".join(kwargs.keys())))
            pdfmetrics.registerFontFamily(font_name, **kwargs)
            return True
    except:
        return False
Esempio n. 10
0
 def __init__(self, session, config, parent):
     AccumulatingDocumentFactory.__init__(self, session, config, parent)
     # text to use as header and footer plus switch for columns or not
     self.headerString = self.get_setting(session, 'header', None)
     self.footerString = self.get_setting(session, 'footer', None)
     self.columns = int(self.get_setting(session, 'columns', 0))
     
     #font crap       
     #psfont can either be helvetica (default), courier or times-roman
     #TTfonts need to be installed on the system and all 4 font types need to be specified with a path to their installed location (needed for some obscure accented characters outside - Latin 1 and 2 I think)
     self.psfont = self.get_setting(session, 'psfont', 'helvetica')
     self.ttfontNormal = self.get_setting(session, 'ttfontNormal', None)        
     self.ttfontBold = self.get_setting(session, 'ttfontBold', None)        
     self.ttfontItalic = self.get_setting(session, 'ttfontItalic', None)        
     self.ttfontBoldItalic = self.get_setting(session, 'ttfontBoldItalic', None)
     if self.ttfontNormal != None:
         self.normaltag = self.ttfontNormal[self.ttfontNormal.rfind('/')+1:self.ttfontNormal.rfind('.')]
         self.boldtag = self.ttfontBold[self.ttfontBold.rfind('/')+1:self.ttfontBold.rfind('.')]
         self.italictag = self.ttfontItalic[self.ttfontItalic.rfind('/')+1:self.ttfontItalic.rfind('.')]
         self.bolditalictag = self.ttfontBoldItalic[self.ttfontBoldItalic.rfind('/')+1:self.ttfontBoldItalic.rfind('.')]
          
         pdfmetrics.registerFont(TTFont(self.normaltag, self.ttfontNormal))
         pdfmetrics.registerFont(TTFont(self.boldtag, self.ttfontBold))
         pdfmetrics.registerFont(TTFont(self.italictag, self.ttfontItalic))
         pdfmetrics.registerFont(TTFont(self.bolditalictag, self.ttfontBoldItalic))               
         registerFontFamily(self.normaltag,normal=self.normaltag,bold=self.boldtag,italic=self.italictag,boldItalic=self.bolditalictag)
         ParagraphStyle.fontName = self.normaltag
     else:
         ParagraphStyle.fontName = self.psfont
Esempio n. 11
0
 def __init__(self, standalone):
     if standalone:
         pdfmetrics.registerFont(
             TTFont(_baseFontName, 'resources/calibri.ttf'))
         pdfmetrics.registerFont(
             TTFont(_baseFontNameB, 'resources/calibrib.ttf'))
         pdfmetrics.registerFont(
             TTFont(_baseFontNameI, 'resources/calibrii.ttf'))
         pdfmetrics.registerFont(
             TTFont(_baseFontNameBI, 'resources/calibriz.ttf'))
     else:
         pdfmetrics.registerFont(
             TTFont(_baseFontName,
                    utils.GoogleUtils.get_from_resources('calibri.ttf')))
         pdfmetrics.registerFont(
             TTFont(_baseFontNameB,
                    utils.GoogleUtils.get_from_resources('calibrib.ttf')))
         pdfmetrics.registerFont(
             TTFont(_baseFontNameI,
                    utils.GoogleUtils.get_from_resources('calibrii.ttf')))
         pdfmetrics.registerFont(
             TTFont(_baseFontNameBI,
                    utils.GoogleUtils.get_from_resources('calibriz.ttf')))
     registerFontFamily(_baseFontName,
                        normal=_baseFontName,
                        bold=_baseFontNameB,
                        italic=_baseFontNameI,
                        boldItalic=_baseFontNameBI)
Esempio n. 12
0
    def docinit(self, els):
        from reportlab.lib.fonts import addMapping
        from reportlab.pdfbase import pdfmetrics
        from reportlab.pdfbase.ttfonts import TTFont

        for node in els:
            for font in node.getElementsByTagName('registerFont'):
                name = font.getAttribute('fontName').encode('ascii')
                fname = font.getAttribute('fontFile').encode('ascii')
                pdfmetrics.registerFont(TTFont(name, fname))
                addMapping(name, 0, 0, name)    #normal
                addMapping(name, 0, 1, name)    #italic
                addMapping(name, 1, 0, name)    #bold
                addMapping(name, 1, 1, name)    #italic and bold
            for font in node.getElementsByTagName('registerTTFont'):
                name = font.getAttribute('faceName').encode('ascii')
                fname = font.getAttribute('fileName').encode('ascii')
                pdfmetrics.registerFont(TTFont(name, fname))	# , subfontIndex=subfontIndex
            for font in node.getElementsByTagName('registerFontFamily'):
                pdfmetrics.registerFontFamily(
                        font.getAttribute('normal').encode('ascii'),
                        normal = font.getAttribute('normal').encode('ascii'),
                        bold = font.getAttribute('bold').encode('ascii'),
                        italic = font.getAttribute('italic').encode('ascii'),
                        boldItalic = font.getAttribute('boldItalic').encode('ascii')
                )
Esempio n. 13
0
def prepare_fonts():
    global PREPARED_FONTS
    if PREPARED_FONTS:
        return
    pdfmetrics.registerFont(
        TTFont('Montserrat', font('Montserrat-Regular.ttf')))
    pdfmetrics.registerFont(
        TTFont('MontserratBold', font('Montserrat-Bold.ttf')))
    pdfmetrics.registerFont(
        TTFont('MontserratItalic', font('Montserrat-Italic.ttf')))
    pdfmetrics.registerFont(
        TTFont('MontserratBoldItalic', font('Montserrat-BoldItalic.ttf')))
    pdfmetrics.registerFontFamily('Montserrat',
                                  normal='Montserrat',
                                  bold='MontserratBold',
                                  italic='MontserratItalic',
                                  boldItalic='MontserratBoldItalic')

    pdfmetrics.registerFont(TTFont('NotoSans', font('NotoSans-Regular.ttf')))
    pdfmetrics.registerFont(TTFont('NotoSansBold', font('NotoSans-Bold.ttf')))
    pdfmetrics.registerFont(
        TTFont('NotoSansItalic', font('NotoSans-Italic.ttf')))
    pdfmetrics.registerFont(
        TTFont('NotoSansBoldItalic', font('NotoSans-BoldItalic.ttf')))
    pdfmetrics.registerFontFamily('NotoSans',
                                  normal='NotoSans',
                                  bold='NotoSansBold',
                                  italic='NotoSansItalic',
                                  boldItalic='NotoSansBoldItalic')
    PREPARED_FONTS = True
Esempio n. 14
0
def register_font_path(font_path):
    # Caching seems to cause problems. Disable for now
    ff = fontfinder.FontFinder(useCache=False)
    ff.addDirectory(font_path, recur=True)

    try:
        ff.search()
    except (KeyError, Exception) as fferror:
        logging.warning("Problem parsing font: {}".format(fferror))

    for family_name in ff.getFamilyNames():
        fonts_in_family = ff.getFontsInFamily(family_name)
        for font in fonts_in_family:
            if len(fonts_in_family) == 1:
                try:
                    ttfont = TTFont(family_name.decode("utf-8"), font.fileName)
                    pdfmetrics.registerFont(ttfont)
                    pdfmetrics.registerFontFamily(family_name)
                except TTFError as e:
                    logging.warning("Could not register font {}, {}".format(
                        family_name, e))
                    continue
            elif len(fonts_in_family) > 1:
                '''If font family has multiple weights/styles'''
                font_name = family_name + "-".encode() + font.styleName
                font_name = font_name.decode("utf-8")
                try:
                    ttfont = TTFont(font_name, font.fileName)
                    pdfmetrics.registerFont(ttfont)
                    addMapping(font.familyName, font.isBold, font.isItalic,
                               font_name)
                except TTFError as e:
                    logging.warning("Could not register font {}, {}".format(
                        family_name, e))
                    continue
Esempio n. 15
0
  def __init__(self, title, filename, background=Gold, \
               Top_Right_To_Inline_Summary_Cutover = 14,\
               Right_Side_Font_Size=20):
    self.Right_Side_Font_Size=Right_Side_Font_Size
    self.title=title
    self.Top_Right_To_Inline_Summary_Cutover = \
      Top_Right_To_Inline_Summary_Cutover

    self.Resource_Path=os.path.dirname(os.path.realpath( __file__ ))+"/../"

    pdfmetrics.registerFont(TTFont('Copperplate-Bold', \
      self.Resource_Path+'ufonts.com_copperplate-bold.ttf'))
    pdfmetrics.registerFont(TTFont('Copperplate', \
      self.Resource_Path+'ufonts.com_copperplate.ttf'))
    registerFontFamily('Copperplate', normal='Copperplate',
                                      bold='Copperplate-Bold',
                                      italic='Copperplate',
                                      boldItalic='Copplerplate-Bold')
    self.doc = BaseDocTemplate(filename, pagesize=letter, leftMargin=0.0*inch,
      rightMargin=0.0*inch, topMargin=0.0*inch, bottomMargin=0.5*inch)
    self.doc.gs_background = background


    frame = Frame(self.doc.leftMargin, self.doc.bottomMargin, self.doc.width,
                  self.doc.height, id='normal')
    template = PageTemplate(id='test', frames=frame, onPage=utils.Page_Setup)
    self.doc.addPageTemplates([template])

    self.doc.elements=[]
Esempio n. 16
0
 def addStyle(self, data):
     def addFont(fontfile):
         if not fontfile:
             return None
         elif fontfile.endswith(".ttf") or fontfile.endswith(".otf"):
             fontname = os.path.splitext(fontfile)[0]
             pdfmetrics.registerFont(TTFont(fontname, fontfile))
             print "Registered", fontfile
             return fontname
         else:
             return fontfile
     name = data.get('name', "")
     s = ParagraphStyle(name)
     normal = addFont(data.get('font', "Helvetica"))
     bold = addFont(data.get('bold', None))
     italic = addFont(data.get('italic', None))
     bolditalic = addFont(data.get('bolditalic', None))
     pdfmetrics.registerFontFamily(normal, normal=normal, bold=bold or normal, italic=italic or normal, boldItalic=bolditalic or normal)
     s.fontName = normal
     s.fontSize = data.get('size', 10)
     s.alignment = dict(center=TA_CENTER, left=TA_LEFT, right=TA_RIGHT)[data.get('align', 'left')]
     s.leading = data.get('leading', s.leading)
     s.valign = data.get('valign', "top")
     s.textColor = data.get('color', "#ff000000")
     self.styles[name] = s
Esempio n. 17
0
def addFontFile(font='castellar'):

    pdfmetrics.registerFont(TTFont('Castellar', 'castellar.ttf'))
    registerFontFamily('Castellar',
                       normal='Castellar',
                       bold='Castellar',
                       italic='Castellar',
                       boldItalic='Castellar')
Esempio n. 18
0
def _register_zhfont():
    """ 中文字體處理
    """
    #pdfmetrics.registerFont(UnicodeCIDFont('MSung-Light'))
    #pdfmetrics.registerFont(UnicodeCIDFont('STSong-Light'))
    pdfmetrics.registerFont(TTFont('msjh', 'c:/msjh.ttf'))
    pdfmetrics.registerFont(TTFont('msjhbd', 'c:/msjhbd.ttf'))
    registerFontFamily('yahei',normal='msjh',bold='msjhbd',italic='msjh',boldItalic='msjhbd')
Esempio n. 19
0
def run(pagesize=None, verbose=0, outDir=None):
    import sys, os
    from reportlab.lib.utils import open_and_read
    cwd = os.getcwd()
    docsDir = os.path.dirname(os.path.dirname(sys.argv[0]) or cwd)
    topDir = os.path.dirname(docsDir)
    if not outDir: outDir = docsDir
    G = {}
    sys.path.insert(0, topDir)
    from reportlab.pdfbase.pdfmetrics import registerFontFamily
    from reportlab.pdfbase import pdfmetrics
    from reportlab.pdfbase.ttfonts import TTFont
    pdfmetrics.registerFont(TTFont('Vera', 'Vera.ttf'))
    pdfmetrics.registerFont(TTFont('VeraBd', 'VeraBd.ttf'))
    pdfmetrics.registerFont(TTFont('VeraIt', 'VeraIt.ttf'))
    pdfmetrics.registerFont(TTFont('VeraBI', 'VeraBI.ttf'))
    registerFontFamily('Vera',
                       normal='Vera',
                       bold='VeraBd',
                       italic='VeraIt',
                       boldItalic='VeraBI')
    from reportlab.rl_config import defaultPageSize
    from tools.docco.rl_doc_utils import setStory, getStory, H1, H2, H3, H4
    from tools.docco.rltemplate import RLDocTemplate
    from tools.docco import rl_doc_utils
    exec('from tools.docco.rl_doc_utils import *', G, G)
    destfn = os.path.join(outDir, 'reportlab-userguide.pdf')
    doc = RLDocTemplate(destfn, pagesize=pagesize or defaultPageSize)

    #this builds the story
    setStory()

    for f in (
            'ch1_intro',
            'ch2_graphics',
            'ch2a_fonts',
            'ch3_pdffeatures',
            'ch4_platypus_concepts',
            'ch5_paragraphs',
            'ch6_tables',
            'ch7_custom',
            'graph_intro',
            'graph_concepts',
            'graph_charts',
            'graph_shapes',
            'graph_widgets',
            'app_demos',
    ):
        #python source is supposed to be utf8 these days
        exec(open_and_read(f + '.py', mode='r'), G, G)
    del G

    story = getStory()
    if verbose: print('Built story contains %d flowables...' % len(story))
    doc.multiBuild(story)
    if verbose: print('Saved "%s"' % destfn)
Esempio n. 20
0
 def _register_fonts(self):
     """
     Register fonts with reportlab. By default, this registers the OpenSans font family
     """
     pdfmetrics.registerFont(TTFont('OpenSans', finders.find('fonts/OpenSans-Regular.ttf')))
     pdfmetrics.registerFont(TTFont('OpenSansIt', finders.find('fonts/OpenSans-Italic.ttf')))
     pdfmetrics.registerFont(TTFont('OpenSansBd', finders.find('fonts/OpenSans-Bold.ttf')))
     pdfmetrics.registerFont(TTFont('OpenSansBI', finders.find('fonts/OpenSans-BoldItalic.ttf')))
     pdfmetrics.registerFontFamily('OpenSans', normal='OpenSans', bold='OpenSansBd',
                                   italic='OpenSansIt', boldItalic='OpenSansBI')
Esempio n. 21
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')
Esempio n. 22
0
 def _register_fonts(self):
     """
     Register fonts with reportlab. By default, this registers the OpenSans font family
     """
     pdfmetrics.registerFont(TTFont('OpenSans', finders.find('fonts/OpenSans-Regular.ttf')))
     pdfmetrics.registerFont(TTFont('OpenSansIt', finders.find('fonts/OpenSans-Italic.ttf')))
     pdfmetrics.registerFont(TTFont('OpenSansBd', finders.find('fonts/OpenSans-Bold.ttf')))
     pdfmetrics.registerFont(TTFont('OpenSansBI', finders.find('fonts/OpenSans-BoldItalic.ttf')))
     pdfmetrics.registerFontFamily('OpenSans', normal='OpenSans', bold='OpenSansBd',
                                   italic='OpenSansIt', boldItalic='OpenSansBI')
Esempio n. 23
0
def run(pagesize=None, verbose=0, outDir=None):
    import sys, os
    from reportlab.lib.utils import open_and_read

    cwd = os.getcwd()
    docsDir = os.path.dirname(os.path.dirname(sys.argv[0]) or cwd)
    topDir = os.path.dirname(docsDir)
    if not outDir:
        outDir = docsDir
    G = {}
    sys.path.insert(0, topDir)
    from reportlab.pdfbase.pdfmetrics import registerFontFamily
    from reportlab.pdfbase import pdfmetrics
    from reportlab.pdfbase.ttfonts import TTFont

    pdfmetrics.registerFont(TTFont("Vera", "Vera.ttf"))
    pdfmetrics.registerFont(TTFont("VeraBd", "VeraBd.ttf"))
    pdfmetrics.registerFont(TTFont("VeraIt", "VeraIt.ttf"))
    pdfmetrics.registerFont(TTFont("VeraBI", "VeraBI.ttf"))
    registerFontFamily("Vera", normal="Vera", bold="VeraBd", italic="VeraIt", boldItalic="VeraBI")
    from tools.docco.rl_doc_utils import setStory, getStory, RLDocTemplate, defaultPageSize, H1, H2, H3, H4
    from tools.docco import rl_doc_utils

    exec("from tools.docco.rl_doc_utils import *", G, G)
    destfn = os.path.join(outDir, "reportlab-userguide.pdf")
    doc = RLDocTemplate(destfn, pagesize=pagesize or defaultPageSize)

    # this builds the story
    setStory()

    for f in (
        "ch1_intro",
        "ch2_graphics",
        "ch2a_fonts",
        "ch3_pdffeatures",
        "ch4_platypus_concepts",
        "ch5_paragraphs",
        "ch6_tables",
        "ch7_custom",
        "graph_intro",
        "graph_concepts",
        "graph_charts",
        "graph_shapes",
        "graph_widgets",
        "app_demos",
    ):
        exec(open_and_read(f + ".py", mode="t"), G, G)
    del G

    story = getStory()
    if verbose:
        print("Built story contains %d flowables..." % len(story))
    doc.multiBuild(story)
    if verbose:
        print('Saved "%s"' % destfn)
Esempio n. 24
0
def _register_pdf_fonts():
    pdfmetrics.registerFont(TTFont('DejaVuSerif', 'DejaVuSerif.ttf'))
    pdfmetrics.registerFont(TTFont('DejaVuSerifBd', 'DejaVuSerif-Bold.ttf'))
    pdfmetrics.registerFont(TTFont('DejaVuSerifIt', 'DejaVuSerif-Italic.ttf'))
    pdfmetrics.registerFont(
        TTFont('DejaVuSerifBI', 'DejaVuSerif-BoldItalic.ttf'))
    pdfmetrics.registerFontFamily('DejaVuSerif',
                                  normal='DejaVuSerif',
                                  bold='DejaVuSerifBd',
                                  italic='DejaVuSerifIt',
                                  boldItalic='DejaVuSerifBI')
Esempio n. 25
0
File: helpers.py Progetto: oledm/gmp
 def setup_fonts(self):
     fonts = (
         ('Times', 'times.ttf'), 
         ('Times Bold', 'timesbd.ttf'),
         ('Times Italic', 'timesi.ttf'),
         ('Times Bold Italic', 'timesbi.ttf'),
     )
     list(map(self.register_font, *zip(*fonts)))
     pdfmetrics.registerFontFamily(
         'Times', normal='Times', bold='Times Bold',
         italic='Times Bold Italic', boldItalic='Times Bold Italic')
Esempio n. 26
0
def set_fonts():
    # register fonts
    registerFont(TTFont('FiraSans',
                        'FiraSans-Regular.ttf'))  # Just some font imports
    registerFont(TTFont('FiraSansBold', 'FiraSans-Bold.ttf'))
    registerFont(TTFont('FiraSansItalic', 'FiraSans-Italic.ttf'))
    registerFont(TTFont('FiraSansBoldItalic', 'FiraSans-BoldItalic.ttf'))
    registerFontFamily('FiraSans',
                       normal='FiraSans',
                       bold='FiraSansBold',
                       italic='FiraSansItalic')
Esempio n. 27
0
 def __init__(self, standalone):
     if standalone:
         pdfmetrics.registerFont(TTFont(_baseFontName, 'resources/calibri.ttf'))
         pdfmetrics.registerFont(TTFont(_baseFontNameB, 'resources/calibrib.ttf'))
         pdfmetrics.registerFont(TTFont(_baseFontNameI, 'resources/calibrii.ttf'))
         pdfmetrics.registerFont(TTFont(_baseFontNameBI, 'resources/calibriz.ttf'))
     else:
         pdfmetrics.registerFont(TTFont(_baseFontName, utils.GoogleUtils.get_from_resources('calibri.ttf')))
         pdfmetrics.registerFont(TTFont(_baseFontNameB, utils.GoogleUtils.get_from_resources('calibrib.ttf')))
         pdfmetrics.registerFont(TTFont(_baseFontNameI, utils.GoogleUtils.get_from_resources('calibrii.ttf')))
         pdfmetrics.registerFont(TTFont(_baseFontNameBI, utils.GoogleUtils.get_from_resources('calibriz.ttf')))
     registerFontFamily(_baseFontName, normal=_baseFontName,bold=_baseFontNameB,italic=_baseFontNameI,boldItalic=_baseFontNameBI)
Esempio n. 28
0
def run(pagesize=None, verbose=0, outDir=None):
    import sys,os
    from reportlab.lib.utils import open_and_read, asUnicode
    cwd = os.getcwd()
    docsDir=os.path.dirname(os.path.dirname(sys.argv[0]) or cwd)
    topDir=os.path.dirname(docsDir)
    if not outDir: outDir=docsDir
    G = {}
    sys.path.insert(0,topDir)
    from reportlab.pdfbase.pdfmetrics import registerFontFamily
    from reportlab.pdfbase import pdfmetrics
    from reportlab.pdfbase.ttfonts import TTFont
    pdfmetrics.registerFont(TTFont('Vera', 'Vera.ttf'))
    pdfmetrics.registerFont(TTFont('VeraBd', 'VeraBd.ttf'))
    pdfmetrics.registerFont(TTFont('VeraIt', 'VeraIt.ttf'))
    pdfmetrics.registerFont(TTFont('VeraBI', 'VeraBI.ttf'))
    registerFontFamily('Vera',normal='Vera',bold='VeraBd',italic='VeraIt',boldItalic='VeraBI')
    from tools.docco.rl_doc_utils import setStory, getStory, RLDocTemplate, defaultPageSize, H1, H2, H3, H4
    from tools.docco import rl_doc_utils
    exec('from tools.docco.rl_doc_utils import *', G, G)
    destfn = os.path.join(outDir,'reportlab-userguide.pdf')
    doc = RLDocTemplate(destfn,pagesize = pagesize or defaultPageSize)


    #this builds the story
    setStory()

    for f in (
        'ch1_intro',
        'ch2_graphics',
        'ch2a_fonts',
        'ch3_pdffeatures',
        'ch4_platypus_concepts',
        'ch5_paragraphs',
        'ch6_tables',
        'ch7_custom',
        'graph_intro',
        'graph_concepts',
        'graph_charts',
        'graph_shapes',
        'graph_widgets',
        'app_demos',
        ):
        #python source is supposed to be utf8 these days
        exec(asUnicode(open_and_read(f+'.py')), G, G)
    del G

    story = getStory()
    if verbose: print('Built story contains %d flowables...' % len(story))
    doc.multiBuild(story)
    if verbose: print('Saved "%s"' % destfn)
Esempio n. 29
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')
Esempio n. 30
0
    def registerFont(self, font):
        pdfmetrics.registerFont(TTFont(font, font + '.ttf'))
        pdfmetrics.registerFont(TTFont(font + 'bold', font + 'bd.ttf'))
        pdfmetrics.registerFont(TTFont(font + 'italic', font + 'i.ttf'))
        pdfmetrics.registerFont(TTFont(font + 'bolditalic', font + 'bi.ttf'))
        pdfmetrics.registerFontFamily(font,
                                      normal=font,
                                      bold=font + 'bold',
                                      italic=font + "italic",
                                      boldItalic=font + 'bolditalic')

        if not font in self.fonts:
            self.fonts.append(font)
            self.addStyles(font)
Esempio n. 31
0
def AjouterPolicesPDF():
    """ Ajouter une police dans Reportlab """
    import reportlab.rl_config
    reportlab.rl_config.warnOnMissingFontGlyphs = 0
    from reportlab.pdfbase import pdfmetrics
    from reportlab.pdfbase.ttfonts import TTFont
    from reportlab.pdfbase.pdfmetrics import registerFontFamily
    
    pdfmetrics.registerFont(TTFont('Arial', 'Outils/arial.ttf'))
    pdfmetrics.registerFont(TTFont('Arial-Bold', 'Outils/arialbd.ttf'))
    pdfmetrics.registerFont(TTFont('Arial-Oblique', 'Outils/ariali.ttf'))
    pdfmetrics.registerFont(TTFont('Arial-BoldOblique', 'Outils/arialbi.ttf'))
    
    registerFontFamily('Arial', normal='Arial', bold='Arial-Bold', italic='Arial-Oblique', boldItalic='Arial-BoldOblique')
Esempio n. 32
0
def set_fonts(fonts_list):
    """
    Register specified fonts and font families to report_info.
    :param fonts_list: list of fonts and font families to register
    """
    # TODO scan jrxml and try to automatically load fonts

    available_fonts = []
    if fonts_list is not None:
        for font in fonts_list:
            font_path = font.get('font_path')
            if type(font_path) == list:
                rl_config.TTFSearchPath.extend(font_path)
            font_filename = font.get('font_filename')
            font_list = font.get('fonts')
            if font_filename is not None and font_list is not None:
                if type(font_list) is str:
                    try:
                        pdfmetrics.registerFont(TTFont(font_list, font_filename))
                        available_fonts.append(font_list)
                    except:  # if font files is not found, output error and skip it.
                        logger.error('font not found. font name:' + name + ' file name:' + font_filename)
                elif type(font_list) is list:
                    for font_reg in font_list:
                        index = font_reg.get('index')
                        name = font_reg.get('name')
                        if name is not None:
                            if index is not None:
                                try:
                                    pdfmetrics.registerFont(TTFont(name, font_filename, subfontIndex=index))
                                    available_fonts.append(name)
                                except: # if font files is not found, output error and skip it.
                                    logger.error('font not found. font name:' + name + ' file name:' + font_filename)
                            else:
                                try:
                                    pdfmetrics.registerFont(TTFont(name, font_filename))
                                    available_fonts.append(name)
                                except: # if font files is not found, output error and skip it.
                                    logger.error('font not found. font name:' + name + ' file name:' + font_filename)
            font_family = font.get('font-family')
            if font_family is not None:
                if font_family.get('name') is not None and font_family.get('normal') is not None\
                        and font_family.get('bold') is not None and font_family.get('italic') is not None\
                        and font_family.get('boldItalic') is not None:
                    pdfmetrics.registerFontFamily(font_family.get('name'), normal=font_family.get('normal'),
                                                  bold=font_family.get('bold'),
                                                  italic=font_family.get('italic'),
                                                  boldItalic=font_family.get('boldItalic'))
    return available_fonts
Esempio n. 33
0
def initial_fonts():
    global g_initial_fonts
    if not g_initial_fonts:
        font_dir_path = join(dirname(__file__), 'fonts')
        pdfmetrics.registerFont(
            TTFont('sans-serif', join(font_dir_path, 'FreeSans.ttf')))
        pdfmetrics.registerFont(
            TTFont('sans-serif-bold', join(font_dir_path, 'FreeSansBold.ttf')))
        pdfmetrics.registerFont(
            TTFont('sans-serif-italic', join(font_dir_path, 'FreeSansOblique.ttf')))
        pdfmetrics.registerFont(
            TTFont('sans-serif-bolditalic', join(font_dir_path, 'FreeSansBoldOblique.ttf')))
        pdfmetrics.registerFontFamily("sans-serif", normal="sans-serif", bold="sans-serif-bold",
                                      italic="sans-serif-italic", boldItalic="sans-serif-bolditalic")
        g_initial_fonts = True
Esempio n. 34
0
def initial_fonts():
    global g_initial_fonts
    if not g_initial_fonts:
        font_dir_path = join(dirname(__file__), 'fonts')
        pdfmetrics.registerFont(
            TTFont('sans-serif', join(font_dir_path, 'FreeSans.ttf')))
        pdfmetrics.registerFont(
            TTFont('sans-serif-bold', join(font_dir_path, 'FreeSansBold.ttf')))
        pdfmetrics.registerFont(
            TTFont('sans-serif-italic', join(font_dir_path, 'FreeSansOblique.ttf')))
        pdfmetrics.registerFont(
            TTFont('sans-serif-bolditalic', join(font_dir_path, 'FreeSansBoldOblique.ttf')))
        pdfmetrics.registerFontFamily("sans-serif", normal="sans-serif", bold="sans-serif-bold",
                                      italic="sans-serif-italic", boldItalic="sans-serif-bolditalic")
        g_initial_fonts = True
Esempio n. 35
0
def create_paragraph_style(name, font_name, **kwargs):
    ttf_path = "C:/Windows/Fonts/{}.ttf"
    family_args = {}  # store arguments for the font family creation
    for font_type in ("normal", "bold", "italic",
                      "boldItalic"):  # recognized font variants
        if font_type in kwargs:  # if this type was passed...
            font_variant = "{}-{}".format(
                font_name, font_type)  # create font variant name
            registerFont(
                TTFont(font_variant, ttf_path.format(kwargs[font_type])))
            family_args[
                font_type] = font_variant  # add it to font family arguments
    registerFontFamily(font_name, **family_args)  # register a font family
    return ParagraphStyle(name=name,
                          fontName=font_name,
                          fontSize=10,
                          leading=12)
Esempio n. 36
0
 def _init_fonts():
     pdfmetrics.registerFont(
         TTFont('Gandhi-R',
                finders.find('font/GandhiSans-Regular-webfont.ttf')))
     pdfmetrics.registerFont(
         TTFont('Gandhi-BI',
                finders.find('font/GandhiSans-BoldItalic-webfont.ttf')))
     pdfmetrics.registerFont(
         TTFont('Gandhi-I',
                finders.find('font/GandhiSans-Italic-webfont.ttf')))
     pdfmetrics.registerFont(
         TTFont('Gandhi-B',
                finders.find('font/GandhiSans-Bold-webfont.ttf')))
     pdfmetrics.registerFontFamily('Gandhi',
                                   normal='Gandhi-R',
                                   bold='Gandhi-B',
                                   italic='Gandhi-I',
                                   boldItalic='Gandhi-BI')
Esempio n. 37
0
def ttf_register(name, family=False, base_dir=BASE):
    if not family:
        pdfmetrics.registerFont(TTFont(name,
        os.path.join(base_dir, '%s.ttf' % name)))
    else:
        pdfmetrics.registerFont(TTFont('%sR' % name,
            os.path.join(base_dir, '%s-Regular.ttf' % name)))
        pdfmetrics.registerFont(TTFont('%sI' % name,
            os.path.join(base_dir, '%s-Italic.ttf' % name)))
        pdfmetrics.registerFont(TTFont('%sBI' % name,
            os.path.join(base_dir, '%s-BoldItalic.ttf' % name)))
        pdfmetrics.registerFont(TTFont('%sB' % name,
            os.path.join(base_dir, '%s-Bold.ttf' % name)))
        registerFontFamily(
            '%s', normal='%sR' % name, bold='%sB' % name, italic='%sI' % name,
            boldItalic='%sBI' % name)
    
    """example:
Esempio n. 38
0
def config_font():
    path_font = os.path.join(w2p_folder, 'static/font_ubuntu/')
    pdfmetrics.registerFont(TTFont('Ubuntu',
                                    path_font + 'Ubuntu-R.ttf'))
    pdfmetrics.registerFont(TTFont('UbuntuB',
                                    path_font + 'Ubuntu-B.ttf'))
    pdfmetrics.registerFont(TTFont('UbuntuBI',
                                    path_font + 'Ubuntu-BI.ttf'))
    pdfmetrics.registerFont(TTFont('UbuntuRI',
                                    path_font + 'Ubuntu-RI.ttf'))
    pdfmetrics.registerFontFamily('Ubuntu', normal='Ubuntu',
                                             bold='UbuntuB',
                                             italic='UbuntuRI',
                                             boldItalic='UbuntuBI')

    return {'normal': 'Ubuntu',
            'bold': 'UbuntuB',
            'italic': 'UbuntuRI',
            'boldItalic': 'UbuntuBI'}
Esempio n. 39
0
	def docinit(self, els):
                from reportlab.lib import fonts
		from reportlab.pdfbase import pdfmetrics

		for node in els:
                    for font in node.getElementsByTagName('registerTTFont'):
                        ttfont = self._load_ttfont(
                            font.getAttribute('faceName'),
                            font.getAttribute('fileName')
                        )
                        pdfmetrics.registerFont(ttfont)
                    for family in node.getElementsByTagName('registerFontFamily'):
                        pdfmetrics.registerFontFamily(
                            family.getAttribute('normal'),
                            normal=family.getAttribute('normal'),
                            bold=family.getAttribute('bold'),
                            italic=family.getAttribute('italic'),
                            boldItalic=family.getAttribute('boldItalic')
                        )
Esempio n. 40
0
def install_font(name, resource_name, user_fonts):
    try:
        pdfmetrics.getFont(name)
    except:
        regular = create_single_font(name, resource_name + "-Regular", None,
                                     user_fonts)
        bold = create_single_font(name + "-Bold", resource_name + "-Bold",
                                  regular, user_fonts)
        italic = create_single_font(name + "-Italic",
                                    resource_name + "-Italic", regular,
                                    user_fonts)
        bold_italic = create_single_font(name + "-BoldItalic",
                                         resource_name + "-BoldItalic", bold,
                                         user_fonts)
        pdfmetrics.registerFontFamily(name,
                                      normal=name,
                                      bold=bold,
                                      italic=italic,
                                      boldItalic=bold_italic)
Esempio n. 41
0
def fuentes():
    from reportlab.pdfbase import pdfmetrics
    from reportlab.pdfbase.ttfonts import TTFont
    reportlab.rl_config.warnOnMissingFontGlyphs = 1
    #pdfmetrics.registerFont(TTFont('Ubuntu', BASE_PDF + 'fonts/Ubuntu-R.ttf' ))
    #pdfmetrics.registerFont(TTFont('UbuntuCon', BASE_PDF + 'fonts/Ubuntu-C.ttf' ))
    pdfmetrics.registerFont(
        TTFont('Roboto', BASE_PDF + 'fonts/Roboto-Regular.ttf'))
    pdfmetrics.registerFont(
        TTFont('RobotoBd', BASE_PDF + 'fonts/Roboto-Bold.ttf'))
    pdfmetrics.registerFont(
        TTFont('RobotoIt', BASE_PDF + 'fonts/Roboto-Italic.ttf'))
    pdfmetrics.registerFont(
        TTFont('RobotoBI', BASE_PDF + 'fonts/Roboto-BoldItalic.ttf'))
    registerFontFamily('Roboto',
                       normal='Roboto',
                       bold='RobotoBd',
                       italic='RobotoIt',
                       boldItalic='RobotoBI')
Esempio n. 42
0
def _register_fonts(settings):
    default_fontdir = settings.get('netprofile.fonts.directory', '')
    default_family = settings.get('netprofile.fonts.default_family', 'tinos')
    fontcfg = make_config_dict(settings, 'netprofile.fonts.family.')
    fontcfg = as_dict(fontcfg)
    for fname, cfg in fontcfg.items():
        if 'normal' not in cfg:
            continue
        fname = cfg.get('name', fname)
        fontdir = cfg.get('directory', default_fontdir)
        pdfmetrics.registerFont(
            ttfonts.TTFont(fname, os.path.join(fontdir, cfg['normal'])))
        reg = {'normal': fname}

        if 'bold' in cfg:
            reg['bold'] = fname + '_b'
            pdfmetrics.registerFont(
                ttfonts.TTFont(reg['bold'], os.path.join(fontdir,
                                                         cfg['bold'])))
        else:
            reg['bold'] = fname

        if 'italic' in cfg:
            reg['italic'] = fname + '_i'
            pdfmetrics.registerFont(
                ttfonts.TTFont(reg['italic'],
                               os.path.join(fontdir, cfg['italic'])))
        else:
            reg['italic'] = fname

        if 'bold_italic' in cfg:
            reg['boldItalic'] = fname + '_bi'
            pdfmetrics.registerFont(
                ttfonts.TTFont(reg['boldItalic'],
                               os.path.join(fontdir, cfg['bold_italic'])))
        else:
            reg['boldItalic'] = fname

        pdfmetrics.registerFontFamily(fname, **reg)

    if default_family in fontcfg:
        return default_family
    return 'Times-Roman'
Esempio n. 43
0
def show_pdf(request,cat_id):
    tag = Tag.objects.get(pk=cat_id)
    word_ids = Tag.objects.get(pk=cat_id).items.values('object_id')
    # Create the HttpResponse object with the appropriate PDF headers.
    response = HttpResponse(mimetype='application/pdf')
    response['Content-Disposition'] = 'attachment; filename=%s.pdf'%(str(tag))
    from reportlab.pdfbase import pdfmetrics
    from reportlab.pdfbase.ttfonts import TTFont
    D = '/usr/share/fonts/truetype/ttf-lg-aboriginal/'
    pdfmetrics.registerFont(TTFont('Vera', D+'AboriginalSansREGULAR9433.ttf'))
    pdfmetrics.registerFont(TTFont('VeraBd', D+'AboriginalSansBOLD9433.ttf'))
    pdfmetrics.registerFont(TTFont('VeraIt', D+'AboriginalSansITALIC9433.ttf'))
    pdfmetrics.registerFont(TTFont('VeraBI', D+'AboriginalSansBOLDITALIC9433.ttf'))

    registerFontFamily('Vera',normal='Vera',bold='VeraBd',italic='VeraIt',boldItalic='VeraBI')

    buffer = StringIO()

    doc = SimpleDocTemplate(buffer)
    Catalog = []
    styles = getSampleStyleSheet()
    header = Paragraph("%s"%(str(tag)), styles['Heading1'])
    Catalog.append(header)
    style = ParagraphStyle(
        name='Normal',
        fontName='Vera',
        fontSize=12,
    )
    count = 0
    for id in word_ids:
        word = Word.objects.get(pk=id['object_id'])
        p = Paragraph("%s - %s" % (word.secwepemc, word.english()),style)
        Catalog.append(p)
        s = Spacer(1, 0.25*inch)
        Catalog.append(s)
    doc.build(Catalog)

    # Get the value of the StringIO buffer and write it to the response.
    pdf = buffer.getvalue()
    buffer.close()
    response.write(pdf)
    return response
def register_font_family(font_name='Crimson Text'):
    """
    Register a font family with the reportlab environment.

    Args:
        font_name (str): Name of the font family to register.
            Currently only ``'Crimson Text'`` is supported.

    Returns: None
    """
    from reportlab.pdfbase import pdfmetrics
    from reportlab.pdfbase import ttfonts
    font_folder = os.path.join(config.RESOURCES_DIR, 'fonts')
    if font_name == 'Cormorant Garamond':
        # Font file paths
        normal = os.path.join(
                font_folder, 'CormorantGaramond-Regular.ttf')
        bold = os.path.join(
                font_folder, 'CormorantGaramond-Semibold.ttf')
        italic = os.path.join(
                font_folder, 'CormorantGaramond-Italic.ttf')
        bold_italic = os.path.join(
                font_folder, 'CormorantGaramond-SemiboldItalic.ttf')
        # Register with reportlab
        pdfmetrics.registerFont(
                ttfonts.TTFont('Cormorant Garamond', normal))
        pdfmetrics.registerFont(
                ttfonts.TTFont('Cormorant Garamond-Bold', bold))
        pdfmetrics.registerFont(
                ttfonts.TTFont('Cormorant Garamond-Italic', italic))
        pdfmetrics.registerFont(
                ttfonts.TTFont('Cormorant Garamond-BoldItalic', bold_italic))
        # Register font family
        pdfmetrics.registerFontFamily(
                'Cormorant Garamond',
                'Cormorant Garamond',
                'Cormorant Garamond-Bold',
                'Cormorant Garamond-Italic',
                'Cormorant Garamond-BoldItalic')
    else:
        raise ValueError('Font {0} is not available'.format(font_name))
Esempio n. 45
0
    def ttf_register(self, name, family=False, base_dir=BASE):
        """
        Register a font or a font family.

        Example:

        # http://www.1001freefonts.com/alegreya_sc.font
        pdfmetrics.registerFont(TTFont('AlegreyaSCR',
            os.path.join(base_dir, 'AlegreyaSC-Regular.ttf')))
        pdfmetrics.registerFont(TTFont('AlegreyaSCI',
            os.path.join(base_dir, 'AlegreyaSC-Italic.ttf')))
        pdfmetrics.registerFont(TTFont('AlegreyaSCBI',
            os.path.join(base_dir, 'AlegreyaSC-BoldItalic.ttf')))
        pdfmetrics.registerFont(TTFont('AlegreyaSCB',
            os.path.join(base_dir, 'AlegreyaSC-Bold.ttf')))
        registerFontFamily(
            'AlegreyaSC', normal='AlegreyaSCR', bold='AlegreyaSCB',
            italic='AlegreyaSCI', boldItalic='AlegreyaSCBI')

        Note:
            Acrobat PDF has 14 built-in fonts, supported by reportlab:
            Courier, Helvetica, Courier-Bold, Helvetica-Bold, Courier-Oblique,
            Helvetica-Oblique, Courier-BoldOblique, Helvetica-BoldOblique,
            Times-Roman, Times-Bold, Times-Italic, Times-BoldItalic, Symbol,
            ZapfDingbats
        """
        if not family:
            pdfmetrics.registerFont(TTFont(name,
            os.path.join(base_dir, '%s.ttf' % name)))
        else:
            pdfmetrics.registerFont(TTFont('%sR' % name,
                os.path.join(base_dir, '%s-Regular.ttf' % name)))
            pdfmetrics.registerFont(TTFont('%sI' % name,
                os.path.join(base_dir, '%s-Italic.ttf' % name)))
            pdfmetrics.registerFont(TTFont('%sBI' % name,
                os.path.join(base_dir, '%s-BoldItalic.ttf' % name)))
            pdfmetrics.registerFont(TTFont('%sB' % name,
                os.path.join(base_dir, '%s-Bold.ttf' % name)))
            registerFontFamily(
                '%s', normal='%sR' % name, bold='%sB' % name,
                italic='%sI' % name, boldItalic='%sBI' % name)
Esempio n. 46
0
def registerFont(fontFamilyName, folder_path):
    """ register a font """
    # Register a custom font
    pdfmetrics.registerFont(
        TTFont('{}-Bold'.format(fontFamilyName),
               join(folder_path, "{}-Bold.ttf".format(fontFamilyName))))
    pdfmetrics.registerFont(
        TTFont(fontFamilyName,
               join(folder_path, "{}.ttf".format(fontFamilyName))))
    pdfmetrics.registerFont(
        TTFont('{}-Oblique'.format(fontFamilyName),
               join(folder_path, "{}-Oblique.ttf".format(fontFamilyName))))
    pdfmetrics.registerFont(
        TTFont('{}-BoldOblique'.format(fontFamilyName),
               join(folder_path, "{}-BoldOblique.ttf".format(fontFamilyName))))
    pdfmetrics.registerFontFamily(
        fontFamilyName,
        normal=fontFamilyName,
        bold='{}-Bold'.format(fontFamilyName),
        italic='{}-Italic'.format(fontFamilyName),
        boldItalic='{}-BoldItalic'.format(fontFamilyName))
Esempio n. 47
0
def register_fonts():
    """
    Register fonts used for generation of PDF documents.
    """

    reportlab.rl_config.warnOnMissingFontGlyphs = 0

    registerFont(TTFont('Bookman', join(FONT_DIR, 'URWBookman-Regular.ttf')))

    registerFont(TTFont('BookmanB', join(FONT_DIR, 'URWBookman-Bold.ttf')))

    registerFont(TTFont('BookmanI', join(FONT_DIR, 'URWBookman-Italic.ttf')))

    registerFont(
        TTFont('BookmanBI', join(FONT_DIR, 'URWBookman-BoldItalic.ttf')))

    registerFontFamily('Bookman',
                       normal='Bookman',
                       bold='BookmanB',
                       italic='BookmanI',
                       boldItalic='BookmanBI')
Esempio n. 48
0
    def register_font(self,
                      name,
                      normal=None,
                      bold=None,
                      italic=None,
                      boldItalic=None,
                      langs=[]):

        # register languages overrides
        if langs:
            for lang in langs:
                self.font_overrides[lang] = name

        # register font family with reportlab
        if normal is None and bold is None and italic is None and boldItalic is None:
            raise ValueError('No font file was specified')
        if normal:
            pdfmetrics.registerFont(
                TTFont(name, os.path.join(self.assets_root, normal)))
            normal = name
        if bold:
            pdfmetrics.registerFont(
                TTFont(name + '-Bold', os.path.join(self.assets_root, bold)))
            bold = name + '-Bold'
        if italic:
            pdfmetrics.registerFont(
                TTFont(name + '-Italic', os.path.join(self.assets_root,
                                                      italic)))
            italic = name + '-Italic'
        if boldItalic:
            pdfmetrics.registerFont(
                TTFont(name + '-BoldItalic',
                       os.path.join(self.assets_root, boldItalic)))
            boldItalic = name + '-BoldItalic'
        pdfmetrics.registerFontFamily(name,
                                      normal=normal,
                                      bold=bold,
                                      italic=italic,
                                      boldItalic=boldItalic)
Esempio n. 49
0
    def register_font(self, name, normal=None, bold=None, italic=None, boldItalic=None, langs=[]):

        # register languages overrides
        if langs:
            for lang in langs:
                self.font_overrides[lang] = name

        # register font family with reportlab
        if normal is None and bold is None and italic is None and boldItalic is None:
            raise ValueError('No font file was specified')
        if normal:
            pdfmetrics.registerFont(TTFont(name, os.path.join(self.assets_root, normal)))
            normal = name
        if bold:
            pdfmetrics.registerFont(TTFont(name + '-Bold', os.path.join(self.assets_root, bold)))
            bold = name + '-Bold'
        if italic:
            pdfmetrics.registerFont(TTFont(name + '-Italic', os.path.join(self.assets_root, italic)))
            italic = name + '-Italic'
        if boldItalic:
            pdfmetrics.registerFont(TTFont(name + '-BoldItalic', os.path.join(self.assets_root, boldItalic)))
            boldItalic = name + '-BoldItalic'
        pdfmetrics.registerFontFamily(name, normal=normal, bold=bold, italic=italic, boldItalic=boldItalic)
Esempio n. 50
0
def AjouterPolicesPDF():
    """ Ajouter une police dans Reportlab """
    import reportlab.rl_config
    reportlab.rl_config.warnOnMissingFontGlyphs = 0
    from reportlab.pdfbase import pdfmetrics
    from reportlab.pdfbase.ttfonts import TTFont
    from reportlab.pdfbase.pdfmetrics import registerFontFamily

    pdfmetrics.registerFont(
        TTFont("Arial", Chemins.GetStaticPath("Polices/arial.ttf")))
    pdfmetrics.registerFont(
        TTFont("Arial-Bold", Chemins.GetStaticPath("Polices/arialbd.ttf")))
    pdfmetrics.registerFont(
        TTFont("Arial-Oblique", Chemins.GetStaticPath("Polices/ariali.ttf")))
    pdfmetrics.registerFont(
        TTFont("Arial-BoldOblique",
               Chemins.GetStaticPath("Polices/arialbi.ttf")))

    registerFontFamily('Arial',
                       normal='Arial',
                       bold='Arial-Bold',
                       italic='Arial-Oblique',
                       boldItalic='Arial-BoldOblique')
Esempio n. 51
0
    def __init__(self, buffer, pagesize, peldany):
        # Register Fonts
        #pdfmetrics.registerFont(TTFont('Arial-Bold', settings.STATIC_ROOT + 'fonts/arialbd.ttf'))
        pdfmetrics.registerFont(TTFont('DejaVuSans', 'DejaVuSans.ttf'))

        pdfmetrics.registerFont(TTFont('DejaVuSerif', 'DejaVuSerif.ttf'))
        pdfmetrics.registerFont(TTFont('DejaVuSerifB', 'DejaVuSerif-Bold.ttf'))
        pdfmetrics.registerFont(TTFont('DejaVuSerifI', 'DejaVuSerif-Italic.ttf'))
        pdfmetrics.registerFont(TTFont('DejaVuSerifBI', 'DejaVuSerif-BoldItalic.ttf'))
        pdfmetrics.registerFontFamily('DejaVuSerif', normal='DejaVuSerif', bold='DejaVuSerifB', italic='DejaVuSerifI',
                                      boldItalic='DejaVuSerifBI')

        self.buffer = buffer
        if pagesize == 'A4':
            self.pagesize = A4
        elif pagesize == 'Letter':
            self.pagesize = letter
        self.width, self.height = self.pagesize
        if peldany == '2':
           self.peldany = '3.2_Könyvelés példánya'
        elif peldany == '3':
           self.peldany = '3.3_Vevőnyilvántartás példánya'
        elif peldany == '1':
           self.peldany = '3.1_Eredeti példány'
Esempio n. 52
0
eg("""
    TTFont(name,filename)
""")
disc(
    """so that the ReportLab internal name is given by the first argument and the second argument
is a string(or file like object) denoting the font's TTF file. In Marius' original patch the filename
was supposed to be exactly correct, but we have modified things so that if the filename is relative
then a search for the corresponding file is done in the current directory and then in directories
specified by $reportlab.rl_config.TTFSearchpath$!""")

from reportlab.lib.styles import ParagraphStyle

from reportlab.pdfbase.pdfmetrics import registerFontFamily
registerFontFamily('Vera',
                   normal='Vera',
                   bold='VeraBd',
                   italic='VeraIt',
                   boldItalic='VeraBI')

disc(
    """Before using the TT Fonts in Platypus we should add a mapping from the family name to the
individual font names that describe the behaviour under the $<b>$ and $<i>$ attributes."""
)

eg("""
from reportlab.pdfbase.pdfmetrics import registerFontFamily
registerFontFamily('Vera',normal='Vera',bold='VeraBd',italic='VeraIt',boldItalic='VeraBI')
""")

disc(
    """If we only have a Vera regular font, no bold or italic then we must map all to the
Esempio n. 53
0
""")
illust(examples.ttffont1, "Using a the Vera TrueType Font")
disc("""In the above example the true type font object is created using""")
eg("""
    TTFont(name,filename)
""")
disc("""so that the ReportLab internal name is given by the first argument and the second argument
is a string(or file like object) denoting the font's TTF file. In Marius' original patch the filename
was supposed to be exactly correct, but we have modified things so that if the filename is relative
then a search for the corresponding file is done in the current directory and then in directories
specified by $reportlab.rl_config.TTFSearchpath$!""")

from reportlab.lib.styles import ParagraphStyle

from reportlab.pdfbase.pdfmetrics import registerFontFamily
registerFontFamily('Vera',normal='Vera',bold='VeraBd',italic='VeraIt',boldItalic='VeraBI')

disc("""Before using the TT Fonts in Platypus we should add a mapping from the family name to the
individual font names that describe the behaviour under the $<b>$ and $<i>$ attributes.""")

eg("""
from reportlab.pdfbase.pdfmetrics import registerFontFamily
registerFontFamily('Vera',normal='Vera',bold='VeraBd',italic='VeraIt',boldItalic='VeraBI')
""")

disc("""If we only have a Vera regular font, no bold or italic then we must map all to the
same internal fontname.  ^&lt;b&gt;^ and ^&lt;i&gt;^ tags may now be used safely, but
have no effect.
After registering and mapping
the Vera font as above we can use paragraph text like""")
parabox2("""<font name="Times-Roman" size="14">This is in Times-Roman</font>
Esempio n. 54
0
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
"""

# Register Segoe UI Normal and Bold font variants
# to use in the PDFs.

fontName = ""

if platform == "win32":
    pdfmetrics.registerFont(TTFont("Segoe UI", "SegoeUI.ttf"))
    pdfmetrics.registerFont(TTFont("Segoe UI Bold", "SegoeUIB.ttf"))
    pdfmetrics.registerFontFamily("Segoe UI",
                                  normal="Segoe UI",
                                  bold="Segoe UI Bold")
    fontName = "Segoe UI"
elif platform == "darwin":
    pdfmetrics.registerFont(TTFont("Helvetica", "Helvetica.ttf"))
    # there is uncertainty in the font file name
    pdfmetrics.registerFont(TTFont("Helvetica Bold", "HelveticaBold.ttf"))
    pdfmetrics.registerFontFamily("Helvetica",
                                  normal="Helvetica",
                                  bold="Helvetica Bold")
elif platform == "linux" or platform == "linux2":
    pdfmetrics.registerFont(TTFont("DejaVu", "DejaVu.ttf"))
    pdfmetrics.registerFont(TTFont("DejaVu Bold", "DejaVuBold.ttf"))
    pdfmetrics.registerFontFamily("DejaVu",
                                  normal="DejaVu",
                                  bold="DejaVu Bold")
Esempio n. 55
0
                              fontSize = 10,
                              alignment = 4,
                              spaceBefore = 0,
                              spaceAfter = 0,
                              firstLineIndent = 1*cm,
                              topIndent =-1*cm,
                              leftIndent = -1*cm,
                              rightIndent = -0.7*cm)

#importar una fuente TT
pdfmetrics.registerFont(TTFont('DejaVu', '/usr/share/fonts/truetype/ttf-dejavu/DejaVuSans.ttf'))
##pdfmetrics.registerFont(TTFont('DejaVuBd', '/usr/share/fonts/truetype/ttf-dejavu/DejaVuSansBold.ttf'))
##pdfmetrics.registerFont(TTFont('DejaVuBdIt', '/usr/share/fonts/truetype/ttf-dejavu/DejaVuSansBoldOblique.ttf'))
##pdfmetrics.registerFont(TTFont('DejaVuIt', '/usr/share/fonts/truetype/ttf-dejavu/DejaVuSansOblique.ttf'))
##registerFontFamily('Dejavu', normal = 'DejaVu', bold = 'DejaVuBd', italic = 'DejaVuIt', boldItalic = 'DejaVuBdIt')
registerFontFamily('Dejavu', normal = 'DejaVu', bold = 'DejaVu', italic = 'DejaVu', boldItalic = 'DejaVu')


def get_print_path(modulo):
    """Devuelve el directorio donde se almacenan los PDF"""
    print_path = os.path.join(os.path.expanduser('~'),'Documentos',modulo)
    ##Si no existe el directorio lo creamos
    if not os.path.isdir(print_path):
        logging.debug("Creando el dir para %s"%modulo)
        os.mkdir(print_path)
    return print_path
def send_to_printer(fichero):
    #logging.debug("Vamos a mandar a la impresora %s"%fichero)
    logging.debug("No lo mandamos a la impresora %s"%fichero)
    os.system("lpr %s"%fichero)
def myFirstPage(canvas, doc):
from reportlab.platypus import TableStyle
import os

FONT_DIR = os.path.join(os.path.dirname(common.__file__), "fonts")

try:
    ps2tt("LiberationSerif")
except ValueError:
    registerFont(TTFont("LiberationSerif", os.path.join(FONT_DIR, "LiberationSerif-Regular.ttf")))
    registerFont(TTFont("LiberationSerif-Bold", os.path.join(FONT_DIR, "LiberationSerif-Bold.ttf")))
    registerFont(TTFont("LiberationSerif-Italic", os.path.join(FONT_DIR, "LiberationSerif-Italic.ttf")))
    registerFont(TTFont("LiberationSerif-BoldItalic", os.path.join(FONT_DIR, "LiberationSerif-BoldItalic.ttf")))
    registerFontFamily(
        "LiberationSerif",
        normal="LiberationSerif",
        bold="LiberationSerif-Bold",
        italic="LiberationSerif-Italic",
        boldItalic="LiberationSerif-BoldItalic",
    )

styles = dict()
styles["main"] = ParagraphStyle(
    "main",
    fontSize=10,
    leading=11.5,
    trailing=0,
    spaceBefore=0,
    spaceAfter=0,
    leftIndent=0,
    rightIndent=0,
    wordWrap=None,
Esempio n. 57
0
def exportPDF(request, slug):
    '''Exports recipes to a pdf'''

    pdfmetrics.registerFont(TTFont('Vera', 'Vera.ttf'))
    pdfmetrics.registerFont(TTFont('VeraBd', 'VeraBd.ttf'))
    pdfmetrics.registerFont(TTFont('VeraIt', 'VeraIt.ttf'))
    pdfmetrics.registerFont(TTFont('VeraBI', 'VeraBI.ttf'))
    registerFontFamily('Vera',normal='Vera',bold='VeraBd',italic='VeraIt',boldItalic='VeraBI')

    recipe = get_object_or_404(Recipe, slug=slug)

    # Create the HttpResponse object with the appropriate PDF headers.
    response = HttpResponse(mimetype='application/pdf')
    response['Content-Disposition'] = 'attachment; filename=' + recipe.slug + '.pdf'

    # Our container for 'Flowable' objects
    elements = []

    #set up our styles
    styles = getSampleStyleSheet()
    styleH1 = styles['Heading1']
    styleH1.textColor= colors.green
    styleH1.fontName='VeraBd'
    styleH2 = styles['Heading2']
    styleH2.textColor=colors.goldenrod
    styleH2.fontName='Vera'
    styleNormal = styles['Normal']
    styleNormal.fontName='Vera'
    styleBullet = styles['Bullet']
    styleBullet.fontName='VeraIt'

    #create the pdf doc
    doc = SimpleDocTemplate(response)

    #set the openeats logo
    logo = settings.STATIC_ROOT + "/" + settings.OELOGO
    I = Image(logo)
    I.hAlign='LEFT'
    elements.append(I)
    elements.append(Spacer(0, 1 * cm))

    #add the recipe photo if the recipe has one
    if recipe.photo:
        photo = settings.BASE_PATH + recipe.thumbnail_image.url
        I = Image(photo)
        I.height="CENTER"
        elements.append(I)
        elements.append(Spacer(0, 0.5 * cm))

    # add the meat of the pdf
    elements.append(Paragraph(recipe.title, styleH1))
    elements.append(Paragraph('info', styleH2))
    elements.append(Paragraph(recipe.info, styleNormal))
    elements.append(Paragraph('ingredients', styleH2))

    for ing in recipe.ingredients.all():
        ing = "%s %s %s %s" %(ing.quantity, ing.measurement, ing.title, ing.preparation)
        elements.append(Paragraph(ing, styleBullet))

    elements.append(Paragraph('directions', styleH2))
    elements.append(Paragraph(recipe.directions, styleNormal))

    #build the pdf and return it
    doc.build(elements)
    return response
Esempio n. 58
0
def make_pdf(data, font_folder="stunden/ubuntu-font-family-0.80/",
             second_table=True):
    """
    Erstellt PDF Rechnungen.
    Nimmt ein dict als erstes Argument und optional ein Keyword Argument namens
    "font_folder", womit man angeben kann wo sich der Ordner der "Ubuntu"
    Schriftart befindet.

    Verwendungsbeispiel:
    make_pdf({
        "pdf_fileobject": u"filename.pdf",  # oder Django HttpResponse Objekt
        "pdf_title": u"Rechnung IT-0815",
        "pdf_author": u"Martin Fischer",
        "pdf_subject": u"Rechnung erstellt von webpystunden Software",
        "pdf_creator": u"webpystunden",
        "pdf_keywords": u"webpystunden, Martin, Fischer",
        "sender_address_name": u"John Cleese",
        "sender_address_street": u"Straße 15",
        "sender_address_city": u"Ort",
        "sender_address_zip_city": u"5555 Ort",
        "sender_address_country": u"Österreich",
        "sender_address_uid": u"UID: 123456789",
        "receiver_address_company": u"Firma",
        "receiver_address_name": u"Eric Idle",
        "receiver_address_street": u"Straße 99",
        "receiver_address_zip_city": u"9999 Ort",
        "receiver_address_country": u"Österreich",
        "receiver_address_uid": u"UID: 987654321",
        "rechnungs_nummer": u"Rechnung IT-0815",
        "rechnungs_titel": u"Rechnung für November",
        "rechnungs_summe_netto": u"100,00",
        "rechnungs_summe_mwst": u"20,00",
        "rechnungs_summe_brutto": u"120,00",
        "stunden_rows": [
            [date(2012, 11, 29),
            time(10, 00, 00,),
            time(12, 00, 00,),
            u"Das Protokoll Nr. 1",
            u"2.00"],
            [date(2012, 11, 30),
            time(13, 00, 00),
            time(16, 30, 00),
            u"Das Protokoll Nr. 2",
            u"3.50"]
        ],
        "stunden_gesamt_stunden": u"5.50",
        "sender_bank_receiver": u"John Cleese",
        "sender_bank_name": u"The Bank",
        "sender_bank_iban": u"AT00000000000000",
        "sender_bank_bic": u"XVSGHSVVVVVVVVV",
    }, font_folder="stunden/ubuntu-font-family-0.80/")
    """

    # Registriert die Schriftart Ubuntu.
    pdfmetrics.registerFont(TTFont("Ubuntu", os.path.join(font_folder,
                                                          "Ubuntu-R.ttf")))
    pdfmetrics.registerFont(TTFont("UbuntuBold", os.path.join(font_folder,
                            "Ubuntu-B.ttf")))
    pdfmetrics.registerFont(TTFont("UbuntuItalic", os.path.join(font_folder,
                            "Ubuntu-RI.ttf")))
    pdfmetrics.registerFontFamily("Ubuntu",
                                  normal="Ubuntu",
                                  bold="UbuntuBold",
                                  italic="UbuntuItalic")

    # Hier werden alles Styles aufgesetzt.
    page_width, page_height = A4
    font_size_p = 12
    font_size_h1 = 16
    color_h1 = colors.HexColor("#556AA6")

    styles = getSampleStyleSheet()

    styles.add(ParagraphStyle(name="p-left",
                              fontName="Ubuntu",
                              fontSize=font_size_p,
                              leading=font_size_p + 2,
                              leftIndent=0,
                              rightIndent=0,
                              firstLineIndent=0,
                              alignment=TA_LEFT,
                              spaceBefore=0,
                              spaceAfter=0,
                              bulletFontName="Ubuntu",
                              bulletFontSize=font_size_p,
                              bulletIndent=0,
                              textColor=colors.black,
                              backColor=None,
                              wordWrap=None,
                              borderWidth=0,
                              borderPadding=0,
                              borderColor=None,
                              borderRadius=None,
                              allowWidows=1,
                              allowOrphans=0))

    styles.add(ParagraphStyle(name="p-right",
                              fontName="Ubuntu",
                              fontSize=font_size_p,
                              leading=font_size_p + 2,
                              leftIndent=0,
                              rightIndent=0,
                              firstLineIndent=0,
                              alignment=TA_RIGHT,
                              spaceBefore=0,
                              spaceAfter=0,
                              bulletFontName="Ubuntu",
                              bulletFontSize=font_size_p,
                              bulletIndent=0,
                              textColor=colors.black,
                              backColor=None,
                              wordWrap=None,
                              borderWidth=0,
                              borderPadding=0,
                              borderColor=None,
                              borderRadius=None,
                              allowWidows=1,
                              allowOrphans=0))

    styles.add(ParagraphStyle(name="h1_left",
                              fontName="Ubuntu",
                              fontSize=font_size_h1,
                              leading=font_size_h1 + 2,
                              leftIndent=0,
                              rightIndent=0,
                              firstLineIndent=0,
                              alignment=TA_LEFT,
                              spaceBefore=0,
                              spaceAfter=0,
                              bulletFontName="Ubuntu",
                              bulletFontSize=font_size_h1,
                              bulletIndent=0,
                              textColor=color_h1,
                              backColor=None,
                              wordWrap=None,
                              borderWidth=0,
                              borderPadding=0,
                              borderColor=None,
                              borderRadius=None,
                              allowWidows=1,
                              allowOrphans=0))

    styles.add(ParagraphStyle(name="table-center",
                              fontName="Ubuntu",
                              fontSize=font_size_p,
                              leading=font_size_p + 2,
                              leftIndent=0,
                              rightIndent=0,
                              firstLineIndent=0,
                              alignment=TA_CENTER,
                              spaceBefore=0,
                              spaceAfter=0,
                              bulletFontName="Ubuntu",
                              bulletFontSize=font_size_p,
                              bulletIndent=0,
                              textColor=colors.black,
                              backColor=None,
                              wordWrap=None,
                              borderWidth=0,
                              borderPadding=0,
                              borderColor=None,
                              borderRadius=None,
                              allowWidows=1,
                              allowOrphans=0))

    styles.add(ParagraphStyle(name="table-left",
                              fontName="Ubuntu",
                              fontSize=font_size_p,
                              leading=font_size_p + 2,
                              leftIndent=0,
                              rightIndent=0,
                              firstLineIndent=0,
                              alignment=TA_LEFT,
                              spaceBefore=0,
                              spaceAfter=0,
                              bulletFontName="Ubuntu",
                              bulletFontSize=font_size_p,
                              bulletIndent=0,
                              textColor=colors.black,
                              backColor=None,
                              wordWrap=None,
                              borderWidth=0,
                              borderPadding=0,
                              borderColor=None,
                              borderRadius=None,
                              allowWidows=1,
                              allowOrphans=0))

    styles.add(ParagraphStyle(name="table-right",
                              fontName="Ubuntu",
                              fontSize=font_size_p,
                              leading=font_size_p + 2,
                              leftIndent=0,
                              rightIndent=0,
                              firstLineIndent=0,
                              alignment=TA_RIGHT,
                              spaceBefore=0,
                              spaceAfter=0,
                              bulletFontName="Ubuntu",
                              bulletFontSize=font_size_p,
                              bulletIndent=0,
                              textColor=colors.black,
                              backColor=None,
                              wordWrap=None,
                              borderWidth=0,
                              borderPadding=0,
                              borderColor=None,
                              borderRadius=None,
                              allowWidows=1,
                              allowOrphans=0))

    styles.add(ParagraphStyle(name="table-left-small",
                              fontName="Ubuntu",
                              fontSize=font_size_p - 2,
                              leading=font_size_p,
                              leftIndent=0,
                              rightIndent=0,
                              firstLineIndent=0,
                              alignment=TA_LEFT,
                              spaceBefore=0,
                              spaceAfter=0,
                              bulletFontName="Ubuntu",
                              bulletFontSize=font_size_p - 2,
                              bulletIndent=0,
                              textColor=colors.black,
                              backColor=None,
                              wordWrap=None,
                              borderWidth=0,
                              borderPadding=0,
                              borderColor=None,
                              borderRadius=None,
                              allowWidows=1,
                              allowOrphans=0))

    # So sieht die erste Seite aus.
    def first_page(canvas, doc):
        canvas.saveState()
        canvas.setFont("Ubuntu", 8)
        canvas.setFillColor(colors.gray)
        canvas.drawCentredString(page_width / 2.0, 20,
                                 "Seite {}".format(doc.page))
        canvas.restoreState()

    # So sehen alle weiter Seiten aus. Identisch zur ersten Seite.
    def further_pages(canvas, doc):
        canvas.saveState()
        canvas.setFont("Ubuntu", 8)
        canvas.setFillColor(colors.gray)
        canvas.drawCentredString(page_width / 2.0, 20,
                                 "Seite {}".format(doc.page))
        canvas.restoreState()

    # Die Story beginnt hier.
    story = []

    story.append(Spacer(1, font_size_p))

    # Die Daten des Rechnungssenders.
    sender_address_parts = [data["sender_address_name"],
                            data["sender_address_street"],
                            data["sender_address_zip_city"],
                            data["sender_address_country"],
                            data["sender_address_uid"]]

    for part in sender_address_parts:
        ptext = u"<font>{}</font>".format(part)
        story.append(Paragraph(ptext, styles["p-left"]))

    story.append(Spacer(1, font_size_p * 4))

    # Die Daten des Rechnungsempfängers.
    receiver_address_parts = [data["receiver_address_company"],
                              data["receiver_address_name"],
                              data["receiver_address_street"],
                              data["receiver_address_zip_city"],
                              data["receiver_address_country"],
                              data["receiver_address_uid"]]

    for part in receiver_address_parts:
        ptext = u"<font>{}</font>".format(part)
        story.append(Paragraph(ptext, styles["p-left"]))

    story.append(Spacer(1, font_size_p))

    # Der Ort und das Datum.
    sender_address_city = data["sender_address_city"]
    today = date.today()
    formated_date = today.strftime("%d.%m.%Y")
    ptext = u"<font>{}, {}</font>".format(sender_address_city, formated_date)
    story.append(Paragraph(ptext, styles["p-right"]))

    story.append(Spacer(1, font_size_p * 5))

    # Die Rechnungsnummer.
    ptext = u"""<font><b>Rechnung Nr: {}</b></font>
            """.format(data["rechnungs_nummer"])
    story.append(Paragraph(ptext, styles["h1_left"]))

    story.append(Spacer(1, font_size_p * 3))

    # Die Tabelle mit den Rechnungsdaten.
    # Überschriften.
    table_header_position = Paragraph(u"<b>Pos</b>", styles["table-center"])
    table_header_bezeichnung = Paragraph(u"<b>Bezeichnung</b>",
                                         styles["table-center"])
    table_header_summe = Paragraph(u"<b>Summe</b>", styles["table-center"])

    # Reihe 1 - Titel und Summe Netto.
    table_row1_position = Paragraph(u"1", styles["table-center"])
    table_row1_bezeichnung = Paragraph(u"{}".format(data["rechnungs_titel"]),
                                       styles["table-center"])
    table_row1_summe = Paragraph(u"€ {}".format(data["rechnungs_summe_netto"]),
                                 styles["table-right"])

    # Reihe 3 - Summe MWST.
    table_row3_position = Paragraph("", styles["table-center"])
    table_row3_bezeichnung = Paragraph(u"+ 20% MwSt", styles["table-right"])
    table_row3_summe = Paragraph(u"€ {}".format(data["rechnungs_summe_mwst"]),
                                 styles["table-right"])

    # Reihe 5 - Info zur Stundentabelle.
    table_row5_position = Paragraph("", styles["table-center"])
    table_row5_bezeichnung = Paragraph(u"""
                    <i>(Detailierte Stundenaufstellung auf Seite 2)</i>""",
                                       styles["table-left-small"])
    table_row5_summe = Paragraph("", styles["table-right"])

    # Reihe 7 - Summe Netto.
    table_row7_position = Paragraph("", styles["table-center"])
    table_row7_bezeichnung = Paragraph(u"Summe netto", styles["table-right"])
    table_row7_summe = Paragraph(u"€ {}".format(data["rechnungs_summe_netto"]),
                                 styles["table-right"])

    # Reihe 9 - Summe MWST.
    table_row9_position = Paragraph("", styles["table-center"])
    table_row9_bezeichnung = Paragraph(u"MwSt.", styles["table-right"])
    table_row9_summe = Paragraph(u"€ {}".format(data["rechnungs_summe_mwst"]),
                                 styles["table-right"])

    # Reihe 10 - Ein paar Striche zur Abgrenzung.
    table_row10_position = Paragraph("", styles["table-center"])
    table_row10_bezeichnung = Paragraph(u"-" * 23, styles["table-right"])
    table_row10_summe = Paragraph("", styles["table-right"])

    # Reihe 11 - Gesamtbetrag und Summe Brutto.
    table_row11_position = Paragraph("", styles["table-center"])
    table_row11_bezeichnung = Paragraph("<b>Gesamtbetrag</b>",
                                        styles["table-right"])
    table_row11_summe = Paragraph(u"<b>€ {}</b>".format(
                                  data["rechnungs_summe_brutto"]),
                                  styles["table-right"])

    # Die Tabelle als Liste aus Listen. Leer bedeutet eine leere Reihe.
    if second_table:
        data_rechnung = [
            [table_header_position, table_header_bezeichnung,
             table_header_summe],
            [table_row1_position, table_row1_bezeichnung, table_row1_summe],
            [],
            [table_row3_position, table_row3_bezeichnung, table_row3_summe],
            [],
            [table_row5_position, table_row5_bezeichnung, table_row5_summe],
            [],
            [table_row7_position, table_row7_bezeichnung, table_row7_summe],
            [],
            [table_row9_position, table_row9_bezeichnung, table_row9_summe],
            [table_row10_position, table_row10_bezeichnung, table_row10_summe],
            [table_row11_position, table_row11_bezeichnung, table_row11_summe],
        ]
    else:
        data_rechnung = [
            [table_header_position, table_header_bezeichnung,
             table_header_summe],
            [table_row1_position, table_row1_bezeichnung, table_row1_summe],
            [],
            [table_row3_position, table_row3_bezeichnung, table_row3_summe],
            [],
            [table_row7_position, table_row7_bezeichnung, table_row7_summe],
            [],
            [table_row9_position, table_row9_bezeichnung, table_row9_summe],
            [table_row10_position, table_row10_bezeichnung, table_row10_summe],
            [table_row11_position, table_row11_bezeichnung, table_row11_summe],
        ]

    # Styles für die Tabelle.
    table_rechnung = Table(data_rechnung,
                           colWidths=[1.5 * cm, 11 * cm, 3 * cm])

    table_rechnung.setStyle(TableStyle([
                            ("BACKGROUND", (0, 0), (-1, 0), colors.lightblue),
                            ("FONTNAME", (0, 0), (-1, -1), "Ubuntu"),
                            ("FONTSIZE", (0, 0), (-1, -1), 12),
                            ("INNERGRID", (0, 0), (-1, -1), 0.25,
                             colors.black),
                            ("BOX", (0, 0), (-1, -1), 0.25, colors.black),
                            ("VALIGN", (0, 0), (-1, -1), "MIDDLE")]))

    # Die Story wird um eine Tabelle reicher.
    story.append(table_rechnung)

    story.append(Spacer(1, font_size_p * 3))

    # Dei Bankinformationen.
    ptext = u"<font>Bitte den Gesamtbetrag überweisen an:</font>"
    story.append(Paragraph(ptext, styles["p-left"]))

    story.append(Spacer(1, font_size_p))

    sender_bank_parts = [u"Empfänger: {}".format(data["sender_bank_receiver"]),
                         u"Bank: {}".format(data["sender_bank_name"]),
                         u"IBAN: {}".format(data["sender_bank_iban"]),
                         u"BIC: {}".format(data["sender_bank_bic"])]

    for part in sender_bank_parts:
        ptext = u"<font>{}</font>".format(part)
        story.append(Paragraph(ptext, styles["p-left"]))

    if second_table:
        # Hier wird die erste Seite beendet.
        story.append(PageBreak())

        story.append(Spacer(1, font_size_p))

        # Die Überschrift auf Seite 2.
        ptext = u"<font><b>Stundenaufstellung</b></font>"
        story.append(Paragraph(ptext, styles["h1_left"]))

        story.append(Spacer(1, font_size_p * 3))

        # Die Tabelle mit den Stundenaufstellungen.
        stunden_table_data = []
        # Überschriften.
        table_datum_header = Paragraph(u"<b>Datum</b>", styles["table-center"])
        table_startzeit_header = Paragraph(u"<b>Startzeit</b>",
                                           styles["table-center"])
        table_endzeit_header = Paragraph(u"<b>Endzeit</b>",
                                         styles["table-center"])
        table_protokoll_header = Paragraph(u"<b>Protokoll</b>",
                                           styles["table-center"])
        table_stunden_header = Paragraph(u"<b>Stunden</b>",
                                         styles["table-center"])

        stunden_table_data_header = [table_datum_header,
                                     table_startzeit_header,
                                     table_endzeit_header,
                                     table_protokoll_header,
                                     table_stunden_header]

        stunden_table_data.append(stunden_table_data_header)

        # Die Reihen mit den Stundendaten.
        stunden_table_data_rows = []
        for stunden_row in data["stunden_rows"]:
            datum = Paragraph(u"{}".format(
                              stunden_row[0].strftime("%d.%m.%Y")),
                              styles["table-center"])
            startzeit = Paragraph(u"{}".format(
                                  stunden_row[1].strftime("%H:%M")),
                                  styles["table-center"])
            endzeit = Paragraph(u"{}".format(stunden_row[2].strftime("%H:%M")),
                                styles["table-center"])
            protokoll = Paragraph(u"{}".format(stunden_row[3]),
                                  styles["table-left"])
            stunden = Paragraph(u"{}".format(stunden_row[4]),
                                styles["table-center"])
            row = [datum, startzeit, endzeit, protokoll, stunden]
            stunden_table_data_rows.append(row)

        for row in stunden_table_data_rows:
            stunden_table_data.append(row)

        # Die letzte Reihe mit den Gesamtstunden.
        table_datum_row_last = Paragraph("", styles["table-center"])
        table_startzeit_row_last = Paragraph("", styles["table-center"])
        table_endzeit_row_last = Paragraph("", styles["table-center"])
        table_protokoll_row_last = Paragraph(u"<b>Gesamtstunden</b>",
                                             styles["table-right"])
        table_stunden_row_last = Paragraph(u"<b>{}</b>".format(
                                           data["stunden_gesamt_stunden"]),
                                           styles["table-center"])

        stunden_table_data_row_last = [table_datum_row_last,
                                       table_startzeit_row_last,
                                       table_endzeit_row_last,
                                       table_protokoll_row_last,
                                       table_stunden_row_last]

        stunden_table_data.append(stunden_table_data_row_last)

        # Styles für die Tabelle.
        table_stunden = Table(
            stunden_table_data,
            colWidths=[2.5 * cm, 2.2 * cm, 2.2 * cm, 7 * cm, 2 * cm]
        )

        table_stunden.setStyle(TableStyle([
            ("BACKGROUND", (0, 0), (-1, 0), colors.lightblue),
            ("FONTNAME", (0, 0), (-1, -1), "Ubuntu"),
            ("FONTSIZE", (0, 0), (-1, -1), 12),
            ("INNERGRID", (0, 0), (-1, -1), 0.25, colors.black),
            ("BOX", (0, 0), (-1, -1), 0.25, colors.black),
            ("VALIGN", (0, 0), (-1, -1), "MIDDLE"), ]))

        # Hier wird die Story um noch eine Tabelle reicher.
        story.append(table_stunden)

    # Das Template für das Dokument wird aufgesetzt.
    doc = SimpleDocTemplate(data["pdf_fileobject"],
                            pagesize=A4,
                            title=u"{}".format(data["pdf_title"]),
                            author=u"{}".format(data["pdf_author"]),
                            subject=u"{}".format(data["pdf_subject"]),
                            creator=u"{}".format(data["pdf_creator"]),
                            keywords=u"{}".format(data["pdf_keywords"]),
                            rightMargin=70,
                            leftMargin=70,
                            topMargin=20,
                            bottomMargin=20)

    # Das PDF wird erstellt.
    doc.build(story, onFirstPage=first_page, onLaterPages=further_pages)
Esempio n. 59
0
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
from reportlab.lib.enums import TA_JUSTIFY,TA_LEFT,TA_RIGHT,TA_CENTER
from reportlab.lib.fonts import addMapping
import reportlab.rl_config
from decimal import Decimal
import string
trans = string.maketrans('áéíóúñ','ÁÉÍÓÚÑ')
reportlab.rl_config.warnOnMissingFontGlyphs = 0
ruta = '../fonts/'
#ruta = '/usr/share/fonts/truetype/ubuntu-font-family/'
pdfmetrics.registerFont(TTFont('Ubuntu', ruta+'Ubuntu-R.ttf'))
pdfmetrics.registerFont(TTFont('UbuntuB', ruta+'Ubuntu-B.ttf'))
pdfmetrics.registerFont(TTFont('UbuntuBI', ruta+'Ubuntu-BI.ttf'))
pdfmetrics.registerFont(TTFont('UbuntuRI', ruta+'Ubuntu-RI.ttf'))
pdfmetrics.registerFontFamily('Ubuntu',normal='Ubuntu',bold='UbuntuB',italic='UbuntuRI',boldItalic='UbuntuBI',)
pdfmetrics.registerFont(TTFont('Calibri', ruta+'CALIBRI.TTF'))
pdfmetrics.registerFont(TTFont('CalibriB', ruta+'CALIBRIB.TTF'))
pdfmetrics.registerFont(TTFont('CalibriBI', ruta+'CALIBRIZ.TTF'))
pdfmetrics.registerFont(TTFont('CalibriRI', ruta+'CALIBRII.TTF'))
pdfmetrics.registerFontFamily('Calibri',normal='Calibri',bold='CalibriB',italic='CalibriRI',boldItalic='CalibriBI',)
pdfmetrics.registerFont(TTFont('Consolas', ruta+'CONSOLA.TTF'))
pdfmetrics.registerFont(TTFont('ConsolasB', ruta+'CONSOLAB.TTF'))
pdfmetrics.registerFont(TTFont('ComsolasBI', ruta+'CONSOLAZ.TTF'))
pdfmetrics.registerFont(TTFont('ConsolasRI', ruta+'CONSOLAI.TTF'))
pdfmetrics.registerFontFamily('Consolas',normal='Consolas',bold='CalibriB',italic='CalibriRI',boldItalic='CalibriBI',)
__author__="econain"
__date__ ="$11/11/2011 10:53:44 AM$"
UNIDADES = ( '', 'UN ', 'DOS ', 'TRES ', 'CUATRO ', 'CINCO ', 'SEIS ', 'SIETE ', 'OCHO ', 'NUEVE ', 'DIEZ ', 'ONCE ', 'DOCE ', 'TRECE ', 'CATORCE ', 'QUINCE ', 'DIECISEIS ', 'DIECISIETE ', 'DIECIOCHO ', 'DIECINUEVE ', 'VEINTE ')
DECENAS = ('VENTI', 'TREINTA ', 'CUARENTA ', 'CINCUENTA ', 'SESENTA ', 'SETENTA ', 'OCHENTA ', 'NOVENTA ', 'CIEN ')
CENTENAS = ('CIENTO ', 'DOSCIENTOS ', 'TRESCIENTOS ', 'CUATROCIENTOS ', 'QUINIENTOS ', 'SEISCIENTOS ', 'SETECIENTOS ', 'OCHOCIENTOS ', 'NOVECIENTOS '  )
Esempio n. 60
-1
def _register_fonts(settings):
    global DEFAULT_FONT

    first_fname = None
    default_fontdir = settings.get('netprofile.fonts.directory', '')
    default_family = settings.get('netprofile.fonts.default_family', 'tinos')
    fontcfg = make_config_dict(settings, 'netprofile.fonts.family.')
    fontcfg = as_dict(fontcfg)
    for fname, cfg in fontcfg.items():
        if 'normal' not in cfg:
            continue
        fname = cfg.get('name', fname)
        if first_fname is None:
            first_fname = fname
        fontdir = cfg.get('directory', default_fontdir)
        pdfmetrics.registerFont(ttfonts.TTFont(
            fname,
            os.path.join(fontdir, cfg['normal'])))
        reg = {'normal': fname}

        if 'bold' in cfg:
            reg['bold'] = fname + '_b'
            pdfmetrics.registerFont(ttfonts.TTFont(
                reg['bold'],
                os.path.join(fontdir, cfg['bold'])))
        else:
            reg['bold'] = fname

        if 'italic' in cfg:
            reg['italic'] = fname + '_i'
            pdfmetrics.registerFont(ttfonts.TTFont(
                reg['italic'],
                os.path.join(fontdir, cfg['italic'])))
        else:
            reg['italic'] = fname

        if 'bold_italic' in cfg:
            reg['boldItalic'] = fname + '_bi'
            pdfmetrics.registerFont(ttfonts.TTFont(
                reg['boldItalic'],
                os.path.join(fontdir, cfg['bold_italic'])))
        else:
            reg['boldItalic'] = fname

        pdfmetrics.registerFontFamily(fname, **reg)

    DEFAULT_FONT = 'Times-Roman'
    if default_family in fontcfg:
        DEFAULT_FONT = fontcfg[default_family].get('name', default_family)
    elif first_fname:
        DEFAULT_FONT = first_fname
    return DEFAULT_FONT