Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing PDImageXObject with another PDFBOX 2.0.3

Tags:

java

pdf

pdfbox

I've read all similar questions and answers and I'm still stuck beacuse old questions were for old versions.

I want to replace all images in given PDF with external images.

Here is what I have done so far:

   for(int a=0;a<doc.getNumberOfPages().size();a++){
        PDPage p = doc.getPage(a);
        PDResources resources = p.getResources();
        for (COSName xObjectName : resources.getXObjectNames()) {
            PDXObject xObject = resources.getXObject(xObjectName);
            if (xObject instanceof PDImageXObject) {
                PDImageXObject original_img = ((PDImageXObject) xObject);
                PDImageXObject replacement_img = PDImageXObject.createFromFile(f.getImages().get(a), doc);
            }        
        }
    }

So, I have 2 PDImageXObjects names original_img and replacement_img. Replacement_img has to overwrite original_img.

like image 245
GrayFox Avatar asked Oct 20 '25 04:10

GrayFox


1 Answers

To replace the old image by the new image, one has to set the resource in question to the new image, i.e.

resources.put(xObjectName, replacement_img);

after the instantiation of replacement_img in the OP's code.

like image 200
mkl Avatar answered Oct 21 '25 16:10

mkl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!