Source code for pdf.page_functions
from datetime import date
from lxml import etree
from textwrap import shorten
from textwrap import wrap
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from onegov.pdf.templates import Template
from reportlab.pdfgen.canvas import Canvas
[docs]
def empty_page_fn(canvas: 'Canvas', doc: 'Template') -> None:
""" An empty header/footer. """
[docs]
def page_fn_header(canvas: 'Canvas', doc: 'Template') -> None:
""" A standard header consisting of a title and the creation string. The
title is automatically wrapped and shortened.
Example::
pdf = Pdf(file, author='OneGov', created='1.1.2000')
pdf.init_a4_portrait(page_fn=page_fn_header)
"""
canvas.saveState()
canvas.setFont('Helvetica', 9)
if doc.title:
lines = wrap(doc.title, 110)[:2]
if len(lines) > 1:
lines[1] = shorten(lines[1], 100)
text = canvas.beginText()
text.setTextOrigin(
doc.leftMargin,
doc.pagesize[1] - doc.topMargin * 2 / 3
)
text.textLines(lines)
canvas.drawText(text)
if created := getattr(doc, 'created', None):
canvas.drawRightString(
doc.pagesize[0] - doc.rightMargin,
doc.pagesize[1] - doc.topMargin * 2 / 3,
created
)
canvas.restoreState()
[docs]
def page_fn_header_logo(canvas: 'Canvas', doc: 'Template') -> None:
""" A standard header consisting of a SVG logo.
The logo is drawn in its original size placed at the bottom on the header,
which allows to give extra margin at the bottom directly in the SVG.
Example::
pdf = Pdf(
file, author='OneGov', created='1.1.2000',
logo='<?xml version="1.0"><svg>...</svg>'
)
pdf.init_a4_portrait(page_fn=page_fn_header_logo)
"""
# reportlab and svglib are particularly heavy imports which are loaded by
# morepath's scan - until we can teach that scanner to ignore certain
# modules automatically we lazy load these modules here
from reportlab.graphics import renderPDF
from svglib.svglib import SvgRenderer # type:ignore[import-untyped]
canvas.saveState()
if logo := getattr(doc, 'logo', None):
parser = etree.XMLParser(remove_comments=True, recover=True)
svg = etree.fromstring(logo.encode('utf-8'), parser=parser)
drawing = SvgRenderer(path=None).render(svg)
renderPDF.draw(
drawing,
canvas,
doc.leftMargin,
doc.pagesize[1] - doc.topMargin
)
canvas.restoreState()