Background information
I am using PDFBox 2.0.27 and try to add watermarks on my PDF (may) containing multiple pages of different Din formats and orientations (vertical & horizontal).
For this reason I created for each combination of Din format and orientation a PDF file, which I want to utilize for watermarks of the respective pages of my original PDF.
Approach
The specific page and overlay/watermark file relation is stored in HashMap<Integer, String> overlayGuide = new HashMap<>();
For adding watermarks to each page I use the following code:
PDDocument originalPDF = PDDocument.load(new File("..Original_PDF.pdf")); // To adjust with actual path
HashMap<Integer, String> overlayGuide = new HashMap<>();
overlayGuide.put(1, "..A1_Horizontal_Watermark.pdf"); // To adjust with actual path
Overlay overlay = new Overlay();
overlay.setInputPDF(originalPDF);
overlay.setOverlayPosition(Overlay.Position.BACKGROUND);
originalPDF = overlay.overlay(overlayGuide);
originalPDF.save(new File("C:\\AxaviaPdfServiceAPI\\temp\\watermarked.pdf"));
overlay.close();
Source of code snippet
This code is based on the suggested code from here.
Problem
The watermarking doesn't work. The output generated by the above code is the original PDF. I receive no exceptions or errors or other hints I could deliver.
What am I missing? The method overlay.setOutputFile("final.pdf");
as posted in the linked stackoverflow question is not available in my currently used version of PDFBox.
Size and orientation of page from original PDF and watermark PDF is (/should be) the same. Manual adding of watermark via Adobe Acrobat DC is working.
Expected result
Based on manual adding via Adobe Acrobat DC I expected something like here
Unfortunatelly I couldn't find an option in Overlay
class to set opacity for the watermark PDF to add.
What I tried
See code snippet above & googeling, which resulted in more or less the same code snippet. Other solutions only handled simple text as watermark or images.
Example files
Example files to test my code can be found here
Boundary conditions
I want to stick at template PDFs for watermarking, since I want to add additional icons/pictures. The provided example file is just a short draft.
Update 2022-11-06
Please share both the input and the output PDFs of your test. – mkl
Original PDF: here
Watermark PDF: here
Result PDF: here
Any help is appreciated. Thank you in advance.
CodePudding user response:
Thanks to mkl for pointing out, that the approach with HashMap<Integer, String> overlayGuide = new HashMap<>();
is currently bugged.
Solution/Work-around
I used the method overlay.overlayDocuments(overlayGuidePDDocuments);
with overlayGuidePDDocuments = HashMap<Integer, PDDocument>
and the watermarks are now set correctly.
Remarks
Setting an opacity for the watermark template PDFs is not possible (or I don't get it how to apply). Therefore the watermark template PDFs are prepared with an opacity.