List of usage examples for org.apache.pdfbox.rendering PDFRenderer PDFRenderer
public PDFRenderer(PDDocument document)
From source file:com.yiyihealth.util.PDF2Image.java
License:Apache License
/** * Infamous main method.//from w w w . j ava 2 s.com * * @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 void main(String[] args) throws IOException { // suppress the Dock icon on OS X 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 < args.length; i++) { if (args[i].equals(PASSWORD)) { i++; if (i >= args.length) { usage(); } password = args[i]; } else if (args[i].equals(START_PAGE)) { i++; if (i >= args.length) { usage(); } startPage = Integer.parseInt(args[i]); } else if (args[i].equals(END_PAGE)) { i++; if (i >= args.length) { usage(); } endPage = Integer.parseInt(args[i]); } else if (args[i].equals(PAGE)) { i++; if (i >= args.length) { usage(); } startPage = Integer.parseInt(args[i]); endPage = Integer.parseInt(args[i]); } else if (args[i].equals(IMAGE_TYPE) || args[i].equals(FORMAT)) { i++; imageFormat = args[i]; } else if (args[i].equals(OUTPUT_PREFIX) || args[i].equals(PREFIX)) { i++; outputPrefix = args[i]; } else if (args[i].equals(COLOR)) { i++; color = args[i]; } else if (args[i].equals(RESOLUTION) || args[i].equals(DPI)) { i++; dpi = Integer.parseInt(args[i]); } else if (args[i].equals(CROPBOX)) { i++; cropBoxLowerLeftX = Float.valueOf(args[i]); i++; cropBoxLowerLeftY = Float.valueOf(args[i]); i++; cropBoxUpperRightX = Float.valueOf(args[i]); i++; cropBoxUpperRightY = Float.valueOf(args[i]); } else if (args[i].equals(TIME)) { showTime = true; } else { if (pdfFile == null) { pdfFile = args[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; i++) { BufferedImage image = renderer.renderImageWithDPI(i, dpi, imageType); String fileName = outputPrefix + "_" + (i + 1) + "." + imageFormat; success &= ImageIOUtil.writeImage(image, fileName, dpi); } // 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(); } } } }
From source file:cz.mzk.editor.server.fedora.KrameriusImageSupport.java
License:Open Source License
/** * Read image./*from w ww . java 2 s .co m*/ * * @param url * the url * @param type * the type * @param page * the page * @return the image * @throws IOException * Signals that an I/O exception has occurred. */ public static Image readImage(URL url, ImageMimeType type, int page) throws IOException { if (type.javaNativeSupport()) { return ImageIO.read(url.openStream()); } else if ((type.equals(ImageMimeType.DJVU)) || (type.equals(ImageMimeType.VNDDJVU)) || (type.equals(ImageMimeType.XDJVU))) { com.lizardtech.djvu.Document doc = new com.lizardtech.djvu.Document(url); doc.setAsync(false); DjVuPage[] p = new DjVuPage[1]; // read page from the document - index 0, priority 1, favorFast true int size = doc.size(); if ((page != 0) && (page >= size)) { page = 0; } p[0] = doc.getPage(page, 1, true); p[0].setAsync(false); DjVuImage djvuImage = new DjVuImage(p, true); Rectangle pageBounds = djvuImage.getPageBounds(0); Image[] images = djvuImage.getImage(new JPanel(), new Rectangle(pageBounds.width, pageBounds.height)); if (images.length == 1) { Image img = images[0]; return img; } else return null; } else if (type.equals(ImageMimeType.PDF)) { try (PDDocument document = PDDocument.load(url.openStream());) { PDFRenderer pdfRenderer = new PDFRenderer(document); int resolution = 96; BufferedImage image = pdfRenderer.renderImageWithDPI(page, resolution, ImageType.RGB); return image; } } else throw new IllegalArgumentException("unsupported mimetype '" + type.getValue() + "'"); }
From source file:cz.mzk.editor.server.newObject.CreateObject.java
License:Open Source License
/** * Creates the thumb prew from pdf.//ww w . j a va 2s . c om * * @param dsId the ds id * @param pathWithoutExtension the path without extension * @param thumbPageNum the thumb page num * @param uuid the uuid * @param width the image width * @throws CreateObjectException the create object exception */ private void createThumbPrewFromPdf(DATASTREAM_ID dsId, String pathWithoutExtension, int thumbPageNum, String uuid, int width) throws CreateObjectException { try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); PDDocument document = PDDocument .load(Files.newInputStream(Paths.get(pathWithoutExtension + Constants.PDF_EXTENSION)));) { long startTime = System.currentTimeMillis(); // convert pdf to image PDFRenderer pdfRenderer = new PDFRenderer(document); BufferedImage imageFull = pdfRenderer.renderImageWithDPI(thumbPageNum - 1, 72, ImageType.RGB); // resize image int height = (int) (imageFull.getHeight() * (double) width / imageFull.getWidth()); BufferedImage preview = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); Graphics2D gPreview = preview.createGraphics(); gPreview.drawImage(imageFull, 0, 0, width, height, null); gPreview.dispose(); ImageIO.write(preview, "jpeg", outputStream); LOGGER.debug("Duration of " + pathWithoutExtension + Constants.PDF_EXTENSION + "conversion was " + (System.currentTimeMillis() - startTime) + "ms"); // upload Client client = new ResteasyClientBuilder() .register(new BasicAuthentication(config.getFedoraLogin(), config.getFedoraPassword())).build(); String prepUrl = "/objects/" + (uuid.contains("uuid:") ? uuid : "uuid:".concat(uuid)) + "/datastreams/" + dsId.getValue() + "?controlGroup=M&versionable=true&dsState=A&mimeType=image/jpeg"; WebTarget target = client.target(config.getFedoraHost().concat(prepUrl)); target.request() .post(Entity.entity(outputStream.toByteArray(), MediaType.APPLICATION_OCTET_STREAM_TYPE)); } catch (IOException e) { LOGGER.error(e.getMessage()); throw new CreateObjectException("Unable to run the convert proces on the pdf file: " + pathWithoutExtension + Constants.PDF_EXTENSION); } }
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 .j ava 2 s. c o m 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:de.redsix.pdfcompare.PdfComparator.java
License:Apache License
private void compare(final PDDocument expectedDocument, final PDDocument actualDocument) throws IOException { expectedDocument.setResourceCache(new ResourceCacheWithLimitedImages()); PDFRenderer expectedPdfRenderer = new PDFRenderer(expectedDocument); actualDocument.setResourceCache(new ResourceCacheWithLimitedImages()); PDFRenderer actualPdfRenderer = new PDFRenderer(actualDocument); final int minPageCount = Math.min(expectedDocument.getNumberOfPages(), actualDocument.getNumberOfPages()); CountDownLatch latch = new CountDownLatch(minPageCount); for (int pageIndex = 0; pageIndex < minPageCount; pageIndex++) { drawImage(latch, pageIndex, expectedDocument, actualDocument, expectedPdfRenderer, actualPdfRenderer); }//w w w . j a va 2s . com Utilities.await(latch, "FullCompare"); Utilities.shutdownAndAwaitTermination(drawExecutor, "Draw"); Utilities.shutdownAndAwaitTermination(parrallelDrawExecutor, "Parallel Draw"); Utilities.shutdownAndAwaitTermination(diffExecutor, "Diff"); if (expectedDocument.getNumberOfPages() > minPageCount) { addExtraPages(expectedDocument, expectedPdfRenderer, minPageCount, MISSING_RGB, true); } else if (actualDocument.getNumberOfPages() > minPageCount) { addExtraPages(actualDocument, actualPdfRenderer, minPageCount, EXTRA_RGB, false); } }
From source file:de.redsix.pdfcompare.PdfComparator.java
License:Apache License
private void addSingleDocumentToResult(InputStream expectedPdfIS, int markerColor) throws IOException { try (PDDocument expectedDocument = PDDocument.load(expectedPdfIS)) { PDFRenderer expectedPdfRenderer = new PDFRenderer(expectedDocument); addExtraPages(expectedDocument, expectedPdfRenderer, 0, markerColor, true); }//from ww w .j a v a 2 s .c o m }
From source file:es.rickyepoderi.pdfimages.Converter.java
License:Open Source License
/** * Method that converts a PDF file in a series of images. * /* ww w . j a v a2 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:eu.europa.esig.dss.pades.signature.PAdESVisibleSignaturePositionTest.java
License:Open Source License
private void checkImageSimilarityPdf(String samplePdf, String checkPdf, float similarity) throws IOException { DSSDocument document = sign(signablePdfs.get(samplePdf)); PDDocument sampleDocument = PDDocument.load(document.openStream()); PDDocument checkDocument = PDDocument .load(getClass().getResourceAsStream("/visualSignature/check/" + checkPdf)); PDPageTree samplePageTree = sampleDocument.getPages(); PDPageTree checkPageTree = checkDocument.getPages(); Assert.assertEquals(checkPageTree.getCount(), samplePageTree.getCount()); PDFRenderer sampleRenderer = new PDFRenderer(sampleDocument); PDFRenderer checkRenderer = new PDFRenderer(checkDocument); for (int pageNumber = 0; pageNumber < checkPageTree.getCount(); pageNumber++) { BufferedImage sampleImage = sampleRenderer.renderImageWithDPI(pageNumber, DPI); BufferedImage checkImage = checkRenderer.renderImageWithDPI(pageNumber, DPI); float checkSimilarity = checkImageSimilarity(sampleImage, checkImage, CHECK_RESOLUTION); float calculatedSimilarity = ((int) (similarity * 100f)) / 100f; // calulate rotated position has about 1 // pixel position difference Assert.assertTrue(checkSimilarity >= calculatedSimilarity); }// ww w .j a va 2 s. c o m }
From source file:eu.europa.esig.dss.pades.signature.PAdESVisibleSignaturePositionTest.java
License:Open Source License
private BufferedImage pdfToBufferedImage(InputStream inputStream) throws IOException { PDDocument document = PDDocument.load(inputStream); PDFRenderer renderer = new PDFRenderer(document); return renderer.renderImageWithDPI(0, DPI); }
From source file:FileIOAux.PrintAux.java
/** * @see/* w w w .ja v a 2s .c o m*/ * http://stackoverflow.com/questions/23326562/apache-pdfbox-convert-pdf-to-images * @param fil * @return */ public static BufferedImage[] pdfToImage(String fil) { BufferedImage[] bim = null; try { PDDocument document = PDDocument.load(new File(fil)); if (document != null) { PDFRenderer pdfRenderer = new PDFRenderer(document); bim = new BufferedImage[document.getNumberOfPages()]; for (int i = 0; i < document.getNumberOfPages(); i++) { bim[i] = pdfRenderer.renderImage(i); } document.close(); } } catch (IOException ex) { Logger.getLogger(PrintAux.class.getName()).log(Level.SEVERE, null, ex); } return bim; }