How to update a PDF without creating a new PDF?

I need to change the value of a field in an existing PDF file. I am using PdfReader, PdfStamper and AcroFields and that's working fine. But, in doing so, it is required to create a new PDF and I wou

I need to change the value of a field in an existing PDF file. I am using PdfReader, PdfStamper and AcroFields and that's working fine. But, in doing so, it is required to create a new PDF and I would like the change to be reflected in the existing PDF itself. If I am setting the destination filename to be the same as the original filename, then my application fails.

Posted on StackOverflow on Apr 18, 2013 by tk2013

You can't read a file and write to it simultaneously. Think of how Microsoft Word works: you can't open a Word document and write directly to it. Word always creates a temporary file, writes the changes to it, then replaces the original file with it, and then throws away the temporary file.

You can do that this way:

  • read the original file with PdfReader;

  • create a PdfWriter instance for the resulting PDF;

  • create a PdfDocument to manipulate the original file

This example is written using iText 7:

PdfReader reader = new PdfReader(src);
PdfWriter writer = new PdfWriter(dest);
PdfDocument pdfDoc = new PdfDocument(reader, writer);
//manipulate pdf…
pdfDoc.close();

Click this link if you want to see how to answer this question in iText 5.



Ready to use iText?

Try our iText 7 Library and add-ons FREE for 30 days. Test your proof of concept, and see if our solution is right for you.

Get my FREE trial
Contact

Still have questions? 

We're happy to answer your questions. Reach out to us and we'll get back to you shortly.

Contact us
Stay updated

Join 11,000+ subscribers and become an iText PDF expert by staying up to date with our new products, updates, tips, technical solutions and happenings.

Subscribe Now