Skip to content

Commit c43ca15

Browse files
DOC: Stamp images directly on a PDF (#2357)
See #1945 Co-authored-by: dmjohnsson23 <dmjohn235@gmail.com>
1 parent 133ccb1 commit c43ca15

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed

docs/user/add-watermark.md

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,3 +58,56 @@ Example of stamp:
5858

5959
Example of watermark:
6060
![watermark.png](watermark.png)
61+
62+
63+
## Stamping images directly
64+
65+
The above code only works for stamps that are already in PDF format.
66+
However, you can easilly convert an image to PDF image using
67+
[Pillow](https://pypi.org/project/Pillow/).
68+
69+
70+
```python
71+
from io import BytesIO
72+
from pathlib import Path
73+
from typing import List, Union
74+
75+
from PIL import Image
76+
from pypdf import PageRange, PdfReader, PdfWriter, Transformation
77+
78+
79+
def image_to_pdf(stamp_img: Union[Path, str]) -> PdfReader:
80+
img = Image.open(stamp_img)
81+
img_as_pdf = BytesIO()
82+
img.save(img_as_pdf, "pdf")
83+
return PdfReader(img_as_pdf)
84+
85+
86+
def stamp_img(
87+
content_pdf: Union[Path, str],
88+
stamp_img: Union[Path, str],
89+
pdf_result: Union[Path, str],
90+
page_indices: Union[PageRange, List[int], None] = None,
91+
):
92+
# Convert the image to a PDF
93+
stamp_pdf = image_to_pdf(stamp_img)
94+
95+
# Then use the same stamp code from above
96+
stamp_page = stamp_pdf.pages[0]
97+
98+
writer = PdfWriter()
99+
100+
reader = PdfReader(content_pdf)
101+
writer.append(reader, pages=page_indices)
102+
for content_page in writer.pages:
103+
content_page.merge_transformed_page(
104+
stamp_page,
105+
Transformation(),
106+
)
107+
108+
with open(pdf_result, "wb") as fp:
109+
writer.write(fp)
110+
111+
112+
stamp_img("example.pdf", "example.png", "out.pdf")
113+
```

0 commit comments

Comments
 (0)