|
| 1 | +#!/usr/bin/env python |
| 2 | +# -*- coding: utf8 -*- |
| 3 | + |
| 4 | +"""convenience wrapper for fpdf with unicode support |
| 5 | +Usage: |
| 6 | + form wfpdf import PDF |
| 7 | + with PDF('output.pdf') as pdf: # or ..PDF('output.pdf', ffamily [, fstyle, fsize, ffname]).. |
| 8 | + pdf.write(8, u"unicode text") # ffname: name of .ttf file, it is recommended save fonts into fpdf/font/ |
| 9 | + # you can download unicode fonts from pyfpdf.googlecode.com/files/fpdf_unicode_font_pack.zip |
| 10 | +
|
| 11 | +This was designed with fpdf 1.7.2 and it could be useful: |
| 12 | + for the calling with with.. syntax, |
| 13 | + for help with installation of unicode fonts as long as these fonts aren't included directly inside the fpdf module |
| 14 | +""" |
| 15 | + |
| 16 | +from fpdf import FPDF |
| 17 | + |
| 18 | +FONT_ERROR = ("Font not found. Hint: To output unicode characters copy unicode fonts " |
| 19 | + "from pyfpdf.googlecode.com/files/fpdf_unicode_font_pack.zip into fpdf/font/ " |
| 20 | + "(or to the location defined in SYSTEM_TTFONTS or FPDF_FONTPATH, " |
| 21 | + "or instantiate as PDF(filename, explicit_unicode_font, ffname=<path>/<fontfilename>)") |
| 22 | + |
| 23 | +class PDF(): |
| 24 | + def __init__(self, fname, ffamily=None, fstyle='', fsize=0, ffname=None): |
| 25 | + self.w_fname = fname |
| 26 | + self.w_pdf = FPDF() |
| 27 | + self.w_pdf.add_page() |
| 28 | + explicit = ffamily |
| 29 | + if not explicit: |
| 30 | + # try Unicode fonts from fpdf/font (or location defined by SYSTEM_TTFONTS or FPDF_FONTPATH) first |
| 31 | + ffamily = 'DejaVu' |
| 32 | + ffname = 'DejaVuSansCondensed.ttf' |
| 33 | + try: |
| 34 | + if ffname: |
| 35 | + self.w_pdf.add_font(ffamily, '', ffname, uni=True) |
| 36 | + self.w_pdf.set_font(ffamily) |
| 37 | + except RuntimeError: |
| 38 | + if not explicit: # fallback from unicode to latin-1 |
| 39 | + self.w_pdf.set_font('Arial') |
| 40 | + else: |
| 41 | + raise RuntimeError(FONT_ERROR) |
| 42 | + |
| 43 | + def __enter__(self): |
| 44 | + return self.w_pdf |
| 45 | + |
| 46 | + def __exit__(self, *args): |
| 47 | + self.w_pdf.output(self.w_fname, 'F') |
| 48 | + |
| 49 | + |
| 50 | +if __name__ == '__main__': |
| 51 | + # test the unicode support |
| 52 | + with PDF('test_unicode.pdf') as pdf: |
| 53 | + try: |
| 54 | + pdf.write(8, u"kůň úpěl ódy dobrý češtin") |
| 55 | + except UnicodeEncodeError: |
| 56 | + raise RuntimeError(FONT_ERROR) |
| 57 | + with PDF('test_unicode.pdf', 'Arial') as pdf: |
| 58 | + pdf.write("nice horses songs") |
0 commit comments