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:adams.flow.transformer.PDFRenderPages.java

License:Open Source License

/**
 * Executes the flow item.//from  w  ww . j  av a  2 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:airviewer.AIRViewerModel.java

License:Apache License

/**
 * Constructor: Loads the PDF document at the path (file system path).
 *
 * @param path A file system path to a PDF file.
 * @throws IOException If the PDF file cannot be read or does not contain
 * valid PDF data./*  www .j  a  v a2s . c o  m*/
 */
AIRViewerModel(Path path) throws IOException {
    super(PDDocument.load(path.toFile()), "");
    renderer = new PDFRenderer(wrappedDocument);
    AbstractDocumentCommandWrapper.registerCommandFactoryWithName(
            (AbstractDocumentCommandWrapper owner,
                    ArrayList<String> args) -> new MoveSelectedAnnotationDocumentCommand(owner, args),
            "MoveSelectedAnnotation");
    AbstractDocumentCommandWrapper.registerCommandFactoryWithName(
            (AbstractDocumentCommandWrapper owner,
                    ArrayList<String> args) -> new DeleteSelectedAnnotationDocumentCommand(owner, args),
            "DeleteSelectedAnnotation");
    AbstractDocumentCommandWrapper.registerCommandFactoryWithName(
            (AbstractDocumentCommandWrapper owner,
                    ArrayList<String> args) -> new ChangeSelectedTextAnnotationDocumentCommand(owner, args),
            "ChangeSelectedAnnotationText");
}

From source file:ambroafb.general.PDFHelper.java

public PDFHelper(InputStream in) throws IOException {
    doc = PDDocument.load(in);
    rend = new PDFRenderer(doc);
}

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 {/*  w  w  w  .  ja va2s .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./*from ww  w . ja  v  a  2 s .c o  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:com.apache.pdfbox.ocr.tesseract.BadScan.java

License:Apache License

@Test
public void textBadScan() {
    try {/*from   w ww  . j ava2  s  .c  o  m*/
        PDDocument document = PDDocument.load(new File("src/test/resources/samples/scansmpl.pdf"));
        PDFRenderer renderer = new PDFRenderer(document);
        BufferedImage image = renderer.renderImage(0, 3);

        TessBaseAPI api = new TessBaseAPI();
        boolean init = api.init("eng");
        api.setBufferedImage(image);
        String text = api.getUTF8Text();
        System.out.println(text);
        api.end();
        assertEquals(init, true);
        document.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.apache.pdfbox.ocr.tesseract.TessBaseAPITest.java

License:Apache License

@Test
public void textBadScan() {
    try {/*from w  w w .  j ava  2 s. c  om*/
        PDDocument document = PDDocument.load(new File("src/test/resources/samples/scansmpl.pdf"));
        PDFRenderer renderer = new PDFRenderer(document);
        BufferedImage image = renderer.renderImage(0, 3);

        TessBaseAPI api = new TessBaseAPI();
        boolean init = api.init("eng");
        api.setBufferedImage(image);
        String text = api.getUTF8Text();
        System.out.println(text);
        api.end();
        assertEquals(true, true);
        document.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.apache.pdfbox.ocr.tesseract.TessBaseAPITest.java

License:Apache License

@Test
public void testBufferedImage() {
    try {//  w ww .j a  v a2s  .c  o  m
        PDDocument document = PDDocument.load(new File("src/test/resources/samples/pdf1.pdf"));
        PDFRenderer renderer = new PDFRenderer(document);
        BufferedImage image = renderer.renderImage(0, 3);

        TessBaseAPI api = new TessBaseAPI();
        boolean init = api.init("eng");
        api.setBufferedImage(image);
        String text = api.getUTF8Text();
        System.out.println(text);
        api.end();
        assertEquals(init, true);
        document.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.apache.pdfbox.ocr.tesseract.TessBaseAPITest.java

License:Apache License

@Test
public void testByteStream() {
    try {//from w  w  w .  j  a v  a2  s. c om
        PDDocument document = PDDocument.load(new File("src/test/resources/samples/pdf2.pdf"));
        PDFRenderer renderer = new PDFRenderer(document);
        BufferedImage image = renderer.renderImage(0, 3);
        int width = image.getWidth();
        int height = image.getHeight();
        int bpp = 3;
        int bpl = width * 3;

        TessBaseAPI api = new TessBaseAPI();
        byte data[] = api.getByteStream(image);
        boolean init = api.init("eng");
        api.setImage(data, width, height, bpp, bpl);
        String text = api.getUTF8Text();
        System.out.println(text);
        api.end();
        assertEquals(init, true);
        document.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.apache.pdfbox.ocr.tesseract.TessBaseAPITest.java

License:Apache License

@Test
public void testIterator() {
    try {/*from   w ww. j  ava 2 s  .  c om*/
        PDDocument document = PDDocument.load(new File("src/test/resources/samples/pdf3.pdf"));
        PDFRenderer renderer = new PDFRenderer(document);
        BufferedImage image = renderer.renderImage(0, 3);
        TessBaseAPI api = new TessBaseAPI();
        boolean init = api.init("eng");
        api.setBufferedImage(image);
        api.getResultIterator();
        if (api.isResultIteratorAvailable()) {
            do {
                System.out.println(api.getWord().trim());
                String result = api.getBoundingBox();
                System.out.println(result);
            } while (api.resultIteratorNext());
        }
        api.end();
        assertEquals(init, true);
        document.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}