Example usage for org.apache.pdfbox.rendering PDFRenderer renderImageWithDPI

List of usage examples for org.apache.pdfbox.rendering PDFRenderer renderImageWithDPI

Introduction

In this page you can find the example usage for org.apache.pdfbox.rendering PDFRenderer renderImageWithDPI.

Prototype

public BufferedImage renderImageWithDPI(int pageIndex, float dpi) throws IOException 

Source Link

Document

Returns the given page as an RGB image at the given DPI.

Usage

From source file:adams.flow.transformer.PDFRenderPages.java

License:Open Source License

/**
 * Executes the flow item./*from w  ww  . j a  va2  s  . c o  m*/
 *
 * @return      null if everything is fine, otherwise error message
 */
@Override
protected String doExecute() {
    String result;
    File file;
    PDDocument doc;
    BufferedImageContainer cont;
    PDFRenderer renderer;
    BufferedImage img;
    MessageCollection errors;

    result = null;

    // get file
    if (m_InputToken.getPayload() instanceof File)
        file = (File) m_InputToken.getPayload();
    else
        file = new PlaceholderFile((String) m_InputToken.getPayload());

    doc = PDFBox.load(file);
    if (doc != null) {
        if (isLoggingEnabled())
            getLogger().info("Rendering pages from '" + file + "'");
        m_Pages.setMax(doc.getNumberOfPages());
        renderer = new PDFRenderer(doc);
        errors = new MessageCollection();
        for (int page : m_Pages.getIntIndices()) {
            if (isLoggingEnabled())
                getLogger().info("Rendering page #" + (page + 1));
            try {
                img = renderer.renderImageWithDPI(page, m_DPI);
                cont = new BufferedImageContainer();
                cont.setImage(img);
                cont.getReport().setStringValue("File", file.getAbsolutePath());
                cont.getReport().setNumericValue("Page", (page + 1));
                m_Images.add(cont);
            } catch (Exception e) {
                errors.add(handleException("Failed to render page #" + (page + 1) + " from " + file, e));
            }
        }
        if (!errors.isEmpty())
            result = errors.toString();
    } else {
        result = "Failed to load PDF document: " + file;
    }

    return result;
}

From source file:com.fcore.base.fileSystem.utils.FileUtil.java

/**
 * PDF to Image(png)/*from ww 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:de.redsix.pdfcompare.PdfComparator.java

License:Apache License

public static ImageWithDimension renderPageAsImage(final PDDocument document,
        final PDFRenderer expectedPdfRenderer, final int pageIndex) throws IOException {
    final BufferedImage bufferedImage = expectedPdfRenderer.renderImageWithDPI(pageIndex, DPI);
    final PDRectangle mediaBox = document.getPage(pageIndex).getMediaBox();
    return new ImageWithDimension(bufferedImage, mediaBox.getWidth(), mediaBox.getHeight());
}

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);
    }/*from   ww  w .  j a  v a2  s  .co 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:firmaapp.MainFormController.java

@FXML
void workOrderDateButtonAction(ActionEvent event) throws IOException {
    LocalDate date = workOrderDatePicker.getValue();
    ProductMySQL prodMySQL = new ProductMySQL();
    String numOfWO = "";
    numOfWO = prodMySQL.createWorkOrder(Date.from(date.atStartOfDay(ZoneId.systemDefault()).toInstant()));

    WorkOrderPDF woPDF = new WorkOrderPDF(numOfWO,
            Date.from(date.atStartOfDay(ZoneId.systemDefault()).toInstant()), RootController.workOrderProducts,
            RootController.workOrderSupplies);
    woPDF.createWorkOrder();//w  w  w.j  a  v  a2s . c o  m

    DateFormat df = new SimpleDateFormat("yy"); // Just the year, with 2 digits
    String formatedDate = df.format(woPDF.getDateOfWorkOrder());

    File file = new File("pdf_docs" + File.separator + "work_orders" + File.separator + "work_order_"
            + woPDF.getNumOfWorkOrder().split("/")[0] + "_" + formatedDate + ".pdf");

    PDDocument doc = PDDocument.load(file);
    PDFRenderer renderer = new PDFRenderer(doc);
    renderer.renderImageWithDPI(0, 300);
    //BufferedImage image = renderer.renderImage(0);
    BufferedImage image = renderer.renderImageWithDPI(0, 300);
    ImageIO.write(image, "PNG", new File("pdf_docs" + File.separator + "work_orders_picture" + File.separator
            + "work_order_" + woPDF.getNumOfWorkOrder().split("/")[0] + "_" + formatedDate + ".png"));
    doc.close();

    WorkOrderMySQL woMySQL = new WorkOrderMySQL();
    ArrayList<WorkOrder> orders = woMySQL.getAllWokrOrders();
    RootController.allWorkOrders = orders;
    Collections.sort(RootController.allWorkOrders, new WorkOrderCompare());
    dataWorkOrders.clear();
    for (WorkOrder w : RootController.allWorkOrders) {
        dataWorkOrders.add(w);
    }
}

From source file:org.geomajas.plugin.printing.document.DefaultDocumentTest.java

License:Open Source License

@Test
public void testToImage() throws Exception {
    testRender();/*from  w w  w .j  av a2  s  . co m*/
    PDDocument pdf = PDDocument.load(new File("target/test.pdf"), true);
    PDFRenderer renderer = new PDFRenderer(pdf);
    BufferedImage bufferedImage = renderer.renderImageWithDPI(0, 144);
    pdf.close();
    ImageIO.write(bufferedImage, "PNG", new File("target/test.png"));
}

From source file:org.geomajas.plugin.printing.document.SinglePageDocument.java

License:Open Source License

private void writeDocument(OutputStream outputStream, Format format, int dpi)
        throws IOException, DocumentException, PrintingException {
    if (format == Format.PDF) {
        baos.writeTo(outputStream);//from   ww w  .java  2  s  . c  o  m
    } else {
        PDDocument pdf = PDDocument.load(new ByteArrayInputStream(baos.toByteArray()), true);
        PDFRenderer renderer = new PDFRenderer(pdf);
        BufferedImage bufferedImage = renderer.renderImageWithDPI(0, dpi);
        pdf.close();
        if (format == Format.PNG) {
            final String formatName = format.getExtension();
            for (Iterator<ImageWriter> iw = ImageIO.getImageWritersByFormatName(formatName); iw.hasNext();) {
                ImageWriter writer1 = iw.next();
                ImageWriteParam writeParam = writer1.getDefaultWriteParam();
                ImageTypeSpecifier typeSpecifier = ImageTypeSpecifier
                        .createFromBufferedImageType(BufferedImage.TYPE_INT_ARGB);
                IIOMetadata metadata = writer1.getDefaultImageMetadata(typeSpecifier, writeParam);
                if (metadata.isReadOnly() || !metadata.isStandardMetadataFormatSupported()) {
                    continue;
                }

                setDPI(metadata);
                // Write bufferedImage to outputStream
                final ImageOutputStream stream = ImageIO.createImageOutputStream(outputStream);
                try {
                    writer1.setOutput(stream);
                    writer1.write(metadata, new IIOImage(bufferedImage, null, metadata), writeParam);
                } finally {
                    stream.flush();
                    stream.close();
                }
                break;
            }
        } else {
            ImageIO.write(bufferedImage, format.getExtension(), outputStream);
        }

    }
}

From source file:pdf.WorkOrderPDF.java

public void createWorkOrderPNG(String path) throws IOException {
    File file = new File(path);
    PDDocument doc = PDDocument.load(file);
    PDFRenderer renderer = new PDFRenderer(doc);
    renderer.renderImageWithDPI(0, 600);
    BufferedImage image = renderer.renderImage(0);
    SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy.");
    ImageIO.write(image, "PNG", new File("pdf_docs\\work_orders_picture\\" + "wopic-"
            + numOfWorkOrder.split("\\/")[0] + "_" + numOfWorkOrder.split("/")[1] + ".pdf"));
    doc.close();/*from w ww  .ja  v a  2  s .  co m*/

}

From source file:src.view.displayer.PageDisplayer.java

/**
 * Transforme la page actuelle en image//from   w ww.ja  v  a2  s  .c  o m
 *
 * @param imagePDF
 * @param pageIndex
 */
public static void setImage(ImageView imagePDF, int pageIndex, DocFile docFile) {
    try {
        PDFRenderer renderer = new PDFRenderer(docFile.getDocument());

        // Transformation de la page en image
        BufferedImage bufferedImage = renderer.renderImageWithDPI(pageIndex, PDF_DISPLAY_DPI);
        WritableImage image = SwingFXUtils.toFXImage(bufferedImage, null);
        imagePDF.setImage(image);

        imagePDF.setId("imagePDF");
        imagePDF.setStyle("-fx-effect: dropshadow(three-pass-box, black, 100, 0, 0, 0);");

        // On met l'image sous la mme forme (paysage, portrait) que la page
        imagePDF.setFitWidth(bufferedImage.getWidth() * docFile.getZoom() * INITIAL_SCALE / 100);
        imagePDF.setFitHeight(bufferedImage.getHeight() * docFile.getZoom() * INITIAL_SCALE / 100);
    } catch (IOException e) {
        System.out.println(e.toString());
    }
}