Example usage for org.apache.pdfbox.rendering ImageType ARGB

List of usage examples for org.apache.pdfbox.rendering ImageType ARGB

Introduction

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

Prototype

ImageType ARGB

To view the source code for org.apache.pdfbox.rendering ImageType ARGB.

Click Source Link

Document

Alpha, Red, Green, Blue

Usage

From source file:at.gv.egiz.pdfas.lib.impl.signing.pdfbox2.PADESPDFBOXSigner.java

License:EUPL

@Override
public Image generateVisibleSignaturePreview(SignParameter parameter, java.security.cert.X509Certificate cert,
        int resolution, OperationStatus status, RequestedSignature requestedSignature) throws PDFASError {
    try {/*from ww  w.  j  a va  2  s . c  o  m*/
        PDFBOXObject pdfObject = (PDFBOXObject) status.getPdfObject();

        PDDocument origDoc = new PDDocument();
        origDoc.addPage(new PDPage(PDRectangle.A4));
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        origDoc.save(baos);
        baos.close();

        pdfObject.setOriginalDocument(new ByteArrayDataSource(baos.toByteArray()));

        SignatureProfileSettings signatureProfileSettings = TableFactory
                .createProfile(requestedSignature.getSignatureProfileID(), pdfObject.getStatus().getSettings());

        // create Table describtion
        Table main = TableFactory.createSigTable(signatureProfileSettings, MAIN, pdfObject.getStatus(),
                requestedSignature);

        IPDFStamper stamper = StamperFactory.createDefaultStamper(pdfObject.getStatus().getSettings());

        IPDFVisualObject visualObject = stamper.createVisualPDFObject(pdfObject, main);

        SignatureProfileConfiguration signatureProfileConfiguration = pdfObject.getStatus()
                .getSignatureProfileConfiguration(requestedSignature.getSignatureProfileID());

        String signaturePosString = signatureProfileConfiguration.getDefaultPositioning();
        PositioningInstruction positioningInstruction = null;
        if (signaturePosString != null) {
            positioningInstruction = Positioning.determineTablePositioning(new TablePos(signaturePosString), "",
                    origDoc, visualObject, pdfObject.getStatus().getSettings());
        } else {
            positioningInstruction = Positioning.determineTablePositioning(new TablePos(), "", origDoc,
                    visualObject, pdfObject.getStatus().getSettings());
        }

        origDoc.close();

        SignaturePositionImpl position = new SignaturePositionImpl();
        position.setX(positioningInstruction.getX());
        position.setY(positioningInstruction.getY());
        position.setPage(positioningInstruction.getPage());
        position.setHeight(visualObject.getHeight());
        position.setWidth(visualObject.getWidth());

        requestedSignature.setSignaturePosition(position);

        PDFAsVisualSignatureProperties properties = new PDFAsVisualSignatureProperties(
                pdfObject.getStatus().getSettings(), pdfObject, (PdfBoxVisualObject) visualObject,
                positioningInstruction, signatureProfileSettings);

        properties.buildSignature();
        PDDocument visualDoc;
        synchronized (PDDocument.class) {
            visualDoc = PDDocument.load(properties.getVisibleSignature());
        }
        // PDPageable pageable = new PDPageable(visualDoc);

        PDPage firstPage = visualDoc.getDocumentCatalog().getPages().get(0);

        float stdRes = 72;
        float targetRes = resolution;
        float factor = targetRes / stdRes;

        int targetPageNumber = 0;//TODO: is this always the case
        PDFRenderer pdfRenderer = new PDFRenderer(visualDoc);
        BufferedImage outputImage = pdfRenderer.renderImageWithDPI(targetPageNumber, targetRes, ImageType.ARGB);

        //BufferedImage outputImage = firstPage.convertToImage(BufferedImage.TYPE_4BYTE_ABGR, (int) targetRes);

        BufferedImage cutOut = new BufferedImage((int) (position.getWidth() * factor),
                (int) (position.getHeight() * factor), BufferedImage.TYPE_4BYTE_ABGR);

        Graphics2D graphics = (Graphics2D) cutOut.getGraphics();

        graphics.drawImage(outputImage, 0, 0, cutOut.getWidth(), cutOut.getHeight(), (int) (1 * factor),
                (int) (outputImage.getHeight() - ((position.getHeight() + 1) * factor)),
                (int) ((1 + position.getWidth()) * factor), (int) (outputImage.getHeight()
                        - ((position.getHeight() + 1) * factor) + (position.getHeight() * factor)),
                null);
        return cutOut;
    } catch (PdfAsException e) {
        logger.warn("PDF-AS  Exception", e);
        throw ErrorExtractor.searchPdfAsError(e, status);
    } catch (Throwable e) {
        logger.warn("Unexpected Throwable  Exception", e);
        throw ErrorExtractor.searchPdfAsError(e, status);
    }
}

From source file:com.ackpdfbox.app.PDFToImage.java

License:Apache License

/**
 * Infamous main method.//  w  w w. j  a va 2s  .  c  om
 *
 * @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:com.yiyihealth.util.PDF2Image.java

License:Apache License

/**
 * Infamous main method.//from   w w  w.j  av  a  2  s  .co m
 *
 * @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:model.util.pdf.PDFUtils.java

License:Apache License

/**
 * Infamous main method.//from  w ww . j av a 2 s . co  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:org.haplo.component.pdfbox.PDF.java

License:Mozilla Public License

/**
 * Render the PDF as an image//from ww w .j ava  2 s  .  com
 */
public void render(String outFilename, String outFormat, int page, int outWidth, int outHeight)
        throws IOException {
    BufferedImage img = null;
    try {
        PDPage pdfPage = this.pdf.getPage(page - 1);
        PDRectangle cropBox = pdfPage.getCropBox();
        int pageWidth = (int) cropBox.getWidth();
        int pageHeight = (int) cropBox.getHeight();
        if (pageHeight <= 0) {
            pageHeight = 1;
        }

        int resolution = (96 * outHeight) / pageHeight;
        if (resolution < 4) {
            resolution = 4;
        }
        if (resolution > 1000) {
            resolution = 1000;
        }
        if (outHeight < 100 || outWidth < 100) {
            resolution *= 2;
        }

        PDFRenderer pdfRenderer = new PDFRenderer(this.pdf);

        img = pdfRenderer.renderImageWithDPI(page - 1, resolution,
                outFormat.equals("png") ? ImageType.ARGB : ImageType.RGB);
    } catch (Exception e) {
        Logger.getLogger("org.haplo.app").error("Error rendering PDF: " + e.toString());
        throw new RuntimeException("Couldn't render PDF page", e);
    }

    // Did it convert? (most likely cause of null return is requested a page which didn't exist)
    if (img == null) {
        throw new RuntimeException("Failed to render PDF - did the requested page exist?");
    }

    // Scale the image to the right size
    BufferedImage original = null;
    if (img.getWidth() != outWidth || img.getHeight() != outHeight) {
        original = img;
        Image scaled = img.getScaledInstance(outWidth, outHeight, Image.SCALE_SMOOTH);
        img = new BufferedImage(outWidth, outHeight, original.getType());
        Graphics2D graphics = img.createGraphics();
        graphics.setBackground(Color.WHITE);
        graphics.clearRect(0, 0, outWidth, outHeight);
        graphics.drawImage(scaled, 0, 0, null);
        graphics.dispose();
        scaled.flush();
    }

    // Write the image to a file
    ImageIO.write(img, outFormat, new File(outFilename));

    // Free resources
    img.flush();
    if (original != null) {
        original.flush();
    }
}