user3648781
user3648781

Reputation: 13

How to use Itext to add an image file into an existing PDF, and declare a unique name for it?

In order to find an added image file and replace it with another image file when I read a PDF next time, I want to use Itext to add an image file into an existing PDF, and declare a unique name for it. My code:

    final PdfName key = new PdfName("MY_SIGN_KEY");
    final PdfName val = new PdfName("MY_SIGN_VAL");

    Image signImage=Image.getInstance(signPngFile.getAbsolutePath());
    signImage.setAlignment(1);
    signImage.scaleAbsolute(newWidth, newHeight);
    signImage.setAbsolutePosition(200,200);

     PdfContentByte over = stamper.getOverContent(1);
     PdfImage stream = new PdfImage(signImage, "", null);
     stream.put(key,val);// a unique name for it.(设置唯一标识符)

     //PdfIndirectObject ref=over.getPdfWriter().addToBody(stream);
     //signImage.setDirectReference(ref.getIndirectReference()); 
     over.addImage(signImage);

Upvotes: 1

Views: 2232

Answers (1)

Bruno Lowagie
Bruno Lowagie

Reputation: 77528

I have tried your code and it works for me. See the AddImageWithID example:

public void manipulatePdf(String src, String dest) throws IOException, DocumentException {
    PdfReader reader = new PdfReader(src);
    PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest));
    Image image = Image.getInstance(IMG);
    PdfImage stream = new PdfImage(image, "", null);
    stream.put(new PdfName("ITXT_SpecialId"), new PdfName("123456789"));
    PdfIndirectObject ref = stamper.getWriter().addToBody(stream);
    image.setDirectReference(ref.getIndirectReference());
    image.setAbsolutePosition(36, 400);
    PdfContentByte over = stamper.getOverContent(1);
    over.addImage(image);
    stamper.close();
    reader.close();
}

In this example, I take a file named hello.pdf and I add an image named bruno.jpg with the file hello_with_image_id.pdf as result.

The image doesn't look black:

enter image description here

The ID is added:

enter image description here

Can you try the code I shared and see if the problem persists.

I can think of one reason why you'd get a black image: in our code, we assume that a single image is added. In the case of JPEG, this is always the case. In the case of PNG or GIF though, adding one source image could result in two images being added. Strictly speaking, PDF doesn't support transparent images (depending on how you interpret the concept of transparent images). Whenever you add a single source image with transparent parts, two images will be added to the PDF: one opaque image and one image mask. The combination of the opaque image and the image mask results in something that is perceived as a transparent image. Maybe this is what happens in your case.

Upvotes: 2

Related Questions