Replacing PDF objects

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

31st May 2016
admin-marketing

Switch code for this example

ReplaceStream.java
  1. /*
  2.  
  3.     This file is part of the iText (R) project.
  4.     Copyright (c) 1998-2016 iText Group NV
  5.  
  6. */
  7.  
  8. /**
  9.  * Example written by Bruno Lowagie in answer to:
  10.  * http://stackoverflow.com/questions/21617218/itext-or-itextsharp-rudimentary-text-edit
  11.  *
  12.  * This is only a partial answer. It's a quick and dirty method showing how to
  13.  * change a stream inside a PDF. Obviously, you'll have to detect words that are
  14.  * stored in Form XObjects too, and you can seriously screw up the layout when
  15.  * you manipulate the content stream as is done in this example.
  16.  */
  17. package com.itextpdf.samples.sandbox.stamper;
  18.  
  19. import com.itextpdf.kernel.pdf.*;
  20. import com.itextpdf.samples.GenericTest;
  21. import com.itextpdf.test.annotations.type.SampleTest;
  22.  
  23. import org.junit.experimental.categories.Category;
  24.  
  25. import java.io.File;
  26.  
  27. @Category(SampleTest.class)
  28. public class ReplaceStream extends GenericTest {
  29.     public static final String DEST = "./target/test/resources/sandbox/stamper/replace_stream.pdf";
  30.     public static final String SRC = "./src/test/resources/pdfs/hello.pdf";
  31.  
  32.     public static void main(String[] args) throws Exception {
  33.         File file = new File(DEST);
  34.         file.getParentFile().mkdirs();
  35.         new ReplaceStream().manipulatePdf(DEST);
  36.     }
  37.  
  38.     @Override
  39.     protected void manipulatePdf(String dest) throws Exception {
  40.         PdfDocument pdfDoc = new PdfDocument(new PdfReader(SRC), new PdfWriter(DEST));
  41.         PdfPage page = pdfDoc.getFirstPage();
  42.         PdfDictionary dict = page.getPdfObject();
  43.         PdfObject object = dict.get(PdfName.Contents);
  44.         if (object instanceof PdfStream) {
  45.             PdfStream stream = (PdfStream) object;
  46.             byte[] data = stream.getBytes();
  47.             stream.setData(new String(data).replace("Hello World", "HELLO WORLD").getBytes("UTF-8"));
  48.         }
  49.         pdfDoc.close();
  50.     }
  51. }
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