List of usage examples for org.apache.pdfbox.rendering PDFRenderer PDFRenderer
public PDFRenderer(PDDocument document)
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. jav a 2 s . c om*/ 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.fcore.base.fileSystem.utils.FileUtil.java
/** * PDF to Image(png)//from w w w . j a v a 2 s . co m * @param pdfPath * @param imagePath */ public static void pdf2png(String pdfPath, String imagePath) { long old = System.currentTimeMillis(); // pdf ?? File file = new File(pdfPath); try { PDDocument doc = PDDocument.load(file); PDFRenderer renderer = new PDFRenderer(doc); int pageCount = doc.getNumberOfPages(); for (int i = 0; i < pageCount; i++) { BufferedImage image = renderer.renderImageWithDPI(i, 250); // Windows //BufferedImage srcImage = resize(image, 240, 240);// ImageIO.write(image, "PNG", new File(imagePath + i + ".png")); } } catch (IOException e) { e.printStackTrace(); } long now = System.currentTimeMillis(); System.out.println("" + ((now - old) / 1000.0) + "\n\n" + "?:" + imagePath); }
From source file:com.formkiq.core.service.conversion.PdfToPngFormatConverter.java
License:Apache License
@Override public ConversionResult convert(final Object data, final WorkflowOutputDocumentType inputType, final WorkflowOutputDocumentType outputType) throws IOException { PDDocument doc = (PDDocument) data;//from ww w . j av a 2 s .com PDFRenderer pdfRenderer = new PDFRenderer(doc); BufferedImage[] images = new BufferedImage[doc.getNumberOfPages()]; for (int page = 0; page < doc.getNumberOfPages(); ++page) { BufferedImage bim = pdfRenderer.renderImage(page, SCALE); images[page] = bim; } ConversionResult result = merge(images); List<ConversionField> fields = findSigningButtons(doc, result); result.setFields(fields); return result; }
From source file:com.htmlhifive.pitalium.sample.pdf.PDFReadTest.java
License:Apache License
/** * PDF?????????<br/>/*from w ww . j a v a 2 s . 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.java2s.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
public void generateImagesPB() throws Exception { PDDocument pdDocument = null;//from w w w . ja v a2 s. co m try { pdDocument = PDDocument.load(_inputFile); PDDocumentCatalog pdDocumentCatalog = pdDocument.getDocumentCatalog(); PDFRenderer pdfRenderer = new PDFRenderer(pdDocument); PDPageTree pdPages = pdDocumentCatalog.getPages(); for (int i = 0; i < pdPages.getCount(); i++) { if (_generateThumbnail && (i == 0)) { _generateImagesPB(pdfRenderer, i, _thumbnailFile, _thumbnailExtension); } if (!_generatePreview) { break; } _generateImagesPB(pdfRenderer, i, _previewFiles[i], _extension); } } finally { if (pdDocument != null) { pdDocument.close(); } } }
From source file:com.testautomationguru.utility.PDFUtil.java
License:Apache License
/** * This method saves the each page of the pdf as image */// w w w .j av a 2s .c om 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 . j a v a 2s . 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.vns.pdf.impl.PdfDocument.java
License:Apache License
private PdfDocument(String pdfFileName) throws IOException { this.pdfFileName = pdfFileName; setWorkingDir();//w w w . j av a 2 s.co m Path filePath = Paths.get(pdfFileName); PosixFileAttributes attrs = Files.getFileAttributeView(filePath, PosixFileAttributeView.class) .readAttributes(); String textAreaFileName = filePath.getFileName().toString() + "_" + filePath.toAbsolutePath().hashCode() + "_" + attrs.size() + "_" + attrs.lastModifiedTime().toString().replace(":", "_") + ".xml"; textAreaFilePath = Paths.get(workingDir.toAbsolutePath().toString(), textAreaFileName); pdfTextStripper = new CustomPDFTextStripper(); document = PDDocument.load(new File(pdfFileName)); pdfRenderer = new PDFRenderer(document); if (Files.notExists(textAreaFilePath, LinkOption.NOFOLLOW_LINKS)) { pdfTextStripper.setSortByPosition(false); pdfTextStripper.setStartPage(0); pdfTextStripper.setEndPage(document.getNumberOfPages()); this.doc = new Doc(new ArrayList<>(), new ArrayList<>()); for (int i = 0; i < document.getNumberOfPages(); i++) { PDPage pdPage = document.getPage(i); PDRectangle box = pdPage.getMediaBox(); this.doc.getPages().add(new Page(new ArrayList<>(), new ArrayList<>(), (int) box.getWidth(), (int) box.getHeight())); } Writer dummy = new OutputStreamWriter(new ByteArrayOutputStream()); try { pdfTextStripper.writeText(document, dummy); } catch (Exception ex) { LOGGER.error(ex.getMessage(), ex); } parseBookmarksAnnotation(); createTextAreaFile(); //document.save(pdfFileName + ".pdf"); } else { loadTextAreaFile(); } }
From source file:com.yiyihealth.tools.test.DrawPrintTextLocations.java
License:Apache License
private void stripPage(int page) throws IOException { PDFRenderer pdfRenderer = new PDFRenderer(document); image = pdfRenderer.renderImage(page, SCALE); PDPage pdPage = document.getPage(page); PDRectangle cropBox = pdPage.getCropBox(); // flip y-axis flipAT = new AffineTransform(); flipAT.translate(0, pdPage.getBBox().getHeight()); flipAT.scale(1, -1);// w w w.ja v a 2 s.c om // page may be rotated rotateAT = new AffineTransform(); int rotation = pdPage.getRotation(); if (rotation != 0) { PDRectangle mediaBox = pdPage.getMediaBox(); switch (rotation) { case 90: rotateAT.translate(mediaBox.getHeight(), 0); break; case 270: rotateAT.translate(0, mediaBox.getWidth()); break; case 180: rotateAT.translate(mediaBox.getWidth(), mediaBox.getHeight()); break; default: break; } rotateAT.rotate(Math.toRadians(rotation)); } g2d = image.createGraphics(); g2d.setStroke(new BasicStroke(0.1f)); g2d.scale(SCALE, SCALE); setStartPage(page + 1); setEndPage(page + 1); Writer dummy = new OutputStreamWriter(new ByteArrayOutputStream()); writeText(document, dummy); // beads in green g2d.setStroke(new BasicStroke(0.4f)); List<PDThreadBead> pageArticles = pdPage.getThreadBeads(); for (PDThreadBead bead : pageArticles) { PDRectangle r = bead.getRectangle(); GeneralPath p = r .transform(Matrix.getTranslateInstance(-cropBox.getLowerLeftX(), cropBox.getLowerLeftY())); Shape s = flipAT.createTransformedShape(p); s = rotateAT.createTransformedShape(s); g2d.setColor(Color.green); g2d.draw(s); } g2d.dispose(); String imageFilename = filename; int pt = imageFilename.lastIndexOf('.'); imageFilename = imageFilename.substring(0, pt) + "-marked-" + (page + 1) + ".png"; ImageIO.write(image, "png", new File(imageFilename)); }