Is there a way to display a PDF (only a single page, if that matters) in Python, without using the PyMuPDF library?
I want to export my project via PyInstaller and including PyMuPDF increases the file size from ~40 to ~105 MB. Since I only want to display my pdf and don't need any of the advanced functionalities of PyMuPDF (or any editing/manipulation at all), I was wondering if there was a way to do so without so much overhead.
The PDF is created during runtime with ReportLab.
I got it to work with the pypdfium2 package, which only adds ~3MB to the exported .exe instead of the ~60MB from mupdf.
import pypdfium2 as pdfium
image_buffer = io.BytesIO()
doc2 = pdfium.PdfDocument(input=pdf_buffer, autoclose=True)
doc2[0].render().to_pil().save(image_buffer, format='PNG')
image_bytes = image_buffer.getvalue()
Here, both pdf_buffer and image_buffer are io.Bytes() for the pdf file input and the image file output respectively.
However, setting this up for PyInstaller took bit:
In the .spec file for the PyInstaller script, you need to manually add 3 files in order for pypdfium2 to properly work. In the a=Analysis(...) call you need to add these 3 lines to the datas argument:
datas=[
    (f'{site_packages_location}/pypdfium2_raw/pdfium.dll', 'pypdfium2_raw'),
    (f'{site_packages_location}/pypdfium2_raw/version.json', 'pypdfium2_raw'),
    (f'{site_packages_location}/pypdfium2/version.json', 'pypdfium2')
]
where
site_packages_location = f"{os.getenv('LOCALAPPDATA')}/Programs/Python/Python312/Lib/site-packages/"
This answer has more info on that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With