List of usage examples for org.apache.pdfbox.rendering PDFRenderer renderImage
public BufferedImage renderImage(int pageIndex) throws IOException
From source file:com.bgh.myopeninvoice.jsf.jsfbeans.InvoiceBean.java
License:Apache License
public String getImageAttachment(AttachmentEntity attachmentEntity) throws IOException, ImageReadException { if (attachmentEntity != null && attachmentEntity.getContent().length > 0) { if (attachmentEntity.getLoadProxy()) { return "/images/" + attachmentEntity.getFileExtension() + ".png"; } else {//from w w w . j av a 2 s .co m selectedAttachmentEntity = attachmentEntity; ImageFormat mimeType = Sanselan.guessFormat(attachmentEntity.getContent()); if (mimeType != null && !"UNKNOWN".equalsIgnoreCase(mimeType.name)) { return "data:image/" + mimeType.extension.toLowerCase() + ";base64," + Base64.getEncoder().encodeToString(attachmentEntity.getContent()); } else if (attachmentEntity.getImageData() != null && attachmentEntity.getImageData().length > 0) { return "data:image/png;base64," + Base64.getEncoder().encodeToString(attachmentEntity.getImageData()); } else if ("pdf".equalsIgnoreCase(attachmentEntity.getFileExtension())) { ByteArrayOutputStream baos = null; PDDocument document = null; try { document = PDDocument.load(attachmentEntity.getContent()); final PDPage page = document.getPage(0); PDFRenderer pdfRenderer = new PDFRenderer(document); final BufferedImage bufferedImage = pdfRenderer.renderImage(0); baos = new ByteArrayOutputStream(); ImageIO.write(bufferedImage, "png", baos); baos.flush(); attachmentEntity.setImageData(baos.toByteArray()); } finally { if (document != null) { document.close(); } if (baos != null) { baos.close(); } } return "data:image/png;base64," + Base64.getEncoder().encodeToString(attachmentEntity.getImageData()); } else { return null; } } } else if (selectedAttachmentEntity != null && selectedAttachmentEntity.getImageData() != null && selectedAttachmentEntity.getImageData().length > 0) { return "data:image/png;base64," + Base64.getEncoder().encodeToString(selectedAttachmentEntity.getImageData()); } else { return null; } }
From source file:com.truckzoo.test.pdf.CustomPageDrawer.java
License:Apache License
public static void main(String[] args) throws IOException { File file = new File("custom-render-demo.pdf"); PDDocument doc = PDDocument.load(file); PDFRenderer renderer = new MyPDFRenderer(doc); BufferedImage image = renderer.renderImage(0); ImageIO.write(image, "PNG", new File("custom-render.png")); doc.close();//from w w w . j a v a 2 s .com }
From source file:FileIOAux.PrintAux.java
/** * @see//from ww w . j a v a 2s. com * 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; }
From source file:gov.anl.aps.cdb.portal.utilities.GalleryUtility.java
License:Open Source License
public static void storeImagePreviews(File originalFile, String imageFormat) { String originalName = originalFile.getName(); boolean viewable; if (imageFormat == null) { imageFormat = getImageFormat(originalName); viewable = viewableFormat(imageFormat); } else {//www . ja v a 2s . c o m viewable = viewableFormat(imageFormat); } if (originalName.endsWith(CdbPropertyValue.ORIGINAL_IMAGE_EXTENSION)) { originalName = originalName.replace(CdbPropertyValue.ORIGINAL_IMAGE_EXTENSION, ""); } if (viewable) { logger.debug("Generating previews for: " + originalName); } else { logger.debug("Cannot generate preview for: " + originalName + " Invalid Extension: " + imageFormat); return; } try { byte[] originalData; // Generate Preview to scale for pdf images. if (imageFormat.equalsIgnoreCase("pdf")) { BufferedImage image = null; try (PDDocument pdfDocument = PDDocument.load(originalFile)) { PDFRenderer renderer = new PDFRenderer(pdfDocument); image = renderer.renderImage(0); pdfDocument.close(); } try (ByteArrayOutputStream imageBaos = new ByteArrayOutputStream()) { ImageIO.write(image, "PNG", imageBaos); imageBaos.flush(); originalData = imageBaos.toByteArray(); imageFormat = "png"; } // It is not possible to catch certain errors during gerneration of a page preview. // Avoid creating blank white previews. if (originalData.length < 5000) { return; } } else { originalData = Files.readAllBytes(originalFile.toPath()); } byte[] thumbData = ImageUtility.resizeImage(originalData, StorageUtility.THUMBNAIL_IMAGE_SIZE, imageFormat); String thumbFileName = originalFile.getAbsolutePath().replace(originalName, originalName + CdbPropertyValue.THUMBNAIL_IMAGE_EXTENSION); thumbFileName = thumbFileName.replace(CdbPropertyValue.ORIGINAL_IMAGE_EXTENSION, ""); Path thumbPath = Paths.get(thumbFileName); Files.write(thumbPath, thumbData); logger.debug("Saved File: " + thumbFileName); byte[] scaledData; if (ImageUtility.verifyImageSizeBigger(originalData, StorageUtility.SCALED_IMAGE_SIZE)) { scaledData = ImageUtility.resizeImage(originalData, StorageUtility.SCALED_IMAGE_SIZE, imageFormat); } else { scaledData = originalData; } String scaledFileName = originalFile.getAbsolutePath().replace(originalName, originalName + CdbPropertyValue.SCALED_IMAGE_EXTENSION); scaledFileName = scaledFileName.replace(CdbPropertyValue.ORIGINAL_IMAGE_EXTENSION, ""); Path scaledPath = Paths.get(scaledFileName); Files.write(scaledPath, scaledData); logger.debug("Saved File: " + scaledFileName); } catch (IOException | ImageProcessingFailed ex) { logger.error(ex); // Check allows this class to run as a utility without server running. FacesContext context = FacesContext.getCurrentInstance(); if (context != null) { SessionUtility.addErrorMessage("Error", ex.toString()); } } }
From source file:GUI.Helper.IOHelper.java
public static boolean getProjectImage(MainController mc) { FileChooser fc = new FileChooser(); fc.setTitle("Select WZITS Project Image"); fc.getExtensionFilters().addAll(//from ww w .ja v a 2 s. c o m //new FileChooser.ExtensionFilter("All Images", "*.*"), new FileChooser.ExtensionFilter("JPG", "*.jpg"), new FileChooser.ExtensionFilter("PNG", "*.png"), new FileChooser.ExtensionFilter("PDF", "*.pdf")); File openFile = fc.showOpenDialog(MainController.getWindow()); //mc.getMainWindow() if (openFile != null) { if (fc.getSelectedExtensionFilter().getExtensions().get(0).equalsIgnoreCase("*.pdf")) { try { PDDocument doc = PDDocument.load(openFile); PDFRenderer pdfRenderer = new PDFRenderer(doc); BufferedImage image = pdfRenderer.renderImage(0); //ImageIOUtil.writeImage(image, "C:\\Users\\ltrask\\Documents\\test_image.png", 300); Image convertedImage = SwingFXUtils.toFXImage(image, null); mc.getProject().setProjPhoto(convertedImage); doc.close(); return true; } catch (IOException e) { Alert al = new Alert(Alert.AlertType.ERROR); al.setTitle("WZITS Tool"); al.setHeaderText("The selected PDF is password protected"); al.showAndWait(); } } else { try { mc.getProject().setProjPhoto(new Image(new FileInputStream(openFile))); return true; } catch (FileNotFoundException e) { } } } return false; }
From source file:GUI.Helper.IOHelper.java
public static Image openImage(MainController mc) { FileChooser fc = new FileChooser(); fc.setTitle("Select WZITS Project Image"); fc.getExtensionFilters().addAll(new FileChooser.ExtensionFilter("JPG", "*.jpg"), new FileChooser.ExtensionFilter("PNG", "*.png"), new FileChooser.ExtensionFilter("PDF", "*.pdf")); File openFile = fc.showOpenDialog(mc.getWindow()); //mc.getMainWindow() if (openFile != null) { if (fc.getSelectedExtensionFilter().getExtensions().get(0).equalsIgnoreCase("*.pdf")) { try { PDDocument doc = PDDocument.load(openFile); PDFRenderer pdfRenderer = new PDFRenderer(doc); BufferedImage image = pdfRenderer.renderImage(0); Image convertedImage = SwingFXUtils.toFXImage(image, null); doc.close();//from w ww . j a v a2s . c om return convertedImage; } catch (IOException e) { Alert al = new Alert(Alert.AlertType.ERROR); al.setTitle("WZITS Tool"); al.setHeaderText("The selected PDF is password protected"); al.showAndWait(); } } else { try { return new Image(new FileInputStream(openFile)); } catch (FileNotFoundException e) { } } } return null; }
From source file:org.dspace.app.mediafilter.PDFBoxThumbnail.java
License:BSD License
/** * @param source/* w ww .j a v a2s .c o m*/ * source input stream * * @return InputStream the resulting input stream */ @Override public InputStream getDestinationStream(Item currentItem, InputStream source, boolean verbose) throws Exception { PDDocument doc = PDDocument.load(source); PDFRenderer renderer = new PDFRenderer(doc); BufferedImage buf = renderer.renderImage(0); // ImageIO.write(buf, "PNG", new File("custom-render.png")); doc.close(); JPEGFilter jpegFilter = new JPEGFilter(); return jpegFilter.getThumb(currentItem, buf, verbose); }
From source file:org.mycore.iview2.frontend.MCRPDFTools.java
License:Open Source License
static BufferedImage getThumbnail(Path pdfFile, int thumbnailSize, boolean centered) throws IOException { InputStream fileIS = Files.newInputStream(pdfFile); PDDocument pdf = PDDocument.load(fileIS); try {/* w ww . j a v a 2 s . c o m*/ PDFRenderer pdfRenderer = new PDFRenderer(pdf); BufferedImage level1Image = pdfRenderer.renderImage(0); int imageType = BufferedImage.TYPE_INT_ARGB; if (!centered) { return level1Image; } final double width = level1Image.getWidth(); final double height = level1Image.getHeight(); LOGGER.info("new PDFBox: " + width + "x" + height); LOGGER.info("temporary image dimensions: " + width + "x" + height); final int newWidth = width < height ? (int) Math.ceil(thumbnailSize * width / height) : thumbnailSize; final int newHeight = width < height ? thumbnailSize : (int) Math.ceil(thumbnailSize * height / width); //if centered make thumbnailSize x thumbnailSize image final BufferedImage bicubic = new BufferedImage(centered ? thumbnailSize : newWidth, centered ? thumbnailSize : newHeight, imageType); LOGGER.info("target image dimensions: " + bicubic.getWidth() + "x" + bicubic.getHeight()); final Graphics2D bg = bicubic.createGraphics(); bg.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC); int x = centered ? (thumbnailSize - newWidth) / 2 : 0; int y = centered ? (thumbnailSize - newHeight) / 2 : 0; if (x != 0 && y != 0) { LOGGER.warn("Writing at position " + x + "," + y); } bg.drawImage(level1Image, x, y, x + newWidth, y + newHeight, 0, 0, (int) Math.ceil(width), (int) Math.ceil(height), null); bg.dispose(); return bicubic; } finally { pdf.close(); } }
From source file:org.silverpeas.core.util.PdfUtil.java
License:Open Source License
/** * Converts the first page of a PDF file into a JPEG image. * @param pdfSource the source pdf file, this content is not modified by this method. * @param imageDestination the destination file of the image representing the first page. *//*ww w . j a v a 2 s. c om*/ public static void firstPageAsImage(File pdfSource, File imageDestination) { if (pdfSource == null || !pdfSource.isFile()) { throw new SilverpeasRuntimeException(PDF_FILE_ERROR_MSG); } else if (!FileUtil.isPdf(pdfSource.getPath())) { throw new SilverpeasRuntimeException(NOT_PDF_FILE_ERROR_MSG); } try (final PDDocument document = PDDocument.load(pdfSource)) { final PDFRenderer pdfRenderer = new PDFRenderer(document); final BufferedImage image = pdfRenderer.renderImage(0); ImageIO.write(image, "jpg", imageDestination); } catch (Exception e) { SilverLogger.getLogger(PdfUtil.class).error(e); throw new SilverpeasRuntimeException( "A problem has occurred during the adding of an image into a pdf file", e); } }
From source file:pdf.DailyReportPDF.java
public void createDailyReportPNG(String path) throws IOException { File file = new File(path); PDDocument doc = PDDocument.load(file); PDFRenderer renderer = new PDFRenderer(doc); BufferedImage image = renderer.renderImage(0); SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy."); ImageIO.write(image, "PNG", new File("pdf_docs\\daily_reports_picture\\" + "drpic-" + sdf.format(dateOfDailyReport) + ".png")); doc.close();/*ww w. j a v a 2s. c om*/ }