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:at.gv.egiz.pdfas.lib.impl.signing.pdfbox2.PADESPDFBOXSigner.java
License:EUPL
@Override public Image generateVisibleSignaturePreview(SignParameter parameter, java.security.cert.X509Certificate cert, int resolution, OperationStatus status, RequestedSignature requestedSignature) throws PDFASError { try {// w w w . j ava 2 s.com PDFBOXObject pdfObject = (PDFBOXObject) status.getPdfObject(); PDDocument origDoc = new PDDocument(); origDoc.addPage(new PDPage(PDRectangle.A4)); ByteArrayOutputStream baos = new ByteArrayOutputStream(); origDoc.save(baos); baos.close(); pdfObject.setOriginalDocument(new ByteArrayDataSource(baos.toByteArray())); SignatureProfileSettings signatureProfileSettings = TableFactory .createProfile(requestedSignature.getSignatureProfileID(), pdfObject.getStatus().getSettings()); // create Table describtion Table main = TableFactory.createSigTable(signatureProfileSettings, MAIN, pdfObject.getStatus(), requestedSignature); IPDFStamper stamper = StamperFactory.createDefaultStamper(pdfObject.getStatus().getSettings()); IPDFVisualObject visualObject = stamper.createVisualPDFObject(pdfObject, main); SignatureProfileConfiguration signatureProfileConfiguration = pdfObject.getStatus() .getSignatureProfileConfiguration(requestedSignature.getSignatureProfileID()); String signaturePosString = signatureProfileConfiguration.getDefaultPositioning(); PositioningInstruction positioningInstruction = null; if (signaturePosString != null) { positioningInstruction = Positioning.determineTablePositioning(new TablePos(signaturePosString), "", origDoc, visualObject, pdfObject.getStatus().getSettings()); } else { positioningInstruction = Positioning.determineTablePositioning(new TablePos(), "", origDoc, visualObject, pdfObject.getStatus().getSettings()); } origDoc.close(); SignaturePositionImpl position = new SignaturePositionImpl(); position.setX(positioningInstruction.getX()); position.setY(positioningInstruction.getY()); position.setPage(positioningInstruction.getPage()); position.setHeight(visualObject.getHeight()); position.setWidth(visualObject.getWidth()); requestedSignature.setSignaturePosition(position); PDFAsVisualSignatureProperties properties = new PDFAsVisualSignatureProperties( pdfObject.getStatus().getSettings(), pdfObject, (PdfBoxVisualObject) visualObject, positioningInstruction, signatureProfileSettings); properties.buildSignature(); PDDocument visualDoc; synchronized (PDDocument.class) { visualDoc = PDDocument.load(properties.getVisibleSignature()); } // PDPageable pageable = new PDPageable(visualDoc); PDPage firstPage = visualDoc.getDocumentCatalog().getPages().get(0); float stdRes = 72; float targetRes = resolution; float factor = targetRes / stdRes; int targetPageNumber = 0;//TODO: is this always the case PDFRenderer pdfRenderer = new PDFRenderer(visualDoc); BufferedImage outputImage = pdfRenderer.renderImageWithDPI(targetPageNumber, targetRes, ImageType.ARGB); //BufferedImage outputImage = firstPage.convertToImage(BufferedImage.TYPE_4BYTE_ABGR, (int) targetRes); BufferedImage cutOut = new BufferedImage((int) (position.getWidth() * factor), (int) (position.getHeight() * factor), BufferedImage.TYPE_4BYTE_ABGR); Graphics2D graphics = (Graphics2D) cutOut.getGraphics(); graphics.drawImage(outputImage, 0, 0, cutOut.getWidth(), cutOut.getHeight(), (int) (1 * factor), (int) (outputImage.getHeight() - ((position.getHeight() + 1) * factor)), (int) ((1 + position.getWidth()) * factor), (int) (outputImage.getHeight() - ((position.getHeight() + 1) * factor) + (position.getHeight() * factor)), null); return cutOut; } catch (PdfAsException e) { logger.warn("PDF-AS Exception", e); throw ErrorExtractor.searchPdfAsError(e, status); } catch (Throwable e) { logger.warn("Unexpected Throwable Exception", e); throw ErrorExtractor.searchPdfAsError(e, status); } }
From source file:com.ackpdfbox.app.PDFToImage.java
License:Apache License
/** * Infamous main method.//from w ww . j av a 2 s .c om * * @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:com.htmlhifive.pitalium.sample.pdf.PDFReadTest.java
License:Apache License
/** * PDF?????????<br/>//from w w w .j a v a 2s . c o m * PDF?1?????1???<br/> * PDF??????Apache PDFBox? * * @param fileName ?PDF???.pdf??? * @return ?????PDF? */ private int savePdfAsImages(String fileName) { int numberOfPages = 0; try (BufferedInputStream fileToParse = new BufferedInputStream( getClass().getResourceAsStream(fileName + ".pdf")); PDDocument pdf = PDDocument.load(fileToParse)) { // 1=1????? final PDFRenderer pdfRenderer = new PDFRenderer(pdf); numberOfPages = pdf.getNumberOfPages(); for (int i = 0; i < numberOfPages; i++) { final BufferedImage image = pdfRenderer.renderImageWithDPI(i, 300, ImageType.RGB); if (!saveExportImage(image, fileName + i + ".png")) { return -1; } } } catch (IOException e) { return -1; } return numberOfPages; }
From source file:com.joowon.returnA.classifier.export.PdfImageExport.java
License:Open Source License
public static File[] export(PDDocument document, String filePath, String fileName) { File[] exportFiles = new File[document.getNumberOfPages()]; try {//from ww w . ja va 2 s. c o m PDFRenderer renderer = new PDFRenderer(document); for (int page = 0; page < document.getNumberOfPages(); ++page) { BufferedImage image = renderer.renderImageWithDPI(page, 300, ImageType.RGB); final String file = filePath + "/" + fileName + "_" + (page + 1) + ".png"; ImageIOUtil.writeImage(image, file, 300); exportFiles[page] = new File(file); System.out.println("Export image file from PDF : " + file + " [" + (page + 1) + "/" + document.getNumberOfPages() + "]"); } } catch (IOException exception) { exception.printStackTrace(); System.err.println("IOException occurred\nCheck file path."); } return exportFiles; }
From source file:com.liferay.portlet.documentlibrary.util.LiferayPDFBoxConverter.java
License:Open Source License
private void _generateImagesPB(PDFRenderer pdfRenderer, int index, File outputFile, String extension) throws Exception { RenderedImage renderedImage = pdfRenderer.renderImageWithDPI(index, _dpi, ImageType.RGB); ImageTool imageTool = ImageToolImpl.getInstance(); if (_height != 0) { renderedImage = imageTool.scale(renderedImage, _width, _height); } else {/*from w ww .jav a 2 s .c om*/ renderedImage = imageTool.scale(renderedImage, _width); } outputFile.createNewFile(); ImageIO.write(renderedImage, extension, outputFile); }
From source file:com.testautomationguru.utility.PDFUtil.java
License:Apache License
/** * This method saves the each page of the pdf as image *//*from w w w . j a v a 2s . c o m*/ private List<String> saveAsImage(String file, int startPage, int endPage) throws IOException { logger.info("file : " + file); logger.info("startPage : " + startPage); logger.info("endPage : " + endPage); ArrayList<String> imgNames = new ArrayList<String>(); try { File sourceFile = new File(file); this.createImageDestinationDirectory(file); this.updateStartAndEndPages(file, startPage, endPage); String fileName = sourceFile.getName().replace(".pdf", ""); PDDocument document = PDDocument.load(sourceFile); PDFRenderer pdfRenderer = new PDFRenderer(document); for (int iPage = this.startPage - 1; iPage < this.endPage; iPage++) { logger.info("Page No : " + (iPage + 1)); String fname = this.imageDestinationPath + fileName + "_" + (iPage + 1) + ".png"; BufferedImage image = pdfRenderer.renderImageWithDPI(iPage, 300, ImageType.RGB); ImageIOUtil.writeImage(image, fname, 300); imgNames.add(fname); logger.info("PDf Page saved as image : " + fname); } document.close(); } catch (Exception e) { e.printStackTrace(); } return imgNames; }
From source file:com.testautomationguru.utility.PDFUtil.java
License:Apache License
private boolean convertToImageAndCompare(String file1, String file2, int startPage, int endPage) throws IOException { boolean result = true; PDDocument doc1 = null;//from w w w .jav a 2 s . c o m PDDocument doc2 = null; PDFRenderer pdfRenderer1 = null; PDFRenderer pdfRenderer2 = null; try { doc1 = PDDocument.load(new File(file1)); doc2 = PDDocument.load(new File(file2)); pdfRenderer1 = new PDFRenderer(doc1); pdfRenderer2 = new PDFRenderer(doc2); for (int iPage = startPage - 1; iPage < endPage; iPage++) { String fileName = new File(file1).getName().replace(".pdf", "_") + (iPage + 1); fileName = this.getImageDestinationPath() + "/" + fileName + "_diff.png"; logger.info("Comparing Page No : " + (iPage + 1)); BufferedImage image1 = pdfRenderer1.renderImageWithDPI(iPage, 300, ImageType.RGB); BufferedImage image2 = pdfRenderer2.renderImageWithDPI(iPage, 300, ImageType.RGB); result = ImageUtil.compareAndHighlight(image1, image2, fileName, this.bHighlightPdfDifference, this.imgColor.getRGB()) && result; if (!this.bCompareAllPages && !result) { break; } } } catch (Exception e) { e.printStackTrace(); } finally { doc1.close(); doc2.close(); } return result; }
From source file:com.yiyihealth.util.PDF2Image.java
License:Apache License
/** * Infamous main method.//from ww w. ja v a 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 www. j a v a 2 s.c om*/ * * @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.ja va2s . 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); } }