You are viewing a plain text version of this content. The canonical link for it is here.
Posted to users@pdfbox.apache.org by Stephen Haggai <st...@gmail.com> on 2015/05/08 02:06:50 UTC

Replacing an image in a PDF file using PDFBox

Hi,

I am trying to replace an image in a PDF file using PDFBox and I am unable
to find any examples. The only example that I found on
http://stackoverflow.com/questions/17423665/replace-image-in-pdf-with-another-image-pdf-box
uses COSStream's replaceWithStream(COSStream stream) that has been
deprecated. Are there any alternatives to this method or is there another
process that I can use.

private static void changeImage(COSObject obj, PDDocument doc) {

    PDXObjectImage imageInPdf =
        (PDXObjectImage) PDXObject.createXObject(
            (COSStream) obj.getObject());

    File inputFile = new File("C:\\temp\\SIGNATURE.jpg");
    PDXObjectImage newImage = new PDJpeg(
        doc, new FileInputStream(inputFile));
    imageInPdf.getCOSStream().replaceWithStream(newImage.getCOSStream());

Thanks,
Stephen

Re: Replacing an image in a PDF file using PDFBox

Posted by Tilman Hausherr <TH...@t-online.de>.
Hi,

You could get the resources from the page with getResources(), then do 
getXObjects() to get the XObjects map, then replace your image with the 
new one. You need to know the key of your image, of course.

However:
- I haven't tested this
- I assume you're using 1.8.9
- It will work only if your image is part of the main content stream, 
not if the image is in an XForm (i.e. deeper nested)
- This does not handle a real electronic signature (and if your document 
is signed, then the signature will not be valid anymore)
- If the new image has a different size than the old one, more troubles 
will be coming
- Don't use this for evil purposes :-)

Good luck... come back if you need more help.

Tilman

Am 08.05.2015 um 02:06 schrieb Stephen Haggai:
> Hi,
>
> I am trying to replace an image in a PDF file using PDFBox and I am unable
> to find any examples. The only example that I found on
> http://stackoverflow.com/questions/17423665/replace-image-in-pdf-with-another-image-pdf-box
> uses COSStream's replaceWithStream(COSStream stream) that has been
> deprecated. Are there any alternatives to this method or is there another
> process that I can use.
>
> private static void changeImage(COSObject obj, PDDocument doc) {
>
>      PDXObjectImage imageInPdf =
>          (PDXObjectImage) PDXObject.createXObject(
>              (COSStream) obj.getObject());
>
>      File inputFile = new File("C:\\temp\\SIGNATURE.jpg");
>      PDXObjectImage newImage = new PDJpeg(
>          doc, new FileInputStream(inputFile));
>      imageInPdf.getCOSStream().replaceWithStream(newImage.getCOSStream());
>
> Thanks,
> Stephen
>


---------------------------------------------------------------------
To unsubscribe, e-mail: users-unsubscribe@pdfbox.apache.org
For additional commands, e-mail: users-help@pdfbox.apache.org