java pdf pdf-generation pdfbox ghost4j

java - Convertir un archivo PDF a imagen



pdf-generation pdfbox (7)

La forma de usar PDFBox es una buena manera de evitar los enlaces nativos. Intente usar el PDFImageWriter del PDFBox, hice lo mismo en unas pocas líneas y funcionó perfectamente. Tienes que extraer el PDFDocument y usar el escritor con él.

PDFImageWriter.write(doc, "png", null, , Integer.MAX_VALUE, "picture");

Para todas las páginas.

PDFImageWriter.write(doc, "png", null, 0, 0, "picture");

Ver: PDFImageWriter Javadoc

Quería convertir documento PDF en imagen. Yo estaba usando Ghost4j.

Problema: Ghost4J necesita el archivo gsdll32.dll en tiempo de ejecución, y no quiero usar el archivo dll.

Pregunta 1: ¿hay alguna manera, en ghost4j para convertir la imagen sin la dll?

Pregunta 2: Encontré la solución en la API de PDFBox. org.apache.pdfbox.pdmodel.PDPagep have method convertToImage () `que convierte la página PDF al formato de imagen.

PDDocument doc = PDDocument.load(new File("/document.pdf")); List<PDPage>pages = doc.getDocumentCatalog().getAllPages(); PDPage page = pages.get(0); BufferedImage image =page.convertToImage(); File outputfile = new File("/image.png"); ImageIO.write(image, "png", outputfile); doc.close();

Sólo tengo texto en el documento PDF. y tengo esa excepción cuando ejecuto este código:

Aug 12, 2013 6:00:24 PM org.apache.pdfbox.util.PDFStreamEngine processOperator INFO: unsupported/disabled operation: BDC Exception in thread "main" java.lang.ExceptionInInitializerError at org.apache.pdfbox.pdmodel.font.PDTrueTypeFont.getawtFont(PDTrueTypeFont.java:481) at org.apache.pdfbox.pdmodel.font.PDSimpleFont.drawString(PDSimpleFont.java:109) at org.apache.pdfbox.pdfviewer.PageDrawer.processTextPosition(PageDrawer.java:235) at org.apache.pdfbox.util.PDFStreamEngine.processEncodedText(PDFStreamEngine.java:496) at org.apache.pdfbox.util.operator.ShowTextGlyph.process(ShowTextGlyph.java:62) at org.apache.pdfbox.util.PDFStreamEngine.processOperator(PDFStreamEngine.java:554) at org.apache.pdfbox.util.PDFStreamEngine.processSubStream(PDFStreamEngine.java:268) at org.apache.pdfbox.util.PDFStreamEngine.processSubStream(PDFStreamEngine.java:235) at org.apache.pdfbox.util.PDFStreamEngine.processStream(PDFStreamEngine.java:215) at org.apache.pdfbox.pdfviewer.PageDrawer.drawPage(PageDrawer.java:125) at org.apache.pdfbox.pdmodel.PDPage.convertToImage(PDPage.java:781) at org.apache.pdfbox.pdmodel.PDPage.convertToImage(PDPage.java:712) at ge.eid.esignature.adessa.pades.sign.PDFtoImage.main(PDFtoImage.java:25) Caused by: java.lang.IllegalArgumentException at java.nio.Buffer.position(Buffer.java:216) at sun.font.TrueTypeFont.lookupName(TrueTypeFont.java:1153) at sun.font.TrueTypeFont.getPostscriptName(TrueTypeFont.java:1205) at java.awt.Font.getPSName(Font.java:1156) at org.apache.pdfbox.pdmodel.font.FontManager.loadFonts(FontManager.java:101) at org.apache.pdfbox.pdmodel.font.FontManager.<clinit>(FontManager.java:53) ... 13 more


Por el error:

org.apache.pdfbox.util.PDFStreamEngine processOperator INFO: operación no admitida / deshabilitada

Debe incluir el tarro de fontbox-1.7.1 en la ruta de clase, a excepción del jar de Apache pdfbox, que solucionará su problema ya que PDFBox utiliza de forma interna fontbox-1.7.1


Probablemente haya intentado convertir un archivo PDF dañado. Tengo los mismos errores cuando el archivo PDF contiene secuencias JPXEncoded.


Puede convertir fácilmente PDF en imagen usando PDFBox . El método renderImageWithDPI de la clase PDFRenderer de PDFBox se utiliza para convertir pdf a imagen.

PDDocument doc=PDDocument.load(new File("filepath/sample.pdf")); PDFRenderer pdfRenderer = new PDFRenderer(doc); BufferedImage bffim = pdfRenderer.renderImageWithDPI(pageNo, 300, ImageType.RGB); String fileName = "image-" + page + ".png"; ImageIOUtil.writeImage(bim, fileName, 300);


Puede convertir fácilmente las páginas del archivo 04-Request-Headers.pdf al formato de imagen.

Convierta todas las páginas pdf en formato de imagen en Java usando PDF Box.

Jar requerido pdfbox-1.8.3.jar

o la dependencia maven

<dependency> <groupId>org.apache.pdfbox</groupId> <artifactId>pdfbox</artifactId> <version>1.8.3</version> </dependency>

Aquí está la solución:

package com.pdf.pdfbox.examples; import java.awt.image.BufferedImage; import java.io.File; import java.util.List; import javax.imageio.ImageIO; import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.pdmodel.PDPage; @SuppressWarnings("unchecked") public class ConvertPDFPagesToImages { public static void main(String[] args) { try { String sourceDir = "C:/Documents/04-Request-Headers.pdf"; // Pdf files are read from this folder String destinationDir = "C:/Documents/Converted_PdfFiles_to_Image/"; // converted images from pdf document are saved here File sourceFile = new File(sourceDir); File destinationFile = new File(destinationDir); if (!destinationFile.exists()) { destinationFile.mkdir(); System.out.println("Folder Created -> "+ destinationFile.getAbsolutePath()); } if (sourceFile.exists()) { System.out.println("Images copied to Folder: "+ destinationFile.getName()); PDDocument document = PDDocument.load(sourceDir); List<PDPage> list = document.getDocumentCatalog().getAllPages(); System.out.println("Total files to be converted -> "+ list.size()); String fileName = sourceFile.getName().replace(".pdf", ""); int pageNumber = 1; for (PDPage page : list) { BufferedImage image = page.convertToImage(); File outputfile = new File(destinationDir + fileName +"_"+ pageNumber +".png"); System.out.println("Image Created -> "+ outputfile.getName()); ImageIO.write(image, "png", outputfile); pageNumber++; } document.close(); System.out.println("Converted Images are saved at -> "+ destinationFile.getAbsolutePath()); } else { System.err.println(sourceFile.getName() +" File not exists"); } } catch (Exception e) { e.printStackTrace(); } } }

Posibles conversiones de imagen a formato jpg, jpeg, png, bmp, gif .

Nota: mencioné los formatos de imagen utilizados principalmente.

ImageIO.write(image , "jpg", new File( destinationDir +fileName+"_"+pageNumber+".jpg" )); ImageIO.write(image , "jpeg", new File( destinationDir +fileName+"_"+pageNumber+".jpeg" )); ImageIO.write(image , "png", new File( destinationDir +fileName+"_"+pageNumber+".png" )); ImageIO.write(image , "bmp", new File( destinationDir +fileName+"_"+pageNumber+".bmp" )); ImageIO.write(image , "gif", new File( destinationDir +fileName+"_"+pageNumber+".gif" ));

Salida de consola:

Images copied to Folder: Converted_PdfFiles_to_Image Total files to be converted -> 13 Aug 06, 2014 1:35:49 PM org.apache.pdfbox.util.PDFStreamEngine processOperator INFO: unsupported/disabled operation: i Image Created -> 04-Request-Headers_1.png Aug 06, 2014 1:35:50 PM org.apache.pdfbox.util.PDFStreamEngine processOperator INFO: unsupported/disabled operation: i Image Created -> 04-Request-Headers_2.png Aug 06, 2014 1:35:51 PM org.apache.pdfbox.util.PDFStreamEngine processOperator INFO: unsupported/disabled operation: i Image Created -> 04-Request-Headers_3.png Aug 06, 2014 1:35:51 PM org.apache.pdfbox.util.PDFStreamEngine processOperator INFO: unsupported/disabled operation: i Image Created -> 04-Request-Headers_4.png Aug 06, 2014 1:35:52 PM org.apache.pdfbox.util.PDFStreamEngine processOperator INFO: unsupported/disabled operation: i Image Created -> 04-Request-Headers_5.png Aug 06, 2014 1:35:52 PM org.apache.pdfbox.util.PDFStreamEngine processOperator INFO: unsupported/disabled operation: i Image Created -> 04-Request-Headers_6.png Aug 06, 2014 1:35:53 PM org.apache.pdfbox.util.PDFStreamEngine processOperator INFO: unsupported/disabled operation: i Image Created -> 04-Request-Headers_7.png Aug 06, 2014 1:35:53 PM org.apache.pdfbox.util.PDFStreamEngine processOperator INFO: unsupported/disabled operation: i Image Created -> 04-Request-Headers_8.png Aug 06, 2014 1:35:54 PM org.apache.pdfbox.util.PDFStreamEngine processOperator INFO: unsupported/disabled operation: i Image Created -> 04-Request-Headers_9.png Aug 06, 2014 1:35:54 PM org.apache.pdfbox.util.PDFStreamEngine processOperator INFO: unsupported/disabled operation: i Image Created -> 04-Request-Headers_10.png Aug 06, 2014 1:35:54 PM org.apache.pdfbox.util.PDFStreamEngine processOperator INFO: unsupported/disabled operation: i Image Created -> 04-Request-Headers_11.png Aug 06, 2014 1:35:55 PM org.apache.pdfbox.util.PDFStreamEngine processOperator INFO: unsupported/disabled operation: i Image Created -> 04-Request-Headers_12.png Aug 06, 2014 1:35:55 PM org.apache.pdfbox.util.PDFStreamEngine processOperator INFO: unsupported/disabled operation: i Image Created -> 04-Request-Headers_13.png Converted Images are saved at -> C:/Documents/Converted_PdfFiles_to_Image


Puede intentar usar NonSequentialParser para evitar errores con algunos archivos PDF (con actualizaciones incrementales):

PDDocument doc = PDDocument.loadNonSeq (nuevo archivo ("/ document.pdf"));


try { PDDocument document = PDDocument.load(PdfInfo.getPDFWAY()); if (document.isEncrypted()) { document.decrypt(PdfInfo.getPASSWORD()); } if ("bilevel".equalsIgnoreCase(PdfInfo.getCOLOR())) { PdfInfo.setIMAGETYPE( BufferedImage.TYPE_BYTE_BINARY); } else if ("indexed".equalsIgnoreCase(PdfInfo.getCOLOR())) { PdfInfo.setIMAGETYPE(BufferedImage.TYPE_BYTE_INDEXED); } else if ("gray".equalsIgnoreCase(PdfInfo.getCOLOR())) { PdfInfo.setIMAGETYPE(BufferedImage.TYPE_BYTE_GRAY); } else if ("rgb".equalsIgnoreCase(PdfInfo.getCOLOR())) { PdfInfo.setIMAGETYPE(BufferedImage.TYPE_INT_RGB); } else if ("rgba".equalsIgnoreCase(PdfInfo.getCOLOR())) { PdfInfo.setIMAGETYPE(BufferedImage.TYPE_INT_ARGB); } else { System.exit(2); } PDFImageWriter imageWriter = new PDFImageWriter(); boolean success = imageWriter.writeImage(document, PdfInfo.getIMAGE_FORMAT(),PdfInfo.getPASSWORD(), PdfInfo.getSTART_PAGE(),PdfInfo.getEND_PAGE(),PdfInfo.getOUTPUT_PREFIX(),PdfInfo.getIMAGETYPE(),PdfInfo.getRESOLUTION()); if (!success) { System.exit(1); } document.close(); } catch (IOException | CryptographyException | InvalidPasswordException ex) { Logger.getLogger(PdfToImae.class.getName()).log(Level.SEVERE, null, ex); } public class PdfInfo { private static String PDFWAY; private static String OUTPUT_PREFIX; private static String PASSWORD; private static int START_PAGE=1; private static int END_PAGE=Integer.MAX_VALUE; private static String IMAGE_FORMAT="jpg"; private static String COLOR="rgb"; private static int RESOLUTION=256; private static int IMAGETYPE=24; private static String filename; private static String filePath=""; }