Skip to content

Instantly share code, notes, and snippets.

@toast38coza
Last active June 30, 2021 22:13
Show Gist options
  • Save toast38coza/7fcaecadc662266660142ab1fb873302 to your computer and use it in GitHub Desktop.
Save toast38coza/7fcaecadc662266660142ab1fb873302 to your computer and use it in GitHub Desktop.
Generate an encrypted pdf with WeasyPrint and PyPDF2
import PyPDF2
import io
from weasyprint import HTML
password = 'foo'
url = "https://google.com"
pdf = HTML(url).write_pdf()
in_file = io.BytesIO(pdf)
out_file = open('google.pdf', 'wb')
pdfReader = PyPDF2.PdfFileReader(in_file)
pdfWriter = PyPDF2.PdfFileWriter()
pdfWriter.appendPagesFromReader(pdfReader)
pdfWriter.encrypt(password)
pdfWriter.write(out_file)
"""python
# want to write to an inmemory stream instead? try this:
out_file = io.BytesIO()
...
pdfWriter.encrypt(password)
pdfWriter.write(out_file)
print(out_file.getvalue())
"""
PyPDF2
WeasyPrint
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment