PDFBox: Overlaying one PDF on another


/ Published in: Java
Save to your folder(s)

Generates two PDF documents and then overlays the second onto the first.


Copy this code and paste it in your HTML
  1. /**
  2.  * @param args the command line arguments
  3.  * @throws java.io.IOException
  4.  */
  5. public static void main(String[] args) throws IOException {
  6. PDDocument document1 = getFirstDoc();
  7. PDDocument document2 = getSecondDoc();
  8.  
  9. Overlay overlay = new Overlay();
  10. overlay.setOverlayPosition(Overlay.Position.FOREGROUND);
  11. overlay.setInputPDF(document1);
  12. overlay.setAllPagesOverlayPDF(document2);
  13.  
  14. Map<Integer, String> ovmap = new HashMap<Integer, String>();
  15. overlay.overlay(ovmap);
  16.  
  17. document1.save("");
  18.  
  19. document1.close();
  20. document2.close();
  21. }
  22.  
  23. static PDDocument getFirstDoc() throws IOException {
  24. PDDocument document = new PDDocument();
  25. PDPage page = new PDPage(PDRectangle.A4);
  26.  
  27. document.addPage(page);
  28.  
  29. PDPageContentStream contentStream = new PDPageContentStream(document, page);
  30.  
  31. contentStream.setNonStrokingColor(Color.RED);
  32. contentStream.addRect(0, 0, page.getMediaBox().getWidth(), page.getMediaBox().getHeight());
  33. contentStream.fill();
  34.  
  35. contentStream.close();
  36.  
  37. return document;
  38. }
  39.  
  40. static PDDocument getSecondDoc() throws IOException {
  41. PDDocument document = new PDDocument();
  42. PDPage page = new PDPage(PDRectangle.A4);
  43.  
  44. document.addPage(page);
  45.  
  46. PDPageContentStream contentStream = new PDPageContentStream(document, page);
  47.  
  48. contentStream.beginText();
  49.  
  50. contentStream.setFont(PDType1Font.TIMES_ROMAN, 12);
  51. contentStream.newLineAtOffset(25, 500);
  52. contentStream.showText("Hello World");
  53.  
  54. contentStream.endText();
  55.  
  56. contentStream.close();
  57.  
  58. return document;
  59. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.