0

So I want to not only add text to a pdf when I create it but as well add a background image at the same time. I was wondering if this is possible since I haven't been able to find any example and the only question similar to this (This one) has not given any feedback from the person that made the question and it wasn't marked as solved.

I'm using this very simple example at the moment:

       PDDocument doc = null;
       PDPage page = null;

       try{
           doc = new PDDocument();
           page = new PDPage();

           doc.addPage(page);
           PDFont font = PDType1Font.HELVETICA_BOLD;

           PDPageContentStream content = new PDPageContentStream(doc, page);
           content.beginText();
           content.setFont( font, 12 );
           content.moveTextPositionByAmount( 100, 700 );
           content.drawString("Hello World");

           content.endText();
           content.close();
           doc.save("printme.pdf");
           doc.close();
       } catch (Exception e){
           System.out.println(e);
       }

Thanks for your time.

Community
  • 1
  • 1
this.user3272243
  • 1,166
  • 2
  • 9
  • 24

1 Answers1

1
try {
        PDDocument document = new PDDocument();
        PDPage page = new PDPage(PDPage.PAGE_SIZE_A4);
        document.addPage(page);
        PDFont font = PDType1Font.HELVETICA_BOLD;
        PDPageContentStream contentStream = new PDPageContentStream(document, page, true, true);
        addImageToPage(document, 0, 0, 4f, "D:/test.jpg", contentStream);
        contentStream.beginText();
        contentStream.setFont(font, 12);
        contentStream.moveTextPositionByAmount(100, 700);
        contentStream.drawString("Hello World");
        contentStream.endText();
        contentStream.close();
        document.save("D:/mydoc.pdf");
    } catch (Exception e) {
        System.out.println(e);
    }

method to add image :

public static void addImageToPage(PDDocument document, int x, int y, float scale, String imageFilePath, PDPageContentStream contentStream)
        throws IOException {
    BufferedImage tmp_image = ImageIO.read(new File(imageFilePath));
    BufferedImage image = new BufferedImage(tmp_image.getWidth(), tmp_image.getHeight(),
            BufferedImage.TYPE_4BYTE_ABGR);
    image.createGraphics().drawRenderedImage(tmp_image, null);
    PDXObjectImage ximage = new PDPixelMap(document, image);
    contentStream.drawXObject(ximage, x, y, ximage.getWidth() * scale, ximage.getHeight() * scale);
}
Dipali Vasani
  • 2,526
  • 2
  • 16
  • 30