Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

DOC: Stamp images directly on a PDF #2357

Merged
merged 1 commit into from
Dec 23, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 53 additions & 0 deletions docs/user/add-watermark.md
Original file line number Diff line number Diff line change
Expand Up @@ -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")
```