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:latexstudio.editor.pdf.PDFService.java

public static PDPage getPDFPage(int number) {
    PDPage page = null;/*from  w w w.  j av  a 2 s .  com*/

    File pdfFile = null;
    try {
        pdfFile = new File(PDF_PATH);
        if (pdfFile.exists()) {
            inputPDF = PDDocument.load(pdfFile);
            List<PDPage> allPages = inputPDF.getDocumentCatalog().getAllPages();
            if (allPages != null && !allPages.isEmpty() && allPages.size() >= number && number > 0) {
                page = allPages.get(number - 1);
            }
        }
    } catch (IOException ex) {
        closeDocument();
    }

    return page;
}

From source file:lucee.runtime.text.pdf.PDFDocument.java

License:Open Source License

public PDDocument toPDDocument() throws CryptographyException, InvalidPasswordException, IOException {
    PDDocument doc;/* w  w w  .  jav a2 s.  c  o  m*/
    if (barr != null)
        doc = PDDocument.load(new ByteArrayInputStream(barr, 0, barr.length));
    else if (resource instanceof FileResource)
        doc = PDDocument.load((File) resource);
    else
        doc = PDDocument.load(new ByteArrayInputStream(IOUtil.toBytes(resource), 0, barr.length));

    if (password != null)
        doc.decrypt(password);

    return doc;

}

From source file:main.java.ufg.inf.manutencao.util.UtilTexto.java

/**
* Le o conteudo (texto) de um arquivo pdf
*
   * @param caminho/*from w  ww .ja v  a 2s .  c  o  m*/
*/
public static String extraiTextoDoPDF(String caminho) {
    PDDocument pdfDocument = null;
    try {
        pdfDocument = PDDocument.load(caminho);
        PDFTextStripper stripper = new PDFTextStripper();
        String texto = stripper.getText(pdfDocument);
        return texto;
    } catch (IOException e) {
        throw new RuntimeException(e);
    } finally {
        if (pdfDocument != null)
            try {
                pdfDocument.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
    }
}

From source file:main.java.vasolsim.common.GenericUtils.java

License:Open Source License

/**
 * gets the number of pages in a pdf/*from   w  w  w  . j a va  2  s  . com*/
 *
 * @param file
 *
 * @return
 *
 * @throws IOException
 */
public static int getPDFPages(File file) throws IOException {
    PDDocument doc = PDDocument.load(file);
    int pages = doc.getNumberOfPages();
    doc.close();
    return pages;
}

From source file:main.java.vasolsim.common.GenericUtils.java

License:Open Source License

/**
 * renders a pdf to images//www .j av  a 2  s .c o  m
 *
 * @param file pdf file
 *
 * @return images
 *
 * @throws IOException
 */
public static BufferedImage[] renderPDF(File file) throws IOException {
    PDDocument doc = PDDocument.load(file);
    @SuppressWarnings("unchecked")
    List<PDPage> pages = doc.getDocumentCatalog().getAllPages();
    Iterator<PDPage> iterator = pages.iterator();
    BufferedImage[] images = new BufferedImage[pages.size()];
    for (int i = 0; iterator.hasNext(); i++)
        images[i] = iterator.next().convertToImage();

    doc.close();

    return images;
}

From source file:main.java.vasolsim.tclient.form.QuestionSetNode.java

License:Open Source License

public void redrawNode(boolean apply) {
    HBox horizontalRoot = new HBox();

    VBox verticalRoot = new VBox();
    verticalRoot.getStyleClass().add("borders");
    horizontalRoot.getChildren().add(verticalRoot);

    Label questionSetInfoLabel = new Label(TeacherClient.QUESTION_SET_INFO_LABEL_TEXT);
    questionSetInfoLabel.getStyleClass().add("lbltext");

    Label questionSetNameLabel = new Label(TeacherClient.QUESTION_SET_NAME_LABEL_TEXT);
    questionSetNameLabel.getStyleClass().add("lbltext");

    final TextField questionSetNameField = new TextField();
    questionSetNameField.setPrefWidth(400);

    Button applyNameButton = new Button("Apply");

    HBox spacer = new HBox();
    spacer.setPrefHeight(2);//from   w  ww  .  j a  v a 2s.  c  om
    spacer.setPrefWidth(2000);
    spacer.getStyleClass().add("lblspacer");

    Label resourceFileInfoLabel = new Label(TeacherClient.RESOURCE_FILE_INFO_LABEL_TEXT);
    resourceFileInfoLabel.getStyleClass().add("lbltext");
    resourceFileInfoLabel.setWrapText(true);

    final Label resourceFileLabel = new Label(lastPath == null ? "File: none" : "File: " + lastPath);
    resourceFileLabel.getStyleClass().add("lbltext");
    resourceFileLabel.setWrapText(true);

    HBox buttonBox = new HBox();
    buttonBox.getStyleClass().add("helementspacing");

    Button loadResourceButton = new Button("Load");
    Button removeResourceButton = new Button("Remove");

    buttonBox.getChildren().addAll(loadResourceButton, removeResourceButton);

    TilePane imageContainer = new TilePane();
    imageContainer.setPrefWidth(2000);
    imageContainer.setVgap(10);
    imageContainer.setHgap(10);
    if (qSet.getResources() != null)
        for (Image i : qSet.getFxResources()) {
            ImageView iv = new ImageView(i);
            iv.setPreserveRatio(true);
            iv.setFitWidth(150);
            iv.getStyleClass().add("pic");
            imageContainer.getChildren().add(iv);
        }
    else {
        Label noImg = new Label("no resource to display");
        noImg.getStyleClass().add("lbltext");
        noImg.setWrapText(true);
        imageContainer.getChildren().add(noImg);
    }

    final ProgressBar bar = new ProgressBar();
    bar.managedProperty().bind(bar.visibleProperty());
    bar.setVisible(false);
    bar.setPrefWidth(2000);

    /*
     * add elements
     */
    verticalRoot.getChildren().addAll(questionSetInfoLabel, questionSetNameLabel, questionSetNameField,
            applyNameButton, spacer, resourceFileLabel, bar, imageContainer, buttonBox);

    /*
     * Init listeners
     */
    applyNameButton.setOnMouseClicked(new EventHandler<MouseEvent>() {
        @Override
        public void handle(MouseEvent mouseEvent) {
            if (questionSetNameField.getText() != null && questionSetNameField.getText().trim().length() > 0) {
                boundTreeElement.label.setText(questionSetNameField.getText());
                questionSetNameField.clear();
            }
        }
    });

    loadResourceButton.setOnMouseClicked(new EventHandler<MouseEvent>() {
        @Override
        public void handle(MouseEvent mouseEvent) {
            FileChooser fc = new FileChooser();
            File resource = fc.showOpenDialog(TeacherClient.stage);
            String tmpPath;
            try {
                tmpPath = resource.getCanonicalPath();
            } catch (IOException e) {
                tmpPath = resource.getAbsolutePath();
            }

            if (tmpPath.equals(""))
                tmpPath = lastPath;
            else
                lastPath = tmpPath;

            final String path = tmpPath;

            Task pdfRender = new Task<Void>() {
                @Override
                protected Void call() throws Exception {
                    int maxProgress = getPDFPages(new File(path)) * 2;
                    PDDocument doc = PDDocument.load(new File(path));
                    @SuppressWarnings("unchecked")
                    List<PDPage> pages = doc.getDocumentCatalog().getAllPages();
                    Iterator<PDPage> iterator = pages.iterator();
                    BufferedImage[] images = new BufferedImage[pages.size()];
                    for (int i = 0; iterator.hasNext(); i++) {
                        images[i] = iterator.next().convertToImage();
                        updateProgress(i, maxProgress);
                    }

                    doc.close();
                    qSet.setResources(images);

                    Image[] fxImages = new Image[images.length];
                    for (int i = 0; i < images.length; i++) {
                        fxImages[i] = convertBufferedImageToFXImage(images[i]);
                        updateProgress(images.length + i, maxProgress);
                    }

                    qSet.setFxResources(fxImages);

                    return null;
                }
            };
            bar.setVisible(true);
            bar.progressProperty().bind(pdfRender.progressProperty());
            resourceFileLabel.setText("File: " + tmpPath);
            new Thread(pdfRender).start();
            //qSet.loadPDFResource(tmpPath);
            //redrawNode(true);

            pdfRender.setOnSucceeded(new EventHandler<WorkerStateEvent>() {
                @Override
                public void handle(WorkerStateEvent workerStateEvent) {
                    bar.setVisible(false);
                    qSet.setResourceType(ResourceType.PNG);
                    redrawNode(true);
                }
            });

            pdfRender.setOnFailed(new EventHandler<WorkerStateEvent>() {
                @Override
                public void handle(WorkerStateEvent workerStateEvent) {
                    bar.setVisible(false);
                    qSet.setResources(null);
                    qSet.setFxResources(null);
                    PopupManager.showMessage("PDF failed to open");
                    redrawNode(false);
                }
            });
        }
    });

    removeResourceButton.setOnMouseClicked(new EventHandler<MouseEvent>() {
        @Override
        public void handle(MouseEvent mouseEvent) {
            qSet.removeResource();
            lastPath = null;
            redrawNode(true);
        }
    });

    questionSetNode = horizontalRoot;

    if (apply) {
        CenterNode.addScrollRoot();
        CenterNode.getScrollRoot().setContent(questionSetNode);
    }
}

From source file:main.PdfReader.java

License:Apache License

@Test
public void testPDFReader() throws Exception {
    // page with example pdf document
    driver.get("http://www.vandevenbv.nl/dynamics/modules/SFIL0200/view.php?fil_Id=5515");

    URL url = new URL(driver.getCurrentUrl());
    BufferedInputStream fileToParse = new BufferedInputStream(url.openStream());

    PDDocument document = null;//from   w w w  .  j av  a2  s. c o m
    try {
        document = PDDocument.load(fileToParse);
        String output = new PDFTextStripper().getText(document);
        System.out.println(output);
    } finally {

        if (document != null) {
            document.close();
        }
    }
}

From source file:mc.program.Importer.java

public void importPDF() {
    try {//from ww  w.  j a  va2s . co m
        PDDocument pdf = PDDocument.load(sourceFile);

        PDFTextStripper stripper = new PDFTextStripper();

        String fileData = stripper.getText(pdf);

        InputStream stream = new ByteArrayInputStream(fileData.getBytes(StandardCharsets.UTF_8));
        Scanner scanner = new Scanner(stream);
        while (scanner.hasNext()) {
            sourceText.add(scanner.next());
        }

        pdf.close();
        stream.close();
        scanner.close();
    } catch (Exception ex) {
        System.out.print(ex);
    }
}

From source file:merge_split.MergeSplit.java

License:Apache License

private void AddButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_AddButtonActionPerformed

    String fileName;/*  ww w  . j  ava 2 s  .c o m*/
    int returnVal = jFileChooser1.showOpenDialog((Component) evt.getSource());
    if (returnVal == JFileChooser.APPROVE_OPTION) {
        File file = jFileChooser1.getSelectedFile();
        fileName = file.toString();
        PDDocument doc = null;
        String code = "";
        try {
            doc = PDDocument.load(file);
            if (doc.isEncrypted()) {

                doc.setAllSecurityToBeRemoved(true);

            }
        } catch (IOException ex) {

        }
        if (doc == null) {
            JFrame frame = new JFrame("Input Dialog Example 3");

            code = JOptionPane.showInputDialog(frame, "Enter password", "PDF is encrypted",
                    JOptionPane.WARNING_MESSAGE);
            try {
                doc = PDDocument.load(file, code);
            } catch (IOException ex) {
                JOptionPane.showMessageDialog(null, "Wrong Password.", "Wrong Password",
                        JOptionPane.WARNING_MESSAGE);

            }

        }
        if (doc != null) {
            int count = doc.getNumberOfPages();

            String currentpages;
            if (count > 1) {
                currentpages = "1 - " + count;
            } else {
                currentpages = "1";
            }
            boolean isOriginalDocEncrypted = doc.isEncrypted();

            String column4;
            if (isOriginalDocEncrypted) {
                column4 = code;
            } else {
                column4 = "ok";
            }
            dtm.addRow(new Object[] { fileName, count, currentpages, column4 });
            try {
                doc.close();
            } catch (IOException ex) {
                JOptionPane.showMessageDialog(null, "Problem accessing file.", "Problem accessing file",
                        JOptionPane.WARNING_MESSAGE);
            }

            arr.add(file);
        }
    } else {
        System.out.println("File access cancelled by user.");
    }

}

From source file:merge_split.MergeSplit.java

License:Apache License

private void MergeButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_MergeButtonActionPerformed
    try {/*from  ww w  . j  a v a2  s .c o m*/
        PDDocument samplePdf = new PDDocument();
        ArrayList<PDDocument> list = new ArrayList<>();
        for (int i = 0; i < dtm.getRowCount(); i++) {
            File file = new File((String) dtm.getValueAt(i, 0));
            String code = (String) dtm.getValueAt(i, 3);
            PDDocument doc1;
            if (code.equals("ok")) {
                doc1 = PDDocument.load(file);
            } else {
                doc1 = PDDocument.load(file, code);

            }
            list.add(doc1);
            doc1.setAllSecurityToBeRemoved(true);
            TreeSet tree = findPages((String) dtm.getValueAt(i, 2));
            for (int j = 0; j < doc1.getNumberOfPages(); j++) {
                if (tree.contains(j + 1)) {
                    samplePdf.addPage(doc1.getPage(j));
                }

            }

        }
        System.out.println("Number:" + samplePdf.getNumberOfPages());

        String destination = jTextField1.getText() + "\\" + jTextField2.getText() + ".pdf";
        PDDocumentInformation info = samplePdf.getDocumentInformation();
        info.setAuthor(jTextField3.getText());
        File output = new File(destination);

        samplePdf.save(output);

        samplePdf.close();
        for (int i = 0; i < list.size(); i++) {
            list.get(i).close();
        }
    } catch (IOException ex) {

        JOptionPane.showMessageDialog(null, "Your input is incorrect. Please fill all the fields.",
                "Input warning", JOptionPane.WARNING_MESSAGE);
    }

}