Last active
June 30, 2021 22:13
-
-
Save toast38coza/7fcaecadc662266660142ab1fb873302 to your computer and use it in GitHub Desktop.
Generate an encrypted pdf with WeasyPrint and PyPDF2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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()) | |
""" |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
PyPDF2 | |
WeasyPrint |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment