Clipping pages in an existing PDF

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

30th October 2015
admin-marketing

Switch code for this example

ClipPdf.java
  1. /**
  2.  * Example written by Bruno Lowagie in answer to:
  3.  * http://stackoverflow.com/questions/26773942/itext-crop-out-a-part-of-pdf-file
  4.  */
  5. package sandbox.stamper;
  6.  
  7. import com.itextpdf.text.DocumentException;
  8. import com.itextpdf.text.pdf.PdfArray;
  9. import com.itextpdf.text.pdf.PdfDictionary;
  10. import com.itextpdf.text.pdf.PdfName;
  11. import com.itextpdf.text.pdf.PdfReader;
  12. import com.itextpdf.text.pdf.PdfStamper;
  13.  
  14. import java.io.File;
  15. import java.io.FileOutputStream;
  16. import java.io.IOException;
  17. import java.util.Locale;
  18.  
  19. import sandbox.WrapToTest;
  20.  
  21. @WrapToTest
  22. public class ClipPdf {
  23.  
  24.     public static final String SRC = "resources/pdfs/hero.pdf";
  25.     public static final String DEST = "results/stamper/hero_clipped.pdf";
  26.  
  27.     public static void main(String[] args) throws IOException, DocumentException {
  28.         File file = new File(DEST);
  29.         file.getParentFile().mkdirs();
  30.         new ClipPdf().manipulatePdf(SRC, DEST);
  31.     }
  32.  
  33.     public void manipulatePdf(String src, String dest) throws IOException, DocumentException {
  34.         PdfReader reader = new PdfReader(src);
  35.         PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest));
  36.         int n = reader.getNumberOfPages();
  37.         PdfDictionary page;
  38.         PdfArray media;
  39.         for (int p = 1; p
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