From f7af6e23fb549f632e76584c8068bfcec59bcacb Mon Sep 17 00:00:00 2001 From: Holger Brunn Date: Wed, 27 Nov 2024 19:57:22 +0100 Subject: [PATCH] [IMP] report_qweb_pdf_watermark: support pypdf >= 2.0 --- report_qweb_pdf_watermark/models/report.py | 30 +++++++++++++++------- 1 file changed, 21 insertions(+), 9 deletions(-) diff --git a/report_qweb_pdf_watermark/models/report.py b/report_qweb_pdf_watermark/models/report.py index 40ecd027cc..d6ba304696 100644 --- a/report_qweb_pdf_watermark/models/report.py +++ b/report_qweb_pdf_watermark/models/report.py @@ -19,8 +19,16 @@ logger.error("ImportError: The PdfImagePlugin could not be imported") try: - from PyPDF2 import PdfFileReader, PdfFileWriter # pylint: disable=W0404 - from PyPDF2.utils import PdfReadError # pylint: disable=W0404 + + try: + from PyPDF2 import PdfReader, PdfWriter # pylint: disable=W0404 + from PyPDF2.errors import PdfReadError # pypdf >= 2.0 + except ImportError: + from PyPDF2 import ( # pylint: disable=W0404 + PdfFileReader as PdfReader, + PdfFileWriter as PdfWriter, + ) + from PyPDF2.utils import PdfReadError # pypdf < 2.0 except ImportError: logger.debug("Can not import PyPDF2") @@ -109,11 +117,11 @@ def _run_wkhtmltopdf( if not watermark: return result - pdf = PdfFileWriter() + pdf = PdfWriter() pdf_watermark = None try: - pdf_watermark = PdfFileReader(BytesIO(watermark)) - except PdfReadError: + pdf_watermark = PdfReader(BytesIO(watermark)) + except (UnicodeDecodeError, PdfReadError): # let's see if we can convert this with pillow try: Image.init() @@ -125,7 +133,7 @@ def _run_wkhtmltopdf( if isinstance(resolution, tuple): resolution = resolution[0] image.save(pdf_buffer, "pdf", resolution=resolution) - pdf_watermark = PdfFileReader(pdf_buffer) + pdf_watermark = PdfReader(pdf_buffer) except Exception as e: logger.exception("Failed to load watermark", e) @@ -136,12 +144,16 @@ def _run_wkhtmltopdf( if not self.pdf_has_usable_pages(pdf_watermark.numPages): return result - for page in PdfFileReader(BytesIO(result)).pages: + for page in PdfReader(BytesIO(result)).pages: watermark_page = pdf.addBlankPage( page.mediaBox.getWidth(), page.mediaBox.getHeight() ) - watermark_page.mergePage(pdf_watermark.getPage(0)) - watermark_page.mergePage(page) + # merge_page is >= 2.0, mergePage < 2.0 + merge_page = ( + getattr(watermark_page, "merge_page", None) or watermark_page.mergePage + ) + merge_page(pdf_watermark.getPage(0)) + merge_page(page) pdf_content = BytesIO() pdf.write(pdf_content)