How to update a PDF without creating a new PDF?

As documented in my book iText in Action, you can’t read a file and write to it simultaneously. Think of how 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 too:

  • read the original file with PdfReader,
  • create a temporary file for PdfStamper, and when you’re done,
  • replace the original file with the temporary file.

Or:

  • read the original file into a byte[],
  • create PdfReader with this byte[], and
  • use the path to the original file for PdfStamper.

This second option is more dangerous, as you’ll lose the original file if you do something that causes an exception in PdfStamper.

Leave a Comment