Skip to content

Commit

Permalink
[IMP] report_qweb_pdf_watermark: support pypdf >= 2.0
Browse files Browse the repository at this point in the history
  • Loading branch information
hbrunn committed Nov 27, 2024
1 parent f193f8d commit f7af6e2
Showing 1 changed file with 21 additions and 9 deletions.
30 changes: 21 additions & 9 deletions report_qweb_pdf_watermark/models/report.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")

Expand Down Expand Up @@ -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()
Expand All @@ -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)

Expand All @@ -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)
Expand Down

0 comments on commit f7af6e2

Please sign in to comment.