Example usage for org.apache.pdfbox.pdmodel PDDocument load

List of usage examples for org.apache.pdfbox.pdmodel PDDocument load

Introduction

In this page you can find the example usage for org.apache.pdfbox.pdmodel PDDocument load.

Prototype

public static PDDocument load(byte[] input) throws IOException 

Source Link

Document

Parses a PDF.

Usage

From source file:com.liferay.portlet.documentlibrary.util.LiferayPDFBoxConverter.java

License:Open Source License

public void generateImagesPB() throws Exception {
    PDDocument pdDocument = null;//  w  ww.j a  v  a 2 s  .c  o m

    try {
        pdDocument = PDDocument.load(_inputFile);

        PDDocumentCatalog pdDocumentCatalog = pdDocument.getDocumentCatalog();

        PDFRenderer pdfRenderer = new PDFRenderer(pdDocument);

        PDPageTree pdPages = pdDocumentCatalog.getPages();

        for (int i = 0; i < pdPages.getCount(); i++) {
            if (_generateThumbnail && (i == 0)) {
                _generateImagesPB(pdfRenderer, i, _thumbnailFile, _thumbnailExtension);
            }

            if (!_generatePreview) {
                break;
            }

            _generateImagesPB(pdfRenderer, i, _previewFiles[i], _extension);
        }
    } finally {
        if (pdDocument != null) {
            pdDocument.close();
        }
    }
}

From source file:com.liferay.portlet.documentlibrary.util.PDFProcessorImpl.java

License:Open Source License

private void _generateImagesPB(FileVersion fileVersion, InputStream inputStream) throws Exception {

    boolean generatePreview = _isGeneratePreview(fileVersion);
    boolean generateThumbnail = _isGenerateThumbnail(fileVersion);

    PDDocument pdDocument = null;/*from  www.j  av a 2  s.  c  om*/

    try {
        pdDocument = PDDocument.load(inputStream);

        PDDocumentCatalog pdDocumentCatalog = pdDocument.getDocumentCatalog();

        List<PDPage> pdPages = pdDocumentCatalog.getAllPages();

        for (int i = 0; i < pdPages.size(); i++) {
            PDPage pdPage = pdPages.get(i);

            if (generateThumbnail && (i == 0)) {
                _generateImagesPB(fileVersion, pdPage, i);

                if (_log.isInfoEnabled()) {
                    _log.info("PDFBox generated a thumbnail for " + fileVersion.getFileVersionId());
                }
            }

            if (!generatePreview) {
                break;
            }

            _generateImagesPB(fileVersion, pdPage, i + 1);
        }

        if (_log.isInfoEnabled() && generatePreview) {
            _log.info("PDFBox generated " + getPreviewFileCount(fileVersion) + " preview pages for "
                    + fileVersion.getFileVersionId());
        }
    } finally {
        if (pdDocument != null) {
            pdDocument.close();
        }
    }
}

From source file:com.lp.server.system.ejbfac.SystemFacBean.java

License:Open Source License

public byte[][] konvertierePDFFileInEinzelneBilder(String pdfFile, int resolution) {
    PDDocument document = null;//from w w  w.  j a va  2s .  com
    byte[][] oBilder = null;
    try {
        document = PDDocument.load(pdfFile);
        List pages = document.getDocumentCatalog().getAllPages();

        oBilder = new byte[pages.size()][];

        for (int i = 0; i < pages.size(); i++) {
            PDPage page = (PDPage) pages.get(i);
            BufferedImage image = page.convertToImage(BufferedImage.TYPE_INT_RGB, resolution);
            oBilder[i] = Helper.imageToByteArray(image);
        }
    } catch (IOException e) {
        e.printStackTrace();
        throw new EJBExceptionLP(EJBExceptionLP.FEHLER, e.getMessage());

    } finally {
        if (document != null) {

            try {
                document.close();
            } catch (IOException e) {
                e.printStackTrace();
                throw new EJBExceptionLP(EJBExceptionLP.FEHLER, e.getMessage());

            }
        }

    }
    return oBilder;
}

From source file:com.mirth.connect.connectors.doc.DocumentDispatcher.java

License:Open Source License

private void encryptPDF(InputStream inputStream, OutputStream outputStream, String password) throws Exception {
    PDDocument document = null;/*w  ww  .  ja v a  2 s. c  o  m*/

    try {
        document = PDDocument.load(inputStream);

        AccessPermission accessPermission = new AccessPermission();
        accessPermission.setCanAssembleDocument(false);
        accessPermission.setCanExtractContent(true);
        accessPermission.setCanExtractForAccessibility(false);
        accessPermission.setCanFillInForm(false);
        accessPermission.setCanModify(false);
        accessPermission.setCanModifyAnnotations(false);
        accessPermission.setCanPrint(true);
        accessPermission.setCanPrintDegraded(true);

        String ownerPassword = System.currentTimeMillis() + "+" + Runtime.getRuntime().freeMemory() + "+"
                + (ownerPasswordSeq++);
        StandardProtectionPolicy policy = new StandardProtectionPolicy(ownerPassword, password,
                accessPermission);
        policy.setEncryptionKeyLength(128);
        document.protect(policy);

        document.save(outputStream);
    } catch (Exception e) {
        throw e;
    } finally {
        if (document != null) {
            document.close();
        }
    }
}

From source file:com.mycompany.mavenproject1.ragaiproject.RagaiGUI.java

private void loadFile(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_loadFile
    // TODO add your handling code here:
    String filePath;/*  ww  w .  j  a v  a 2s  .c o m*/
    List<File> fileList = new ArrayList<File>();
    files = null;
    columnHeaders = null;
    clearTextArea(selectedFiles);
    ((DefaultListModel) (jList1.getModel())).clear();
    int returnVal = fc.showOpenDialog(jLabel1);
    if (returnVal == JFileChooser.APPROVE_OPTION) {
        //File[]files = fc.getSelectedFiles();
        files = fc.getSelectedFiles();
        for (File file : files) {
            selectedFiles.append(file.getName() + "\n");
        }
        for (int i = 0; i < files.length; i++) {
            filePath = files[i].getAbsolutePath();
            fileList.add(new File(filePath));
        }
        //String filePath = files[0].getAbsolutePath();
        // File file = new File(filePath);
        PDDocument formatterPDF = null;

        try {
            formatterPDF = PDDocument.load(fileList.get(0));
            //PDFManipulation formatter = new PDFManipulation();
            for (int i = 0; i < files.length; i++) {
                pdfList.add(PDDocument.load(fileList.get(i)));
            }
            columnHeaders = formatter.getFieldNames(formatterPDF, jList1);
        } catch (IOException ex) {
            System.out.println("PDF Failed to Load");
        }

    }
}

From source file:com.mycompany.mavenproject1.ragaiproject.RagaiGUI.java

private void convertToExcel(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_convertToExcel
    // TODO add your handling code here:

    System.out.println("files = " + Arrays.toString(files));

    String filePath = files[0].getAbsolutePath();
    File file = new File(filePath);
    PDDocument pdf1 = null;//  w  w w  . j av  a  2s . c o  m
    List<String> selectedFields = jList1.getSelectedValuesList();
    try {
        pdf1 = PDDocument.load(file);

        //PDFManipulation exporter = new PDFManipulation();
        //pdfArray[0] = exporter.powderMETForm(pdf1);
        formatter.convert(pdfList, selectedFields, outputFileName.getText());
    } catch (IOException ex) {
        Logger.getLogger(RagaiGUI.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.mycompany.textextract.textExtract.java

public static void main(String[] args) throws IOException {
    File folder = new File(args[0]);
    File target = new File(args[1]);
    String[] files = folder.list();
    for (String filename : files) {
        if (new File(filename).isFile() && !Arrays.asList(target.list()).contains(filename + ".txt")) {
            try {
                PDDocument doc = PDDocument.load(folder.getAbsolutePath() + "/" + filename);
                PDFTextStripper strip = new PDFTextStripper();
                PrintWriter writer = new PrintWriter(target.getAbsolutePath() + "/" + filename + ".txt",
                        "UTF-8");
                writer.print(strip.getText(doc));
                doc.close();/*w  ww .  j a  va2s .c o  m*/
                writer.close();
            } catch (Exception e) {
                System.out.println("writing failed-" + e.toString());
            }
        }
    }
}

From source file:com.ning.billing.recurly.TestRecurlyClient.java

License:Apache License

@Test(groups = "integration")
public void testCreateInvoiceAndRetrieveInvoicePdf() throws Exception {
    final Account accountData = TestUtils.createRandomAccount();

    PDDocument pdDocument = null;//from w ww . java 2 s . c  o m
    try {

        // Create a user
        final Account account = recurlyClient.createAccount(accountData);

        // Create an Adjustment
        final Adjustment a = new Adjustment();
        a.setUnitAmountInCents(150);
        a.setCurrency(CURRENCY);

        final Adjustment createdA = recurlyClient.createAccountAdjustment(accountData.getAccountCode(), a);

        // Post an invoice/invoice the adjustment
        final Invoice invoiceData = new Invoice();
        invoiceData.setCollectionMethod("manual");
        invoiceData.setLineItems(null);
        final Invoice invoice = recurlyClient.postAccountInvoice(accountData.getAccountCode(), invoiceData)
                .getChargeInvoice();
        Assert.assertNotNull(invoice);

        InputStream pdfInputStream = recurlyClient.getInvoicePdf(invoice.getId());
        Assert.assertNotNull(pdfInputStream);

        pdDocument = PDDocument.load(pdfInputStream);
        String pdfString = new PDFTextStripper().getText(pdDocument);

        Assert.assertNotNull(pdfString);
        Assert.assertTrue(pdfString.contains("Invoice # " + invoice.getId()));
        Assert.assertTrue(pdfString.contains("Subtotal $" + 1.5));
        // Attempt to close the invoice
        final Invoice closedInvoice = recurlyClient.markInvoiceSuccessful(invoice.getId());
        Assert.assertEquals(closedInvoice.getState(), "paid", "Invoice not closed successfully");

    } finally {
        if (pdDocument != null) {
            pdDocument.close();
        }
        // Close the account
        recurlyClient.closeAccount(accountData.getAccountCode());
    }
}

From source file:com.ntc.utils.PdfTextExtractor.java

public PdfTextExtractor(File file) {
    try {/*from www  .  j  av  a2 s. co m*/
        document = PDDocument.load(file);
        numberOfPages = document.getNumberOfPages();
        stripper = new PDFTextStripper();
    } catch (IOException ex) {
        Logger.getLogger(PdfTextExtractor.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.odc.pdfextractor.parser.CleanPdfParser.java

License:Apache License

/**
 * This will print the documents docBuilder.
 *
 * @param args The command line arguments.
 *
 * @throws Exception If there is an error parsing the document.
 *//*from   w  w  w .j  a v a 2  s  . c o m*/
public DocumentLocation processPdf(String filename) throws Exception {

    PDDocument document = null;
    try {
        document = PDDocument.load(filename);
        if (document.isEncrypted()) {
            try {
                document.decrypt("");
            } catch (InvalidPasswordException e) {
                System.err.println("Error: Document is encrypted with a password.");
                System.exit(1);
            }
        }
        List allPages = document.getDocumentCatalog().getAllPages();
        System.out.print("Extracting text from PDF");
        for (int i = 0; i < allPages.size(); i++) {
            PDPage page = (PDPage) allPages.get(i);
            System.out.print(".");
            PDStream contents = page.getContents();
            if (contents != null) {
                this.processStream(page, page.findResources(), page.getContents().getStream());
            }
            docBuilder.incrementPage();
        }
    } finally {
        System.out.println();
        if (document != null) {
            document.close();
        }
    }
    return docBuilder.getDoc();
}