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 428dbe7 commit fabb5d3
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

Check warning on line 25 in report_qweb_pdf_watermark/models/report.py

View check run for this annotation

Codecov / codecov/patch

report_qweb_pdf_watermark/models/report.py#L25

Added line #L25 was not covered by tests
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 @@ -108,11 +116,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 @@ -124,7 +132,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 @@ -135,12 +143,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 fabb5d3

Please sign in to comment.