PDF to JPGs with Java
August 27, 2013
I have a requirement to take a PDF, convert it to JPG and then show these on a web page. This can be done using Ghost4J and Ghostscript. Ghost4J is a Java API onto the Ghostscript functionality.
This can be done with the following Java code, which replies on Ghost4J (and its dependencies) and GhostScript being available on the machine.
After installing Ghostscript, I had to add the bin directory to my PATH
.
GhostscriptRevision lRevision = Ghostscript.getRevision(); System.out.println(lRevision.getCopyright()); System.out.println(lRevision.getNumber()); System.out.println(lRevision.getProduct()); System.out.println(lRevision.getRevisionDate()); // load PDF document PDFDocument lDocument = new PDFDocument(); lDocument.load(new File("/tmp/DashboardApiSpec.pdf")); // create renderer SimpleRenderer lRenderer = new SimpleRenderer(); // set resolution (in DPI) lRenderer.setResolution(300); // render as images List<Image> lImages = lRenderer.render(lDocument); Iterator<Image> lImageIterator = lImages.iterator(); int lFilename = 0; while (lImageIterator.hasNext()) { Image lImage = lImageIterator.next(); BufferedImage lBufferedImage = new BufferedImage(lImage.getWidth(null), lImage.getHeight(null), BufferedImage.TYPE_INT_RGB); Graphics2D lGraphics2D = lBufferedImage.createGraphics(); lGraphics2D.drawImage(lImage, 0, 0, null); lGraphics2D.dispose(); String lFilePath = "/tmp/myImage" + lFilename + ".jpg"; System.out.println(lFilePath); ImageIO.write(lBufferedImage, "jpg", new File(lFilePath)); lFilename++; }
Signed PDFs
This approach will also work with signed PDFs, as long as you supply a correct version of the Bouncy Castle JCE library. Ghost4J shipped with iText 2.1.7, and this worked with bcprov-jdk15-141.jar
.