@@ -58,3 +58,56 @@ Example of stamp:
58
58
59
59
Example of watermark:
60
60
![ 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