0

I am Currently using ICEPDF to render PDF files and display it in my java Swing application (in Internal Frame). Now I want to add crop features to my Java application. Like, if I click a button, I can drag required portion of PDF and save it as Image in my local storage.

Is there an efficient way to crop out PDF and save as image (.JPG) via java program?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Nesh
  • 134
  • 9

1 Answers1

2

Ghost4J library (http://ghost4j.sourceforge.net), is your best option:

3 simple step:

  1. Load PDF files:

    PDFDocument document = new PDFDocument();
    document.load(new File("test.pdf"));
    
  2. Create the renderer:

    SimpleRenderer renderer = new SimpleRenderer();
    
    // set resolution (in DPI)
    renderer.setResolution(600);
    
  3. Render:

    List<Image> images = renderer.render(document);
    

Then you can do what you want with your image objects, for example, you can write them as JPG like this:

for (int i = 0; i < images.size(); i++) {
    ImageIO.write((RenderedImage) images.get(i), "jpg", new File((i + 1) + ".jpg"));
}

Ghost4J uses the native Ghostscript API so you need to have a Ghostscript installed.

EDIT: investigating a bit, if you convert the PDF to Image you won't have much problem to crop them:

BufferedImage is a(n) Image, so the implicit cast that you're doing in the second line is able to be compiled directly. If you knew an Image was really a BufferedImage, you would have to cast it explicitly like so:

Image image = ImageIO.read(new File(file));
BufferedImage buffered = (BufferedImage) image;

Then you can crop it with BufferedImage::getSubimage method:

private BufferedImage cropImage(BufferedImage src, Rectangle rect) {
  BufferedImage dest = src.getSubimage(rect.x, rect.y, rect.width, rect.height);
  return dest; 
}
Community
  • 1
  • 1
Jordi Castilla
  • 26,609
  • 8
  • 70
  • 109