From c43ca15e91b46a5c7b477fa8584a96c698349902 Mon Sep 17 00:00:00 2001 From: Martin Thoma Date: Sat, 23 Dec 2023 12:10:03 +0100 Subject: [PATCH] DOC: Stamp images directly on a PDF (#2357) See https://github.com/py-pdf/pypdf/pull/1945 Co-authored-by: dmjohnsson23 --- docs/user/add-watermark.md | 53 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) diff --git a/docs/user/add-watermark.md b/docs/user/add-watermark.md index e296d79a8..74ef3f451 100644 --- a/docs/user/add-watermark.md +++ b/docs/user/add-watermark.md @@ -58,3 +58,56 @@ Example of stamp: Example of watermark: ![watermark.png](watermark.png) + + +## Stamping images directly + +The above code only works for stamps that are already in PDF format. +However, you can easilly convert an image to PDF image using +[Pillow](https://pypi.org/project/Pillow/). + + +```python +from io import BytesIO +from pathlib import Path +from typing import List, Union + +from PIL import Image +from pypdf import PageRange, PdfReader, PdfWriter, Transformation + + +def image_to_pdf(stamp_img: Union[Path, str]) -> PdfReader: + img = Image.open(stamp_img) + img_as_pdf = BytesIO() + img.save(img_as_pdf, "pdf") + return PdfReader(img_as_pdf) + + +def stamp_img( + content_pdf: Union[Path, str], + stamp_img: Union[Path, str], + pdf_result: Union[Path, str], + page_indices: Union[PageRange, List[int], None] = None, +): + # Convert the image to a PDF + stamp_pdf = image_to_pdf(stamp_img) + + # Then use the same stamp code from above + stamp_page = stamp_pdf.pages[0] + + writer = PdfWriter() + + reader = PdfReader(content_pdf) + writer.append(reader, pages=page_indices) + for content_page in writer.pages: + content_page.merge_transformed_page( + stamp_page, + Transformation(), + ) + + with open(pdf_result, "wb") as fp: + writer.write(fp) + + +stamp_img("example.pdf", "example.png", "out.pdf") +```