List of usage examples for org.apache.pdfbox.rendering PDFRenderer renderImageWithDPI
public BufferedImage renderImageWithDPI(int pageIndex, float dpi, ImageType imageType) throws IOException
From source file:ddf.catalog.transformer.input.pdf.PdfThumbnailGeneratorImpl.java
License:Open Source License
@Override public Optional<byte[]> apply(PDDocument pdfDocument) throws IOException { PDFRenderer pdfRenderer = new PDFRenderer(pdfDocument); if (pdfDocument.getNumberOfPages() < 1) { return Optional.empty(); }//w w w .ja v a 2 s .c om BufferedImage image = pdfRenderer.renderImageWithDPI(0, RESOLUTION_DPI, ImageType.RGB); int largestDimension = Math.max(image.getHeight(), image.getWidth()); float scalingFactor = IMAGE_HEIGHTWIDTH / largestDimension; int scaledHeight = (int) (image.getHeight() * scalingFactor); int scaledWidth = (int) (image.getWidth() * scalingFactor); BufferedImage scaledImage = new BufferedImage(scaledWidth, scaledHeight, BufferedImage.TYPE_INT_RGB); Graphics2D graphics = scaledImage.createGraphics(); graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); graphics.drawImage(image, 0, 0, scaledWidth, scaledHeight, null); graphics.dispose(); try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) { ImageIOUtil.writeImage(scaledImage, FORMAT_NAME, outputStream, RESOLUTION_DPI, IMAGE_QUALITY); return Optional.of(outputStream.toByteArray()); } }
From source file:es.rickyepoderi.pdfimages.Converter.java
License:Open Source License
/** * Method that converts a PDF file in a series of images. * /*from w w w. j a v a 2 s . c o m*/ * @param pdfFile The PDF file to read * @param prefix The prefix of the images to write * @param imgFormat The image format ("jpg", "png",...) used by ImageIO * @param dpi The DPI of the images to render pages * @param type The type of the image (RGB, GREY,...) * @throws IOException Some error generating the images */ public void pdf2Images(File pdfFile, String prefix, String suffix, int dpi, ImageType type) throws IOException { PDDocument document = PDDocument.load(pdfFile); PDFRenderer pdfRenderer = new PDFRenderer(document); int pad = (int) Math.ceil(Math.log10(document.getNumberOfPages())); if (pad == 0) { pad = 1; } String format = String.format("%s.%%0%dd.%s", prefix, pad, suffix); for (int i = 0; i < document.getNumberOfPages(); i++) { BufferedImage image = pdfRenderer.renderImageWithDPI(i, dpi, type); ImageIO.write(image, suffix, new File(String.format(format, i))); } }
From source file:idp.pdf_converter.java
public static void pdf_converter(File file) throws IOException { PDDocument document = PDDocument.load(file); PDFRenderer pdfRenderer = new PDFRenderer(document); String path = System.getProperty("user.dir") + "\\src\\main\\temp\\images\\"; for (int page = 0; page < document.getNumberOfPages(); ++page) { BufferedImage bim = pdfRenderer.renderImageWithDPI(page, 300, ImageType.GRAY); ImageIOUtil.writeImage(bim, path + file.getName() + "-" + (page + 1) + ".png", 300); }//from w w w . ja v a 2 s . c o m document.close(); }
From source file:jgnash.report.pdf.Report.java
License:Open Source License
/** * Renders the PDF report to a raster image * * @param pageIndex page index//from w w w. ja v a2 s . c om * @param dpi DPI for the image * @return the image * @throws IOException IO exception */ public BufferedImage renderImage(final int pageIndex, final int dpi) throws IOException { final PDFRenderer pdfRenderer = new PDFRenderer(pdfDocument); return pdfRenderer.renderImageWithDPI(pageIndex, dpi, ImageType.RGB); }
From source file:merge_split.MergeSplit.java
License:Apache License
private void ConvertButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ConvertButtonActionPerformed PDDocument document = null;/*from w w w. ja v a 2 s . c o m*/ try { document = PDDocument.load(new File((String) ConvertFileField.getText()), convertcode); } catch (IOException ex) { JOptionPane.showMessageDialog(null, "Problem opening pdf.", "Problem opening pdf", JOptionPane.WARNING_MESSAGE); } TreeSet tree = findPages((String) ConvertPagesField.getText()); PDFRenderer pdfRenderer = new PDFRenderer(document); for (int page = 0; page < document.getNumberOfPages(); ++page) { BufferedImage bim = null; try { bim = pdfRenderer.renderImageWithDPI(page, 300, ImageType.RGB); } catch (IOException ex) { JOptionPane.showMessageDialog(null, "Problem rendering image.", "Problem rendering image", JOptionPane.WARNING_MESSAGE); } // suffix in filename will be used as the file format String destination = ConvertDestinationField.getText() + "\\" + ConvertNameField.getText(); String image = ".png"; if (pngbutton.isSelected()) { image = ".png"; } else if (bmpbutton.isSelected()) { image = ".bmp"; } else if (gifbutton.isSelected()) { image = ".gif"; } else if (jpgbutton.isSelected()) { image = ".jpg"; } try { if (tree.contains(page + 1)) { ImageIOUtil.writeImage(bim, destination + "-" + (page + 1) + image, 300); } } catch (IOException ex) { JOptionPane.showMessageDialog(null, "Problem output image.", "Problem output image", JOptionPane.WARNING_MESSAGE); java.util.logging.Logger.getLogger(MergeSplit.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } } try { document.close(); } catch (IOException ex) { Logger.getLogger(MergeSplit.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:model.util.pdf.PDFUtils.java
License:Apache License
/** * Infamous main method./*w ww . j av a 2 s. co m*/ * Adapted by Julius Huelsmann. * * @author Ben Litchfield * * @param args Command line arguments, should be one and a reference to a file. * * @throws IOException If there is an error parsing the document. */ public static BufferedImage pdf2image(final String[] _parameters) throws IOException { // suppress the Dock icon on OS X if called from outside // the paint - project. System.setProperty("apple.awt.UIElement", "true"); String password = ""; String pdfFile = null; String outputPrefix = null; String imageFormat = "jpg"; int startPage = 1; int endPage = Integer.MAX_VALUE; String color = "rgb"; int dpi; float cropBoxLowerLeftX = 0; float cropBoxLowerLeftY = 0; float cropBoxUpperRightX = 0; float cropBoxUpperRightY = 0; boolean showTime = false; try { dpi = Toolkit.getDefaultToolkit().getScreenResolution(); } catch (HeadlessException e) { dpi = 96; } for (int i = 0; i < _parameters.length; i++) { if (_parameters[i].equals(PASSWORD)) { i++; if (i >= _parameters.length) { usage(); } password = _parameters[i]; } else if (_parameters[i].equals(START_PAGE)) { i++; if (i >= _parameters.length) { usage(); } startPage = Integer.parseInt(_parameters[i]); } else if (_parameters[i].equals(END_PAGE)) { i++; if (i >= _parameters.length) { usage(); } endPage = Integer.parseInt(_parameters[i]); } else if (_parameters[i].equals(PAGE)) { i++; if (i >= _parameters.length) { usage(); } startPage = Integer.parseInt(_parameters[i]); endPage = Integer.parseInt(_parameters[i]); } else if (_parameters[i].equals(IMAGE_TYPE) || _parameters[i].equals(FORMAT)) { i++; imageFormat = _parameters[i]; } else if (_parameters[i].equals(OUTPUT_PREFIX) || _parameters[i].equals(PREFIX)) { i++; outputPrefix = _parameters[i]; } else if (_parameters[i].equals(COLOR)) { i++; color = _parameters[i]; } else if (_parameters[i].equals(RESOLUTION) || _parameters[i].equals(DPI)) { i++; dpi = Integer.parseInt(_parameters[i]); } else if (_parameters[i].equals(CROPBOX)) { i++; cropBoxLowerLeftX = Float.valueOf(_parameters[i]); i++; cropBoxLowerLeftY = Float.valueOf(_parameters[i]); i++; cropBoxUpperRightX = Float.valueOf(_parameters[i]); i++; cropBoxUpperRightY = Float.valueOf(_parameters[i]); } else if (_parameters[i].equals(TIME)) { showTime = true; } else { if (pdfFile == null) { pdfFile = _parameters[i]; } } } if (pdfFile == null) { usage(); } else { if (outputPrefix == null) { outputPrefix = pdfFile.substring(0, pdfFile.lastIndexOf('.')); } PDDocument document = null; try { document = PDDocument.load(new File(pdfFile), password); ImageType imageType = null; if ("bilevel".equalsIgnoreCase(color)) { imageType = ImageType.BINARY; } else if ("gray".equalsIgnoreCase(color)) { imageType = ImageType.GRAY; } else if ("rgb".equalsIgnoreCase(color)) { imageType = ImageType.RGB; } else if ("rgba".equalsIgnoreCase(color)) { imageType = ImageType.ARGB; } if (imageType == null) { System.err.println("Error: Invalid color."); System.exit(2); } //if a CropBox has been specified, update the CropBox: //changeCropBoxes(PDDocument document,float a, float b, float c,float d) if (cropBoxLowerLeftX != 0 || cropBoxLowerLeftY != 0 || cropBoxUpperRightX != 0 || cropBoxUpperRightY != 0) { changeCropBox(document, cropBoxLowerLeftX, cropBoxLowerLeftY, cropBoxUpperRightX, cropBoxUpperRightY); } long startTime = System.nanoTime(); // render the pages boolean success = true; endPage = Math.min(endPage, document.getNumberOfPages()); PDFRenderer renderer = new PDFRenderer(document); for (int i = startPage - 1; i < endPage;) { BufferedImage image = renderer.renderImageWithDPI(i, dpi, imageType); String fileName = outputPrefix + (i + 1) + "." + imageFormat; success &= ImageIOUtil.writeImage(image, fileName, dpi); return image; } // performance stats long endTime = System.nanoTime(); long duration = endTime - startTime; int count = 1 + endPage - startPage; if (showTime) { System.err.printf("Rendered %d page%s in %dms\n", count, count == 1 ? "" : "s", duration / 1000000); } if (!success) { System.err.println("Error: no writer found for image format '" + imageFormat + "'"); System.exit(1); } } finally { if (document != null) { document.close(); } } return null; } return null; }
From source file:model.util.pdf.PDFUtils.java
License:Apache License
public static BufferedImage pdf2image(PDDocument _document, int _pageNumber) { int dpi = 0;//from w ww . j av a 2 s.c om try { dpi = Toolkit.getDefaultToolkit().getScreenResolution(); dpi = 130; } catch (HeadlessException e) { dpi = 96; dpi = 130; } PDFRenderer renderer = new PDFRenderer(_document); BufferedImage image; try { image = renderer.renderImageWithDPI(_pageNumber, dpi, ImageType.RGB); return image; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); return null; } }
From source file:net.betzel.fop.pdf.viewer.FXMLController.java
License:Apache License
private void createImages(FileStreamSources fileStreamSources) { if (Platform.isFxApplicationThread()) { final Task<List<BufferedImage>> createImagesTask = new Task<List<BufferedImage>>() { @Override//from www . ja v a 2 s . c o m protected List<BufferedImage> call() throws Exception { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); List<BufferedImage> bufferedImages = new ArrayList(); FOUserAgent userAgent = fopFactory.newFOUserAgent(); userAgent.getEventBroadcaster().addEventListener(fopEventListener); Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, userAgent, byteArrayOutputStream); Transformer transformer = transformerFactory.newTransformer(fileStreamSources.getXslSource()); transformer.setErrorListener(xmlTransformErrorListener); Result result = new SAXResult(fop.getDefaultHandler()); transformer.transform(fileStreamSources.getXmlSource(), result); FormattingResults foResults = fop.getResults(); List pageSequences = foResults.getPageSequences(); for (java.util.Iterator it = pageSequences.iterator(); it.hasNext();) { PageSequenceResults pageSequenceResults = (PageSequenceResults) it.next(); logging.appendText("PageSequence " + (String.valueOf(pageSequenceResults.getID()).length() > 0 ? pageSequenceResults.getID() : "<no id>") + " generated " + pageSequenceResults.getPageCount() + " pages.\n"); } try (PDDocument pdDocument = PDDocument .load(new ByteArrayInputStream(byteArrayOutputStream.toByteArray()))) { PDFRenderer pdfRenderer = new PDFRenderer(pdDocument); int pageCounter = 0; for (PDPage pdPage : pdDocument.getPages()) { bufferedImages.add(pdfRenderer.renderImageWithDPI(pageCounter, 150, ImageType.RGB)); pageCounter++; } } return bufferedImages; } }; createImagesTask.setOnSucceeded((WorkerStateEvent event) -> { Platform.runLater(() -> { images.clear(); images.addAll(createImagesTask.getValue()); }); }); createImagesTask.setOnFailed((WorkerStateEvent event) -> { Platform.runLater(() -> { scanProgressDialog.close(); logging.appendText("Error creating images from PDF\n"); reentrantLock.unlock(); images.clear(); }); }); backgoundExecutor.submit(createImagesTask); } }
From source file:org.haplo.component.pdfbox.PDF.java
License:Mozilla Public License
/** * Render the PDF as an image/* ww w. j av a 2 s . com*/ */ public void render(String outFilename, String outFormat, int page, int outWidth, int outHeight) throws IOException { BufferedImage img = null; try { PDPage pdfPage = this.pdf.getPage(page - 1); PDRectangle cropBox = pdfPage.getCropBox(); int pageWidth = (int) cropBox.getWidth(); int pageHeight = (int) cropBox.getHeight(); if (pageHeight <= 0) { pageHeight = 1; } int resolution = (96 * outHeight) / pageHeight; if (resolution < 4) { resolution = 4; } if (resolution > 1000) { resolution = 1000; } if (outHeight < 100 || outWidth < 100) { resolution *= 2; } PDFRenderer pdfRenderer = new PDFRenderer(this.pdf); img = pdfRenderer.renderImageWithDPI(page - 1, resolution, outFormat.equals("png") ? ImageType.ARGB : ImageType.RGB); } catch (Exception e) { Logger.getLogger("org.haplo.app").error("Error rendering PDF: " + e.toString()); throw new RuntimeException("Couldn't render PDF page", e); } // Did it convert? (most likely cause of null return is requested a page which didn't exist) if (img == null) { throw new RuntimeException("Failed to render PDF - did the requested page exist?"); } // Scale the image to the right size BufferedImage original = null; if (img.getWidth() != outWidth || img.getHeight() != outHeight) { original = img; Image scaled = img.getScaledInstance(outWidth, outHeight, Image.SCALE_SMOOTH); img = new BufferedImage(outWidth, outHeight, original.getType()); Graphics2D graphics = img.createGraphics(); graphics.setBackground(Color.WHITE); graphics.clearRect(0, 0, outWidth, outHeight); graphics.drawImage(scaled, 0, 0, null); graphics.dispose(); scaled.flush(); } // Write the image to a file ImageIO.write(img, outFormat, new File(outFilename)); // Free resources img.flush(); if (original != null) { original.flush(); } }
From source file:org.qifu.util.PdfConvertUtils.java
License:Apache License
public static List<File> toImageFiles(File pdfFile, int resolution) throws Exception { PDDocument document = PDDocument.load(pdfFile); PDFRenderer pdfRenderer = new PDFRenderer(document); /*/*w w w .ja va 2 s.co m*/ List<PDPage> pages = new LinkedList<PDPage>(); for (int i=0; i < document.getDocumentCatalog().getPages().getCount(); i++) { pages.add( document.getDocumentCatalog().getPages().get(i) ); } */ File tmpDir = new File(Constants.getWorkTmpDir() + "/" + PdfConvertUtils.class.getSimpleName() + "/" + System.currentTimeMillis() + "/"); FileUtils.forceMkdir(tmpDir); List<File> files = new LinkedList<File>(); //int len = String.valueOf(pages.size()+1).length(); int len = String.valueOf(document.getDocumentCatalog().getPages().getCount() + 1).length(); //for (int i=0; i<pages.size(); i++) { for (int i = 0; i < document.getDocumentCatalog().getPages().getCount(); i++) { String name = StringUtils.leftPad(String.valueOf(i + 1), len, "0"); BufferedImage bufImage = pdfRenderer.renderImageWithDPI(i, resolution, ImageType.RGB); File imageFile = new File(tmpDir.getPath() + "/" + name + ".png"); FileOutputStream fos = new FileOutputStream(imageFile); ImageIOUtil.writeImage(bufImage, "png", fos, resolution); fos.flush(); fos.close(); files.add(imageFile); } document.close(); tmpDir = null; return files; }