Replacing PDF objects

This is a code example of iText PDF, discover more.

8th November 2015
admin-marketing

Switch code for this example

ReplaceStream.java
  1. /**
  2.  * Example written by Bruno Lowagie in answer to:
  3.  * http://stackoverflow.com/questions/21617218/itext-or-itextsharp-rudimentary-text-edit
  4.  *
  5.  * This is only a partial answer. It's a quick and dirty method showing how to
  6.  * change a stream inside a PDF. Obviously, you'll have to detect words that are
  7.  * stored in Form XObjects too, and you can seriously screw up the layout when
  8.  * you manipulate the content stream as is done in this example.
  9.  */
  10. package sandbox.stamper;
  11.  
  12. import com.itextpdf.text.DocumentException;
  13. import com.itextpdf.text.pdf.PRStream;
  14. import com.itextpdf.text.pdf.PdfDictionary;
  15. import com.itextpdf.text.pdf.PdfName;
  16. import com.itextpdf.text.pdf.PdfObject;
  17. import com.itextpdf.text.pdf.PdfReader;
  18. import com.itextpdf.text.pdf.PdfStamper;
  19.  
  20. import java.io.File;
  21. import java.io.FileOutputStream;
  22. import java.io.IOException;
  23.  
  24. import sandbox.WrapToTest;
  25.  
  26. @WrapToTest
  27. public class ReplaceStream {
  28.     public static final String SRC = "resources/pdfs/hello.pdf";
  29.     public static final String DEST = "results/stamper/hello_changed.pdf";
  30.  
  31.     public static void main(String[] args) throws IOException, DocumentException {
  32.         File file = new File(DEST);
  33.         file.getParentFile().mkdirs();
  34.         new ReplaceStream().manipulatePdf(SRC, DEST);
  35.     }
  36.  
  37.     public void manipulatePdf(String src, String dest) throws IOException, DocumentException {
  38.         PdfReader reader = new PdfReader(src);
  39.         PdfDictionary dict = reader.getPageN(1);
  40.         PdfObject object = dict.getDirectObject(PdfName.CONTENTS);
  41.         if (object instanceof PRStream) {
  42.             PRStream stream = (PRStream)object;
  43.             byte[] data = PdfReader.getStreamBytes(stream);
  44.             stream.setData(new String(data).replace("Hello World", "HELLO WORLD").getBytes());
  45.         }
  46.         PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest));
  47.         stamper.close();
  48.         reader.close();
  49.     }
  50. }
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