Пример #1
0
def dotest(outputname, nostamp):
    fpdf.set_global('SYSTEM_TTFONTS', "c:\\WINDOWS\\Fonts")

    pdf = fpdf.FPDF()
    if nostamp:
        pdf._putinfo = lambda: common.test_putinfo(pdf)

    pdf.add_page()
    # Add a Windows System font (uses UTF-8)
    t0 = time.time()
    pdf.add_font('sysfont','','arial.ttf',uni=True)
    pdf.set_font('sysfont','',14)
    t1 = time.time()
    if not nostamp:
        common.log("ttf loading time", t1-t0)

    # Load a UTF-8 string from a file and print it
    with open(os.path.join(common.basepath, "HelloWorld.txt"), "rb") as file:
        txt = file.read().decode("UTF-8")
    pdf.multi_cell(25, 5, txt)

    pdf.text(100, 5, '1234')

    pdf.write(5,'To find out what\'s new in self tutorial, click ')
    pdf.set_font('','U')
    link=pdf.add_link()
    pdf.write(5,'here',link)

    # Select a standard font (uses windows-1252)
    pdf.set_font('Arial','',14)
    pdf.ln(10)
    pdf.write(5, 'The file size of this PDF is only 12 KB.')

    pdf.output(outputname, 'F')
Пример #2
0
def create_pdf_file(cmd_args, all_news):
    """
    Creates and fills in the PDF file with the required data
    """
    path_to_pdf = create_path_to_file(cmd_args.to_pdf, 'RSS_NEWS.pdf')

    # --- normal cache mode ---
    set_global("FPDF_CACHE_MODE", 0)

    pdf = FPDF(orientation='P', unit='mm', format='A4')
    pdf.set_margins(5, 10, 5)
    pdf.add_page()

    # use downloaded unicode font
    pdf.add_font('dejavu',
                 '',
                 os.path.join(FONT_PATH, 'DejaVuSans.ttf'),
                 uni=True)

    pdf.set_font('dejavu', size=20)
    pdf.set_text_color(5, 14, 110)
    pdf.cell(200, 10, txt=f'RSS News', ln=1, align="C")
    pdf.ln(10)
    pdf.set_text_color(0, 0, 0)

    for new in all_news:
        add_new_to_pdf(cmd_args, new, pdf)

    LOGGER.info(f'Download PDF file with required news to the {path_to_pdf}')

    try:
        pdf.output(path_to_pdf, 'F')
    except FileNotFoundError:
        raise PATHError('Setted PATH is invalid')
Пример #3
0
def dotest(outputname, nostamp):
    fpdf.set_global("FPDF_CACHE_MODE", 1)
    pdf = fpdf.FPDF()
    pdf.add_font('DejaVu', '', \
        os.path.join(common.basepath, "font", 'DejaVuSansCondensed.ttf'), \
        uni = True)
    pdf.set_font('DejaVu', '', 14)

    with open(os.path.join(common.basepath, "HelloWorld.txt"), "rb") as file:
        txt = file.read().decode("UTF-8")
    std_ln = [
        27.0849, 37.9455, 30.4927, 25.7711, 41.0175, 38.7406, 30.3445, 22.1163,
        34.8314, 12.0813, 20.0829, 14.7485, 33.4188
    ]
    for line, reqw in zip(txt.split("\n"), std_ln):
        if line[-1:] == "\r":
            line = line[:-1]
        lang = line.split(":", 1)
        w = pdf.get_string_width(lang[1])
        c = check_width(reqw, w)
        if not nostamp:
            s = lang[0] + ": "
            if c:
                s += "Ok"
            else:
                s += "%.4f != %.4f" % (w, reqw)
            common.log(s)
        assert c, "Glyph widths for \"" + lang[0] + "\" wrong!"
Пример #4
0
def dotest(outputname, nostamp):
    fpdf.set_global("FPDF_CACHE_MODE", 1)
    pdf = fpdf.FPDF()
    pdf.add_font('DejaVu', '', \
        os.path.join(common.basepath, "font", 'DejaVuSansCondensed.ttf'), \
        uni = True)
    pdf.set_font('DejaVu','',14)

    with open(os.path.join(common.basepath, "HelloWorld.txt"), "rb") as file:
        txt = file.read().decode("UTF-8")
    std_ln = [27.0849, 37.9455, 30.4927, 25.7711, 41.0175, 38.7406, 30.3445, 
        22.1163, 34.8314, 12.0813, 20.0829, 14.7485, 33.4188]
    for line, reqw in zip(txt.split("\n"), std_ln):
        if line[-1:] == "\r":
            line = line[:-1]
        lang = line.split(":", 1)
        w = pdf.get_string_width(lang[1])
        c = check_width(reqw, w)
        if not nostamp:
            s = lang[0] + ": "
            if c:
                s += "Ok"
            else:
                s += "%.4f != %.4f" % (w, reqw)
            common.log(s)
        assert c, "Glyph widths for \"" + lang[0] + "\" wrong!"
Пример #5
0
 def ready(self):
     """Sets global options for FPDF"""
     from fpdf import set_global
     from tempfile import mkdtemp
     import muckrock.task.signals  # pylint: disable=unused-import,unused-variable
     # cache in a temp directory since the font
     # directory is read only on heroku
     set_global('FPDF_CACHE_MODE', 2)
     set_global('FPDF_CACHE_DIR', mkdtemp())
Пример #6
0
    def init_theme_fonts(self):
        fpdf.set_global("FPDF_FONT_DIR", self.theme_dir)

        for finfo in self.theme.get("fonts", []):
            try:
                name, style, fname = finfo
            except ValueError:
                raise ThemeError("invalid 'fonts' in theme, fmt: [ name, style, fname ]")

            if style not in [ "B", "I", "BI", "IB", "" ]:
                raise ThemeError("invalid style in 'fonts' - '%s'" % style)

            fname = os.path.join(self.theme_dir, fname)
            if not os.path.exists(fname):
                raise ThemeError("font file '%s' not found" % fname)

            self.pdf.add_font(name, style, fname, uni=True)
Пример #7
0
    def init_theme_fonts(self):
        fpdf.set_global("FPDF_FONT_DIR", self.theme_dir)

        for finfo in self.theme.get("fonts", []):
            try:
                name, style, fname = finfo
            except ValueError:
                raise ThemeError(
                    "invalid 'fonts' in theme, fmt: [ name, style, fname ]")

            if style not in ["B", "I", "BI", "IB", ""]:
                raise ThemeError("invalid style in 'fonts' - '%s'" % style)

            fname = os.path.join(self.theme_dir, fname)
            if not os.path.exists(fname):
                raise ThemeError("font file '%s' not found" % fname)

            self.pdf.add_font(name, style, fname, uni=True)
Пример #8
0
def dotest(outputname, nostamp):
    fpdf.set_global("FPDF_CACHE_MODE", 1)
    pdf = FPDF()
    if nostamp:
        pdf._putinfo = lambda: common.test_putinfo(pdf)

    pdf.add_page()
    # Add a Unicode font (uses UTF-8)
    pdf.add_font('DejaVu', '', \
        os.path.join(common.basepath, "font", 'DejaVuSans.ttf'), \
        uni = True)
    pdf.set_font('DejaVu', '', 14)
    with open(os.path.join(common.basepath, "HelloWorld.txt"), "rb") as file:
        txt = file.read().decode("UTF-8")

    if not nostamp:
        text(pdf, txt, 100, nostamp)
    text(pdf, txt, 75, nostamp)
    text(pdf, txt, 125, nostamp)

    pdf.output(outputname, 'F')
Пример #9
0
def dotest(outputname, nostamp):
    fpdf.set_global("FPDF_CACHE_MODE", 1)
    pdf = FPDF()
    if nostamp:
        pdf._putinfo = lambda: common.test_putinfo(pdf)

    pdf.add_page()
    # Add a Unicode font (uses UTF-8)
    pdf.add_font('DejaVu', '', \
        os.path.join(common.basepath, "font", 'DejaVuSans.ttf'), \
        uni = True)
    pdf.set_font('DejaVu', '', 14)
    with open(os.path.join(common.basepath, "HelloWorld.txt"), "rb") as file:
        txt = file.read().decode("UTF-8")

    if not nostamp:
        text(pdf, txt, 100, nostamp)
    text(pdf, txt, 75, nostamp)
    text(pdf, txt, 125, nostamp)

    pdf.output(outputname, 'F')
Пример #10
0
    def __init__(self, file_handler, report_file_name,
                 open_after_download_flag, properties):
        self.file_handler = file_handler
        self.open_after_download = open_after_download_flag
        self.properties = properties
        self.font_path = join(self.file_handler.fonts_dir,
                              'DejaVuSans.ttf')  # unicode font
        self.pdf = FPDF(orientation='P', unit='mm', format='A4')
        fpdf.set_global("FPDF_CACHE_MODE", 1)

        # get date & time
        current_date = datetime.now().strftime("%d.%m.%Y  %H:%M")
        current_timestamp = str(time.time()).replace('.', '')

        self.title = properties.report_title
        self.subtitle = properties.report_subtitle
        self.subtitle_date = properties.subtitle_with_date.format(current_date)
        self.subtitle_rec_dir = properties.subtitle_with_rec_dir_path.format(
            self.file_handler.recording_dir)
        self.subtitle_export_dir = properties.subtitle_with_exported_dir_path.format(
            self.file_handler.exports_dir)
        self.pdf_file_name = properties.pdf_report_file_name.format(
            current_timestamp
        ) if report_file_name == "" else report_file_name + ".pdf"

        # table with fixation_report.csv data
        self.fixation_detector_table_description = properties.fixation_detector_table_description
        self.parameter_table_header_name = properties.fixation_detector_settings_values_param
        self.value_table_header_name = properties.fixation_detector_settings_values_val

        self.target_file_path = join(self.file_handler.downloads_dir,
                                     self.pdf_file_name)

        self.title_font_size = 25
        self.subtitle_font_size = 20
        self.subsection_title_fontsize = 25
        self.paragraph_fontsize = 14
Пример #11
0
    def createBook(self, textChapters, destination):
        destination += "\\" + self.novelName
        pdfPath = destination + "\\" + self.novelName + ".pdf"
        # if folder already existed,it deletes it
        if os.path.exists(destination):
            shutil.rmtree(destination, ignore_errors=True)
        os.mkdir(destination)

        # set UTF8 fonts
        import fpdf
        fpdf.set_global("SYSTEM_TTFONTS",
                        os.path.join(os.path.dirname(__file__), 'fonts'))
        pdf = fpdf.FPDF()
        pdf.add_font("NotoSans",
                     style="",
                     fname="NotoSans-Regular.ttf",
                     uni=True)
        pdf.add_font("NotoSans",
                     style="B",
                     fname="NotoSans-Bold.ttf",
                     uni=True)
        pdf.add_font("NotoSans",
                     style="I",
                     fname="NotoSans-Italic.ttf",
                     uni=True)
        pdf.add_font("NotoSans",
                     style="BI",
                     fname="NotoSans-BoldItalic.ttf",
                     uni=True)
        pdf.set_font("NotoSans", size=12)
        for textChapter in textChapters:
            pdf.add_page()
            pdf.set_xy(10.0, 10.0)
            pdf.set_text_color(76.0, 32.0, 250.0)
            pdf.multi_cell(0, 10, textChapter)
        pdf.output(pdfPath, 'F')
Пример #12
0
def dotest(outputname, nostamp):
    pdf = fpdf.FPDF()
    if nostamp:
        pdf._putinfo = lambda: common.test_putinfo(pdf)

    fpdf.set_global("FPDF_CACHE_MODE", 1)
    # set default alias: {nb} that will be replaced with total page count
    pdf.alias_nb_pages()

    # Add a Unicode font (uses UTF-8)
    pdf.add_font('DejaVu', '', \
        os.path.join(common.basepath, "font", 'DejaVuSansCondensed.ttf'), \
        uni = True)
    pdf.set_font('DejaVu', '', 14)

    for i in range(5):
        pdf.add_page()
        pdf.set_font('Arial','B',16)
        pdf.cell(40,10,'Hello World! Page %d from {nb}' % (i + 1))
        pdf.set_font('DejaVu','',14)
        pdf.cell(40,30,'Hello World! unicode {nb}')


    pdf.output(outputname, 'F')
Пример #13
0
# Example of unicode support based on tfPDF
# http://www.fpdf.org/en/script/script92.php

import sys
import time
import fpdf

# Set system font path
fpdf.set_global('SYSTEM_TTFONTS', r"c:\WINDOWS\Fonts")

pdf = fpdf.FPDF()
pdf.add_page()

# Add a Windows System font (uses UTF-8)
t0 = time.time()
pdf.add_font('sysfont', '', 'arial.ttf', uni=True)
pdf.set_font('sysfont', '', 14)
t1 = time.time()
print "ttf loading time", t1 - t0
fn = 'winfonts.pdf'

# Load a UTF-8 string from a file and print it
txt = open('HelloWorld.txt').read()
pdf.multi_cell(15, 5, txt)

pdf.text(100, 5, '1234')

pdf.write(5, 'To find out what\'s new in self tutorial, click ')
pdf.set_font('', 'U')
link = pdf.add_link()
pdf.write(5, 'here', link)
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from bs4 import BeautifulSoup
import argparse
import os
import email, smtplib, ssl
from email import encoders
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

import fpdf
fpdf.set_global("SYSTEM_TTFONTS", os.path.join(os.path.dirname(__file__),'fonts'))

# --------------------------------------------------
def get_args():
    """Get command-line arguments"""

    parser = argparse.ArgumentParser(
        description='WRAC Session output generator',
        formatter_class=argparse.ArgumentDefaultsHelpFormatter)

    parser.add_argument('-u',
                        '--user',
                        metavar='user',
                        help='Enter either "juniors" or "sessions" depending on which output is required',
                        type=str,
                        choices=['sessions', 'juniors'],
Пример #15
0
        'place': 'Place:',
        'coords': 'Coordinates:',
        'date': 'Date:',
        'col': 'Collector(s):',
        'det': 'Identifier(s):',
        'diden': 'Date Ident.:',
        'alt': 'Altitude:',
        'country': 'Country:',
        'region': 'Region:'
        }

FPDF = fpdf.FPDF

BASE_URL = os.path.dirname(os.path.abspath(__file__))

fpdf.set_global('FPDF_FONT_DIR', os.path.join(BASE_URL, './fonts'))

BGI_LOGO_IMG = os.path.join(BASE_URL, './imgs', 'bgi_logo.png')

LABEL_WIDTH = 140
LABEL_HEIGHT = 100

FIRST_LINE = LABEL_HEIGHT/7
global LINE_HEIGHT
LINE_HEIGHT = LABEL_HEIGHT/16
LINE_SCALE = 0.85
PADDING_X = 3
PADDING_Y = 4
INTERSPACE = 1

LOGO_WIDTH = 15
Пример #16
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import fpdf
import os

BASE_PATH = os.path.dirname(os.path.abspath(__file__))
print("PATH:", BASE_PATH)

fpdf.set_global('FPDF_FONT_DIR', os.path.join(BASE_PATH, './fonts'))

BGI_LOGO_IMG = os.path.join(BASE_PATH, './imgs', 'bgi_logo.png')

# ----------- Common settings -----------------------
LABEL_WIDTH = 140
LABEL_HEIGHT = 100

FIRST_LINE = LABEL_HEIGHT / 7
LINE_HEIGHT = LABEL_HEIGHT / 16
LINE_SCALE = 0.85
PADDING_X = 3
PADDING_Y = 4
INTERSPACE = 1

LOGO_WIDTH = 15
LOGO_HEIGHT = 15

QR_SIZE = 28

TITLE_FONT_SIZE = 16
REGULAR_FONT_SIZE = 14
Пример #17
0
def dotest(outputname, nostamp):
    cachepath = os.path.join(os.path.dirname(__file__), "cache")
    if os.path.exists(cachepath):
        # cleanup dest
        for item in os.listdir(cachepath):
            os.remove(os.path.join(cachepath, item))
    else:
        # create font dir
        os.makedirs(cachepath)
    hashpath = os.path.join(os.path.dirname(__file__), "hash")
    if os.path.exists(hashpath):
        # cleanup dest
        for item in os.listdir(hashpath):
            os.remove(os.path.join(hashpath, item))
    else:
        # create font dir
        os.makedirs(hashpath)
    # copy font files
    shutil.copy(
        os.path.join(common.basepath, "font", "DejaVuSansCondensed.ttf"),
        cachepath)
    shutil.copy(os.path.join(common.basepath, "font", "DejaVuSans.ttf"),
                cachepath)
    f1 = os.path.join(cachepath, "DejaVuSansCondensed.ttf")
    f2 = os.path.join(cachepath, "DejaVuSans.ttf")

    # --- normal cache mode ---
    fpdf.set_global("FPDF_CACHE_MODE", 0)
    # first load
    t0 = time.time()
    pdf = testfile(f1, f2)
    t1 = time.time()
    assert os.path.exists(f1[:-3] +
                          "pkl"), "Pickle for DejaVuSansCondensed not found"
    assert os.path.exists(f2[:-3] + "pkl"), "Pickle for DejaVuSans not found"
    # load cached
    t2 = time.time()
    pdf = testfile(f1, f2)
    t3 = time.time()
    if not nostamp:
        common.log("Cache fonts:  ", t1 - t0)
        common.log("Reload fonts: ", t3 - t2)
    pdf.add_page()
    # trigger cw127
    #pdf.write(5, "Γειά σου κόσμος")
    pdf.write(5, "Привет!")
    pdf.write(10, "Hello")
    pdf.output(os.path.join(cachepath, "pdf0.pdf"), "F")
    # check cw127
    assert not os.path.exists(
        f1[:-3] + "cw127.pkl"), "Cw127 for DejaVuSansCondensed not found"
    assert os.path.exists(f2[:-3] +
                          "cw127.pkl"), "Unnecessary cw127 for DejaVuSans"

    # --- disable cache reading ---
    fpdf.set_global("FPDF_CACHE_MODE", 1)
    # put garbage data to cache files - fpdf should not read pkl
    trashfile(f1[:-3] + "pkl")
    trashfile(f2[:-3] + "pkl")
    trashfile(f2[:-3] + "cw127.pkl")
    # test same file
    t0 = time.time()
    pdf = testfile(f1, f2)
    t1 = time.time()
    # remove pkl files
    os.remove(f1[:-3] + "pkl")
    os.remove(f2[:-3] + "pkl")
    os.remove(f2[:-3] + "cw127.pkl")
    # test reload
    t2 = time.time()
    pdf = testfile(f1, f2)
    t3 = time.time()
    if not nostamp:
        common.log("No cache 1st: ", t1 - t0)
        common.log("No cache 2nd: ", t3 - t2)
    pdf.add_page()
    pdf.write(5, "Γειά σου κόσμος")
    pdf.write(10, "Hello")
    pdf.output(os.path.join(cachepath, "pdf1.pdf"), "F")
    # test no files created
    assert not os.path.exists(
        f1[:-3] + "pkl"), "Unnecessary file DejaVuSansCondensed.pkl"
    assert not os.path.exists(f2[:-3] +
                              "pkl"), "Unnecessary file DejaVuSans.pkl"
    assert not os.path.exists(
        f1[:-3] + "cw127.pkl"), "Unnecessary file DejaVuSansCondensed.127.pkl"
    assert not os.path.exists(
        f2[:-3] + "cw127.pkl"), "Unnecessary file DejaVuSans.127.pkl"

    # --- hash cache ---
    fpdf.set_global("FPDF_CACHE_MODE", 2)
    fpdf.set_global("FPDF_CACHE_DIR", hashpath)
    t0 = time.time()
    pdf = testfile(f1, f2)
    t1 = time.time()
    assert not os.path.exists(f1[:-3] +
                              "pkl"), "Misplaced file DejaVuSansCondensed.pkl"
    assert not os.path.exists(f2[:-3] + "pkl"), "Misplaced file DejaVuSans.pkl"
    # load cached
    t2 = time.time()
    pdf = testfile(f1, f2)
    t3 = time.time()
    # test reload
    if not nostamp:
        common.log("Hash load 1st:", t1 - t0)
        common.log("Hash load 2nd:", t3 - t2)
    # check hash
    assert os.path.exists(os.path.join(
        hashpath,
        hashfn(f1) +
        ".pkl")), "Cached pickle for DejaVuSansCondensed not found"
    assert os.path.exists(os.path.join(
        hashpath,
        hashfn(f2) + ".pkl")), "Cached pickle for DejaVuSans not found"
    pdf.add_page()
    pdf.write(5, "Хешировали, хешировали, да выдохешировали.")
    pdf.write(10, "Hello")
    pdf.output(os.path.join(cachepath, "pdf2.pdf"), "F")
    assert not os.path.exists(os.path.join(
        hashpath,
        hashfn(f1) +
        ".cw127.pkl")), "Cachecd cw127 for DejaVuSansCondensed not found"
    assert os.path.exists(os.path.join(
        hashpath,
        hashfn(f2) + ".cw127.pkl")), "Unnecessary cached cw127 for DejaVuSans"
Пример #18
0
# Example of unicode support based on tfPDF
# http://www.fpdf.org/en/script/script92.php

import sys
import time
import fpdf

# Set system font path
fpdf.set_global('SYSTEM_TTFONTS', r"c:\WINDOWS\Fonts")

pdf = fpdf.FPDF()
pdf.add_page()

# Add a Windows System font (uses UTF-8)
t0 = time.time()
pdf.add_font('sysfont','','arial.ttf',uni=True)
pdf.set_font('sysfont','',14)
t1 = time.time()
print "ttf loading time", t1-t0
fn = 'winfonts.pdf'

# Load a UTF-8 string from a file and print it
txt = open('HelloWorld.txt').read()
pdf.multi_cell(15, 5, txt)

pdf.text(100, 5, '1234')

pdf.write(5,'To find out what\'s new in self tutorial, click ')
pdf.set_font('','U')
link=pdf.add_link()
pdf.write(5,'here',link)
Пример #19
0
#  along with TInventory.  If not, see <http://www.gnu.org/licenses/>.

import os

from django.utils import formats

import fpdf
from api.models import CheckOutProcess, Item

from tinventory.settings import BASE_DIR

TEMP_DIR = "tmp"
FONTS_DIR = "fonts"

fpdf.FPDF_FONT_DIR = os.path.join(BASE_DIR, FONTS_DIR)
fpdf.set_global("FPDF_FONT_DIR", os.path.join(BASE_DIR, FONTS_DIR))
print(fpdf.FPDF_FONT_DIR)
FPDF_FONT_DIR = os.path.join(BASE_DIR, FONTS_DIR)


class Report(fpdf.FPDF):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        self.add_font("Roboto Condensed",
                      fname="RobotoCondensed-Regular.ttf",
                      uni=True)
        self.add_font("Roboto Condensed Bold",
                      fname="RobotoCondensed-Bold.ttf",
                      uni=True)
        self.add_font("Roboto Condensed Light",
Пример #20
0
from fpdf import FPDF
import fpdf
import pandas as pd
import requests

URL = "http://image.tmdb.org/t/p/w200/"

fpdf.set_global('SYSTEM_TTFONTS', "Fonts")


def get_fpdf():
    pdf = FPDF()
    pdf.add_font("NotoSans", style="", fname="NotoSans-Regular.ttf", uni=True)
    pdf.add_font("NotoSans", style="B", fname="NotoSans-Bold.ttf", uni=True)
    pdf.add_font("NotoSans", style="I", fname="NotoSans-Italic.ttf", uni=True)
    pdf.add_font("NotoSans",
                 style="BI",
                 fname="NotoSans-BoldItalic.ttf",
                 uni=True)
    return pdf


def create_pdf(oscars):
    count_cell = 0
    x_image = 15
    y_image = 14
    H_IMAGE = 51
    H_CELL = 60
    pdf = get_fpdf()
    pdf.add_page()
    pdf.set_font('NotoSans', 'B', 12)
Пример #21
0
 def __init__(self):
     fpdf.set_global("FPDF_CACHE_MODE", 2)
     fpdf.set_global("FPDF_CACHE_DIR", "/tmp")
     super(SPZPDF, self).__init__("L", "mm", "A4")
     self.add_font("DejaVu", "", "/usr/share/fonts/truetype/dejavu/DejaVuSansCondensed.ttf", uni=True)
     self.add_font("DejaVu", "B", "/usr/share/fonts/truetype/dejavu/DejaVuSansCondensed-Bold.ttf", uni=True)
Пример #22
0
def dotest(outputname, nostamp):
    cachepath = os.path.join(os.path.dirname(__file__), "cache")
    if os.path.exists(cachepath):
        # cleanup dest
        for item in os.listdir(cachepath):
            os.remove(os.path.join(cachepath, item))
    else:
        # create font dir
        os.makedirs(cachepath)
    hashpath = os.path.join(os.path.dirname(__file__), "hash")
    if os.path.exists(hashpath):
        # cleanup dest
        for item in os.listdir(hashpath):
            os.remove(os.path.join(hashpath, item))
    else:
        # create font dir
        os.makedirs(hashpath)
    # copy font files
    shutil.copy(os.path.join(common.basepath, "font", "DejaVuSansCondensed.ttf"), cachepath)
    shutil.copy(os.path.join(common.basepath, "font", "DejaVuSans.ttf"), cachepath)
    f1 = os.path.join(cachepath, "DejaVuSansCondensed.ttf")
    f2 = os.path.join(cachepath, "DejaVuSans.ttf")

    # --- normal cache mode ---
    fpdf.set_global("FPDF_CACHE_MODE", 0)
    # first load
    t0 = time.time()
    pdf = testfile(f1, f2)
    t1 = time.time()
    assert os.path.exists(f1[:-3] + "pkl"), "Pickle for DejaVuSansCondensed not found"
    assert os.path.exists(f2[:-3] + "pkl"), "Pickle for DejaVuSans not found"
    # load cached
    t2 = time.time()
    pdf = testfile(f1, f2)
    t3 = time.time()
    if not nostamp:
        common.log("Cache fonts:  ", t1 - t0)
        common.log("Reload fonts: ", t3 - t2)
    pdf.add_page()
    # trigger cw127
    #pdf.write(5, "Γειά σου κόσμος")
    pdf.write(5, "Привет!")
    pdf.write(10, "Hello")
    pdf.output(os.path.join(cachepath, "pdf0.pdf"), "F")
    # check cw127
    assert not os.path.exists(f1[:-3] + "cw127.pkl"), "Cw127 for DejaVuSansCondensed not found"
    assert os.path.exists(f2[:-3] + "cw127.pkl"), "Unnecessary cw127 for DejaVuSans"
        
    # --- disable cache reading ---
    fpdf.set_global("FPDF_CACHE_MODE", 1)
    # put garbage data to cache files - fpdf should not read pkl
    trashfile(f1[:-3] + "pkl")
    trashfile(f2[:-3] + "pkl")
    trashfile(f2[:-3] + "cw127.pkl")
    # test same file
    t0 = time.time()
    pdf = testfile(f1, f2)
    t1 = time.time()
    # remove pkl files
    os.remove(f1[:-3] + "pkl")
    os.remove(f2[:-3] + "pkl")
    os.remove(f2[:-3] + "cw127.pkl")
    # test reload
    t2 = time.time()
    pdf = testfile(f1, f2)
    t3 = time.time()
    if not nostamp:
        common.log("No cache 1st: ", t1 - t0)
        common.log("No cache 2nd: ", t3 - t2)
    pdf.add_page()
    pdf.write(5, "Γειά σου κόσμος")
    pdf.write(10, "Hello")
    pdf.output(os.path.join(cachepath, "pdf1.pdf"), "F")
    # test no files created
    assert not os.path.exists(f1[:-3] + "pkl"), "Unnecessary file DejaVuSansCondensed.pkl"
    assert not os.path.exists(f2[:-3] + "pkl"), "Unnecessary file DejaVuSans.pkl"
    assert not os.path.exists(f1[:-3] + "cw127.pkl"), "Unnecessary file DejaVuSansCondensed.127.pkl"
    assert not os.path.exists(f2[:-3] + "cw127.pkl"), "Unnecessary file DejaVuSans.127.pkl"

    # --- hash cache ---
    fpdf.set_global("FPDF_CACHE_MODE", 2)
    fpdf.set_global("FPDF_CACHE_DIR", hashpath)
    t0 = time.time()
    pdf = testfile(f1, f2)
    t1 = time.time()
    assert not os.path.exists(f1[:-3] + "pkl"), "Misplaced file DejaVuSansCondensed.pkl"
    assert not os.path.exists(f2[:-3] + "pkl"), "Misplaced file DejaVuSans.pkl"
    # load cached
    t2 = time.time()
    pdf = testfile(f1, f2)
    t3 = time.time()
    # test reload
    if not nostamp:
        common.log("Hash load 1st:", t1 - t0)
        common.log("Hash load 2nd:", t3 - t2)
    # check hash
    assert os.path.exists(os.path.join(hashpath, hashfn(f1) + ".pkl")), "Cached pickle for DejaVuSansCondensed not found"
    assert os.path.exists(os.path.join(hashpath, hashfn(f2) + ".pkl")), "Cached pickle for DejaVuSans not found"            
    pdf.add_page()
    pdf.write(5, "Хешировали, хешировали, да выдохешировали.")
    pdf.write(10, "Hello")
    pdf.output(os.path.join(cachepath, "pdf2.pdf"), "F")
    assert not os.path.exists(os.path.join(hashpath, hashfn(f1) + ".cw127.pkl")), "Cachecd cw127 for DejaVuSansCondensed not found"
    assert os.path.exists(os.path.join(hashpath, hashfn(f2) + ".cw127.pkl")), "Unnecessary cached cw127 for DejaVuSans"
Пример #23
0
import fpdf
import build_folders as bf
from fpdf import FPDF
fpdf.set_global("SYSTEM_TTFONTS", './fonts/')

header_title = None
header_date = None


def create_pdf(idx, dict):
    print('Criando')
    global header_title
    global header_date

    header_title = dict['Title']
    header_date = dict['Date']
    pdf = PDF()
    pdf.add_font("NotoSans", style="", fname="NotoSans-Regular.ttf", uni=True)
    pdf.add_font("NotoSans", style="B", fname="NotoSans-Bold.ttf", uni=True)
    pdf.add_font("NotoSans", style="I", fname="NotoSans-Italic.ttf", uni=True)
    pdf.add_font("NotoSans",
                 style="BI",
                 fname="NotoSans-BoldItalic.ttf",
                 uni=True)
    #print(content)
    pdf.build(dict)
    pdf.output(bf.get_folder() + '/Noticia-{}.pdf'.format(idx), 'F')


class PDF(FPDF):
    def header(self):