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

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

Introduction

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

Prototype

public PDFRenderer(PDDocument document) 

Source Link

Document

Creates a new PDFRenderer.

Usage

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();//from  w  w  w. ja v  a2  s .co  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: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 {//from w  ww. j  a  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 w w w.ja  v a  2  s .  com
            //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   www  .ja  va  2s  .com
                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:idp.pdf_converter.java

public static void pdf_converter(File file) throws IOException {
    PDDocument document = PDDocument.load(file);
    PDFRenderer pdfRenderer = new PDFRenderer(document);
    String path = System.getProperty("user.dir") + "\\src\\main\\temp\\images\\";
    for (int page = 0; page < document.getNumberOfPages(); ++page) {
        BufferedImage bim = pdfRenderer.renderImageWithDPI(page, 300, ImageType.GRAY);
        ImageIOUtil.writeImage(bim, path + file.getName() + "-" + (page + 1) + ".png", 300);
    }/*from w  ww.  j a  v a2 s.c  o  m*/
    document.close();
}

From source file:jgnash.report.pdf.Report.java

License:Open Source License

/**
 * Renders the PDF report to a raster image
 *
 * @param pageIndex page index//w w  w  .j  av a  2 s .c  om
 * @param dpi       DPI for the image
 * @return the image
 * @throws IOException IO exception
 */
public BufferedImage renderImage(final int pageIndex, final int dpi) throws IOException {
    final PDFRenderer pdfRenderer = new PDFRenderer(pdfDocument);
    return pdfRenderer.renderImageWithDPI(pageIndex, dpi, ImageType.RGB);
}

From source file:merge_split.MergeSplit.java

License:Apache License

private void ConvertButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ConvertButtonActionPerformed
    PDDocument document = null;//from  w ww . j a v a  2 s. com
    try {
        document = PDDocument.load(new File((String) ConvertFileField.getText()), convertcode);
    } catch (IOException ex) {
        JOptionPane.showMessageDialog(null, "Problem opening pdf.", "Problem opening pdf",
                JOptionPane.WARNING_MESSAGE);
    }
    TreeSet tree = findPages((String) ConvertPagesField.getText());

    PDFRenderer pdfRenderer = new PDFRenderer(document);
    for (int page = 0; page < document.getNumberOfPages(); ++page) {
        BufferedImage bim = null;
        try {
            bim = pdfRenderer.renderImageWithDPI(page, 300, ImageType.RGB);
        } catch (IOException ex) {
            JOptionPane.showMessageDialog(null, "Problem rendering image.", "Problem rendering image",
                    JOptionPane.WARNING_MESSAGE);

        }

        // suffix in filename will be used as the file format
        String destination = ConvertDestinationField.getText() + "\\" + ConvertNameField.getText();
        String image = ".png";
        if (pngbutton.isSelected()) {
            image = ".png";
        } else if (bmpbutton.isSelected()) {
            image = ".bmp";
        } else if (gifbutton.isSelected()) {
            image = ".gif";
        } else if (jpgbutton.isSelected()) {
            image = ".jpg";
        }
        try {
            if (tree.contains(page + 1)) {

                ImageIOUtil.writeImage(bim, destination + "-" + (page + 1) + image, 300);
            }
        } catch (IOException ex) {
            JOptionPane.showMessageDialog(null, "Problem output image.", "Problem output image",
                    JOptionPane.WARNING_MESSAGE);
            java.util.logging.Logger.getLogger(MergeSplit.class.getName()).log(java.util.logging.Level.SEVERE,
                    null, ex);

        }
    }
    try {
        document.close();
    } catch (IOException ex) {
        Logger.getLogger(MergeSplit.class.getName()).log(Level.SEVERE, null, ex);

    }
}

From source file:model.util.pdf.PDFUtils.java

License:Apache License

/**
 * Infamous main method.//  w  ww .j a va  2 s . c o  m
 * Adapted by Julius Huelsmann.
 * 
 * @author Ben Litchfield
 *
 * @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 BufferedImage pdf2image(final String[] _parameters) throws IOException {

    // suppress the Dock icon on OS X if called from outside
    // the paint - project.
    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 < _parameters.length; i++) {
        if (_parameters[i].equals(PASSWORD)) {
            i++;
            if (i >= _parameters.length) {
                usage();
            }
            password = _parameters[i];
        } else if (_parameters[i].equals(START_PAGE)) {
            i++;
            if (i >= _parameters.length) {
                usage();
            }
            startPage = Integer.parseInt(_parameters[i]);
        } else if (_parameters[i].equals(END_PAGE)) {
            i++;
            if (i >= _parameters.length) {
                usage();
            }
            endPage = Integer.parseInt(_parameters[i]);
        } else if (_parameters[i].equals(PAGE)) {
            i++;
            if (i >= _parameters.length) {
                usage();
            }
            startPage = Integer.parseInt(_parameters[i]);
            endPage = Integer.parseInt(_parameters[i]);
        } else if (_parameters[i].equals(IMAGE_TYPE) || _parameters[i].equals(FORMAT)) {
            i++;
            imageFormat = _parameters[i];
        } else if (_parameters[i].equals(OUTPUT_PREFIX) || _parameters[i].equals(PREFIX)) {
            i++;
            outputPrefix = _parameters[i];
        } else if (_parameters[i].equals(COLOR)) {
            i++;
            color = _parameters[i];
        } else if (_parameters[i].equals(RESOLUTION) || _parameters[i].equals(DPI)) {
            i++;
            dpi = Integer.parseInt(_parameters[i]);
        } else if (_parameters[i].equals(CROPBOX)) {
            i++;
            cropBoxLowerLeftX = Float.valueOf(_parameters[i]);
            i++;
            cropBoxLowerLeftY = Float.valueOf(_parameters[i]);
            i++;
            cropBoxUpperRightX = Float.valueOf(_parameters[i]);
            i++;
            cropBoxUpperRightY = Float.valueOf(_parameters[i]);
        } else if (_parameters[i].equals(TIME)) {
            showTime = true;
        } else {
            if (pdfFile == null) {
                pdfFile = _parameters[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;) {
                BufferedImage image = renderer.renderImageWithDPI(i, dpi, imageType);
                String fileName = outputPrefix + (i + 1) + "." + imageFormat;
                success &= ImageIOUtil.writeImage(image, fileName, dpi);
                return image;
            }

            // 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();
            }
        }
        return null;
    }
    return null;
}

From source file:model.util.pdf.PDFUtils.java

License:Apache License

public static BufferedImage pdf2image(PDDocument _document, int _pageNumber) {

    int dpi = 0;/*from   w  w  w.ja v  a 2s .co  m*/
    try {
        dpi = Toolkit.getDefaultToolkit().getScreenResolution();
        dpi = 130;
    } catch (HeadlessException e) {
        dpi = 96;
        dpi = 130;
    }
    PDFRenderer renderer = new PDFRenderer(_document);
    BufferedImage image;
    try {
        image = renderer.renderImageWithDPI(_pageNumber, dpi, ImageType.RGB);
        return image;
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return null;
    }

}

From source file:net.betzel.fop.pdf.viewer.FXMLController.java

License:Apache License

private void createImages(FileStreamSources fileStreamSources) {
    if (Platform.isFxApplicationThread()) {
        final Task<List<BufferedImage>> createImagesTask = new Task<List<BufferedImage>>() {
            @Override//from ww w.jav  a2 s .c o  m
            protected List<BufferedImage> call() throws Exception {

                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                List<BufferedImage> bufferedImages = new ArrayList();
                FOUserAgent userAgent = fopFactory.newFOUserAgent();
                userAgent.getEventBroadcaster().addEventListener(fopEventListener);
                Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, userAgent, byteArrayOutputStream);
                Transformer transformer = transformerFactory.newTransformer(fileStreamSources.getXslSource());
                transformer.setErrorListener(xmlTransformErrorListener);
                Result result = new SAXResult(fop.getDefaultHandler());
                transformer.transform(fileStreamSources.getXmlSource(), result);
                FormattingResults foResults = fop.getResults();
                List pageSequences = foResults.getPageSequences();
                for (java.util.Iterator it = pageSequences.iterator(); it.hasNext();) {
                    PageSequenceResults pageSequenceResults = (PageSequenceResults) it.next();
                    logging.appendText("PageSequence "
                            + (String.valueOf(pageSequenceResults.getID()).length() > 0
                                    ? pageSequenceResults.getID()
                                    : "<no id>")
                            + " generated " + pageSequenceResults.getPageCount() + " pages.\n");
                }
                try (PDDocument pdDocument = PDDocument
                        .load(new ByteArrayInputStream(byteArrayOutputStream.toByteArray()))) {
                    PDFRenderer pdfRenderer = new PDFRenderer(pdDocument);
                    int pageCounter = 0;
                    for (PDPage pdPage : pdDocument.getPages()) {
                        bufferedImages.add(pdfRenderer.renderImageWithDPI(pageCounter, 150, ImageType.RGB));
                        pageCounter++;
                    }
                }
                return bufferedImages;
            }
        };
        createImagesTask.setOnSucceeded((WorkerStateEvent event) -> {
            Platform.runLater(() -> {
                images.clear();
                images.addAll(createImagesTask.getValue());
            });
        });
        createImagesTask.setOnFailed((WorkerStateEvent event) -> {
            Platform.runLater(() -> {
                scanProgressDialog.close();
                logging.appendText("Error creating images from PDF\n");
                reentrantLock.unlock();
                images.clear();
            });
        });
        backgoundExecutor.submit(createImagesTask);
    }
}