Skip to content

Commit

Permalink
Add code snippet to set PDF magnification
Browse files Browse the repository at this point in the history
Fix #692.
  • Loading branch information
liZe committed Jul 25, 2019
1 parent 8d10c01 commit f000160
Showing 1 changed file with 42 additions and 2 deletions.
44 changes: 42 additions & 2 deletions docs/tips-tricks.rst
Original file line number Diff line number Diff line change
@@ -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
----------------------------------------------------------
Expand Down Expand Up @@ -217,3 +219,41 @@ Show me the code!
.. note::

In the `CSS Generated Content for Paged Media Module <https://www.w3.org/TR/css-gcpm-3/>`_, the W3C proposed standards to support most expected features for print media. `Running elements <https://www.w3.org/TR/css-gcpm-3/#running-elements>`_ are the CSS compliant solution to this problem. See this `issue on the project <https://github.com/Kozea/WeasyPrint/issues/92>`_ 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)

0 comments on commit f000160

Please sign in to comment.