From f0001604231e4c3c5bff07bfa1930d176712c767 Mon Sep 17 00:00:00 2001 From: Guillaume Ayoub Date: Thu, 25 Jul 2019 11:25:40 +0200 Subject: [PATCH] Add code snippet to set PDF magnification Fix #692. --- docs/tips-tricks.rst | 44 ++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 42 insertions(+), 2 deletions(-) diff --git a/docs/tips-tricks.rst b/docs/tips-tricks.rst index 78b252f5c..5d10019a6 100644 --- a/docs/tips-tricks.rst +++ b/docs/tips-tricks.rst @@ -1,10 +1,12 @@ -Tips & tricks +Tips & Tricks ============= This page presents some tips and tricks, mostly in the form of code snippets. .. note:: - These tips are primarily sourced from the community. You too can share your tricks with the community, just open a PR! (If you do so, don't forget to make your code readable for the others and add some context :)). + These tips are primarily sourced from the community. You too can share your tricks with the community, just open a PR! (If you do so, don't forget to make your code readable for the others and add some context :).) + + Include header and footer of arbitrary complexity in a PDF ---------------------------------------------------------- @@ -217,3 +219,41 @@ Show me the code! .. note:: In the `CSS Generated Content for Paged Media Module `_, the W3C proposed standards to support most expected features for print media. `Running elements `_ are the CSS compliant solution to this problem. See this `issue on the project `_ for more details for a possible implementation. + + +Edit the generated PDF using WeasyPrint's PDF editor +---------------------------------------------------- + +Why this snippet? +................. + +You may want to edit the PDF generated by WeasyPrint, for example to add PDF features that are not supported by CSS properties. + +WeasyPrint includes a very simple and limited PDF editor that can be used in this case. This PDF editor only works with documents generated by WeasyPrint. + +In this example, we will set the magnification to "Fit page", so that the PDF size automatically fits in the PDF reader window when open. + +How to use this snippet? +........................ + +You can use the code below as a simple Python script. Change the URL you want to render and the path of the generated PDF to fit your needs. + +If you want to add other features, you will have to read the PDF specification! + +Show me the code! +................. + +.. code-block:: python + + from io import BytesIO + from weasyprint import HTML + from weasyprint.pdf import PDFFile, pdf_format + + html = HTML('http://weasyprint.org/') + content = BytesIO(html.write_pdf()) + pdf_file = PDFFile(content) + params = pdf_format('/OpenAction [0 /FitV null]') + pdf_file.extend_dict(pdf_file.catalog, params) + pdf_file.finish() + pdf = pdf_file.fileobj.getvalue() + open('/tmp/weasyprint.pdf', 'wb').write(pdf)