Kozea / WeasyPrint

The awesome document factory
https://weasyprint.org
BSD 3-Clause "New" or "Revised" License
7.15k stars 680 forks source link

Question: Is there a way to set the magnification? #692

Closed adonig closed 5 years ago

adonig commented 6 years ago

First of all, let me thank you for maintaining this great library! :-)

Is there a way to set the magnification to "Fit page" like with Acrobat Pro shown in this video?

liZe commented 6 years ago

First of all, let me thank you for maintaining this great library! :-)

You're welcome!

Is there a way to set the magnification to "Fit page" like with Acrobat Pro shown in this video?

No, but I think that it's possible using WeasyPrint's Python API … and some PDF knowledge. If you' have some PDF skills, the next paragraph may be useful. If you're not, then, you can skip them :wink:.

(According to the PDF spec, we have to add a "OpenAction" destination in the PDF's catalog, leading to the first page with the "/FitV" option.)

If you're not afraid of using WeasyPrint's API, I can try to write a small demo sample, or even give you some hints so that you can write it yourself!

Adding an option working out-of-the-box may be useful, but the hard part is to find a clean API for this, as there's a lot of different options.

adonig commented 6 years ago

Thank you for the explanation! It was so good, I was able to make it work :-)

I found no reference to the catalog in the v0.42.3 API, so I had to switch to the current master.

Here is a piece of code for other people who might read the issue and want to do the same:

from io import BytesIO
from weasyprint.pdf import PDFFile
from weasyprint.pdf import pdf_format

# Add your code rendering HTML into a weasyprint.Document here.
# In my case this was done by django-weasyprint.

content = BytesIO(document.write_pdf())
pdf_file = PDFFile(content)
params = pdf_format('/OpenAction [0 /FitV null]')
pdf_file.extend_dict(pdf_file.catalog, params)
pdf_file.finish()
return pdf_file.fileobj.getvalue()
liZe commented 6 years ago

Thank you for the explanation! It was so good, I was able to make it work :-)

:tada:

I found no reference to the catalog in the v0.42.3 API, so I had to switch to the current master.

Here is a piece of code for other people who might read the issue and want to do the same:

I keep the issue open as we should give this example in the documentation.