This website uses cookies for visitor traffic analysis. By using the website, you agree with storing the cookies on your computer.More information

Add an image to an existing PDF

Do you know the problem: You got a PDF document and want to add an image to a single page, but you have no printer/scanner.

Normally jPdf Tweak solves simple PDF problems, but it is not possible to add a simple image to a PDF file :( . It supports watermarks, but it is not supported to set the position or page.

I wrote some lines of code to solve my problem:

PdfReader pdr = new PdfReader("D:\\test.pdf");

PdfStamper pds = new PdfStamper(pdr, new FileOutputStream("D:\\test_image.pdf"));

PdfContentByte pcbPosition;

PdfGState pgsTransparency;

Image img;

for (int i = 1, anz = pdr.getNumberOfPages(); i <= anz; i++)
{
        //only first page
        if (i == 1)
        {
                pcbPosition = pds.getOverContent(i);
   
                pgsTransparency = new PdfGState();
                pgsTransparency.setFillOpacity(100 / 100f);
               
                img = Image.getInstance(FileUtil.getContent("D:\\image.png"));
               
                //x: 0 = left
                //y: 0 = bottom
                img.setAbsolutePosition(500f, 250f);
                //70 is 100%
                img.scalePercent(10);
                img.setRotationDegrees(0);
               
                pcbPosition.saveState();

                pcbPosition.setGState(pgsTransparency);
                pcbPosition.addImage(img);
       
                pcbPosition.restoreState();
        }
}

pds.close();

Use the current iText version or iText 4.2.0 (friendly license).

Leave a Reply

Spam protection by WP Captcha-Free