Example usage for org.apache.pdfbox.tools.imageio ImageIOUtil writeImage

List of usage examples for org.apache.pdfbox.tools.imageio ImageIOUtil writeImage

Introduction

In this page you can find the example usage for org.apache.pdfbox.tools.imageio ImageIOUtil writeImage.

Prototype

public static boolean writeImage(BufferedImage image, String formatName, OutputStream output)
        throws IOException 

Source Link

Document

Writes a buffered image to a file using the given image format.

Usage

From source file:at.knowcenter.wag.egov.egiz.pdfbox2.pdf.PDFUtilities.java

License:EUPL

public static float getMaxYPosition(PDDocument pdfDataSource, int page, IPDFVisualObject pdfTable,
        float signatureMarginVertical, float footer_line, ISettings settings) throws IOException {

    PositioningRenderer renderer = new PositioningRenderer(pdfDataSource);
    //BufferedImage bim = renderer.renderImage(page);

    int width = (int) pdfDataSource.getPage(page).getCropBox().getWidth();
    int height = (int) pdfDataSource.getPage(page).getCropBox().getHeight();
    BufferedImage bim = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);

    Graphics2D graphics = bim.createGraphics();
    graphics.setBackground(MAGIC_COLOR);

    renderer.renderPageToGraphics(page, graphics);

    Color bgColor = MAGIC_COLOR;/*from w  w  w  .  j  ava  2  s .c  o m*/

    if ("true".equals(settings.getValue(BG_COLOR_DETECTION))) { //only used if background color should be determined automatically
        bgColor = determineBackgroundColor(bim);
    }

    int yCoord = bim.getHeight() - 1 - (int) footer_line;

    for (int row = yCoord; row >= 0; row--) {
        for (int col = 0; col < bim.getWidth(); col++) {
            int val = bim.getRGB(col, row);
            if (val != bgColor.getRGB()) {
                yCoord = row;
                row = -1;
                break;
            }
        }
    }

    String outFile = settings.getValue(SIG_PLACEMENT_DEBUG_OUTPUT);
    if (outFile != null) {
        ImageIOUtil.writeImage(bim, outFile, 72);
    }
    return yCoord;
}

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 w  w  w. j  ava 2s .com*/
        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.testautomationguru.utility.PDFUtil.java

License:Apache License

/**
* This method saves the each page of the pdf as image
*//*ww w.  ja  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.yiyihealth.util.PDF2Image.java

License:Apache License

/**
 * Infamous main method.//from www  . 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:edu.ist.psu.sagnik.research.pdfbox2playground.javatest.ExtractImages.java

License:Apache License

/**
 * Writes the image to a file with the filename + an appropriate suffix, like "Image.jpg".
 * The suffix is automatically set by the
 * @param filename the filename/*from ww w  . j  ava 2s  .c om*/
 * @throws IOException When somethings wrong with the corresponding file.
 */
private void write2file(PDImage pdImage, String filename, boolean directJPEG) throws IOException {
    String suffix = pdImage.getSuffix();
    if (suffix == null) {
        suffix = "png";
    }

    FileOutputStream out = null;
    try {
        out = new FileOutputStream(filename + "." + suffix);
        BufferedImage image = pdImage.getImage();
        if (image != null) {
            if ("jpg".equals(suffix)) {
                String colorSpaceName = pdImage.getColorSpace().getName();
                if (directJPEG || PDDeviceGray.INSTANCE.getName().equals(colorSpaceName)
                        || PDDeviceRGB.INSTANCE.getName().equals(colorSpaceName)) {
                    // RGB or Gray colorspace: get and write the unmodifiedJPEG stream
                    //InputStream data = pdImage.getColor.getPartiallyFilteredStream(JPEG);
                    //IOUtils.copy(data, out);
                    //IOUtils.closeQuietly(data);
                    BufferedImage b = pdImage.getImage();
                    ImageIOUtil.writeImage(b, "jpg", out);
                } else {
                    // for CMYK and other "unusual" colorspaces, the JPEG will be converted
                    ImageIOUtil.writeImage(image, suffix, out);
                }
            } else {
                ImageIOUtil.writeImage(image, suffix, out);
            }
        }
        out.flush();
    } finally {
        if (out != null) {
            out.close();
        }
    }
}

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);
    }/* ww  w  .j a  va  2 s  .  co  m*/
    document.close();
}

From source file:jgnash.PDFBoxTableTest.java

License:Open Source License

@Test
void basicReportTest() throws IOException {

    Path tempPath = null;//from  ww  w. j  a va2 s.co m
    Path tempRasterPath = null;

    try (final Report report = new SimpleReport()) {
        tempPath = Files.createTempFile("pdfTest", ".pdf");
        tempRasterPath = Files.createTempFile("pdfTest", ".png");

        final float padding = 2.5f;

        report.setTableFont(PDType1Font.COURIER);
        report.setHeaderFont(PDType1Font.HELVETICA_BOLD);
        report.setCellPadding(padding);
        report.setBaseFontSize(9);

        final PageFormat pageFormat = ReportPrintFactory.getDefaultPage();
        pageFormat.setOrientation(PageFormat.LANDSCAPE);
        report.setPageFormat(pageFormat);

        report.setFooterFont(PDType1Font.TIMES_ITALIC);
        report.setEllipsis("");

        assertEquals(1, Report.getGroups(new BasicTestReport()).size());
        assertEquals(80, ((Report.GroupInfo) Report.getGroups(new BasicTestReport()).toArray()[0]).rows);

        report.addTable(new BasicTestReport(), "Test Report");
        report.addFooter();

        report.saveToFile(tempPath);

        assertTrue(report.isLandscape());
        assertEquals(padding, report.getCellPadding());
        assertTrue(Files.exists(tempPath));

        // Create a PNG file
        final BufferedImage bim = report.renderImage(0, 300);
        ImageIOUtil.writeImage(bim, tempRasterPath.toString(), 300);

        assertTrue(Files.exists(tempRasterPath));

    } catch (final IOException e) {
        e.printStackTrace();
    } finally {
        if (tempPath != null) {
            Files.deleteIfExists(tempPath);
        }

        if (tempRasterPath != null) {
            Files.deleteIfExists(tempRasterPath);
        }
    }
}

From source file:jgnash.PDFBoxTableTest.java

License:Open Source License

@Test
void crossTabReportTest() throws IOException {

    Path tempPath = null;/*from   w  ww.  j ava 2  s  .c  o  m*/
    Path tempRasterPath = null;

    try (final Report report = new SimpleReport()) {
        tempPath = Files.createTempFile("pdfTest", ".pdf");
        tempRasterPath = Files.createTempFile("pdfTest", ".png");

        final float padding = 2.5f;

        report.setTableFont(PDType1Font.COURIER);
        report.setHeaderFont(PDType1Font.HELVETICA_BOLD);
        report.setCellPadding(padding);
        report.setBaseFontSize(9);
        report.setForceGroupPagination(true);

        final PageFormat pageFormat = (PageFormat) report.getPageFormat().clone();
        pageFormat.setOrientation(PageFormat.LANDSCAPE);
        report.setPageFormat(pageFormat);

        report.setFooterFont(PDType1Font.TIMES_ITALIC);
        report.setEllipsis("");

        assertEquals(2, Report.getGroups(new CrossTabTestReport()).size());
        assertEquals(40, ((Report.GroupInfo) Report.getGroups(new CrossTabTestReport()).toArray()[0]).rows);

        report.addTable(new CrossTabTestReport(), "Test Report");
        report.addFooter();

        report.saveToFile(tempPath);

        assertTrue(report.isLandscape());
        assertEquals(padding, report.getCellPadding());
        assertTrue(Files.exists(tempPath));

        // Create a PNG file
        final BufferedImage bim = report.renderImage(0, 300);
        ImageIOUtil.writeImage(bim, tempRasterPath.toString(), 300);

        assertTrue(Files.exists(tempRasterPath));

    } catch (final IOException e) {
        e.printStackTrace();
    } finally {
        if (tempPath != null) {
            Files.deleteIfExists(tempPath);
        }

        if (tempRasterPath != null) {
            Files.deleteIfExists(tempRasterPath);
        }
    }
}

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 ww w .j  a  v  a2s.  co m*/
    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  w w .  j a  va2s  .c om*/
 * 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;
}