Shrink a PDF document in size - Apache PDFBox example

In this example we are taking a large PDF document, then reducing the size by simply converting each page to an image and then adding them back as pages to generate a new PDF document. This is helpful when you need to send them to a printer with specific page size.

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.common.PDRectangle;
import org.apache.pdfbox.pdmodel.graphics.image.JPEGFactory;
import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject;
import org.apache.pdfbox.rendering.ImageType;
import org.apache.pdfbox.rendering.PDFRenderer;


public class ShrinkPDF {

 public ShrinkPDF() {

 }

 public static void main(String[] args) {

  try {

   PDDocument pdDocument = new PDDocument();
   PDDocument oDocument = PDDocument.load(new File("docs/in.pdf"));
   PDFRenderer pdfRenderer = new PDFRenderer(oDocument);
   int numberOfPages = oDocument.getNumberOfPages();
   PDPage page = null;

   for (int i = 0; i < numberOfPages; i++) {
    page = new PDPage(PDRectangle.LETTER);
    BufferedImage bim = pdfRenderer.renderImageWithDPI(i, 300, ImageType.RGB);
    PDImageXObject pdImage = JPEGFactory.createFromImage(pdDocument, bim);
    PDPageContentStream contentStream = new PDPageContentStream(pdDocument, page);
    float newHeight = PDRectangle.LETTER.getHeight();
    float newWidth = PDRectangle.LETTER.getWidth();
    contentStream.drawImage(pdImage, 0, 0, newWidth, newHeight);
    contentStream.close();

    pdDocument.addPage(page);
   }

   pdDocument.save("docs/out.pdf");
   pdDocument.close();

  } catch (IOException e) {
   e.printStackTrace();
  }


 }

}

No comments:

Post a Comment

NO JUNK, Please try to keep this clean and related to the topic at hand.
Comments are for users to ask questions, collaborate or improve on existing.