List of usage examples for org.apache.pdfbox.pdmodel PDDocument close
@Override public void close() throws IOException
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 .c om * * @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// w w w. ja va 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);//w w w . ja v a 2 s.c o m 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; try {//from w w w. j a v a2 s . co m 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 w w w . j a v a 2 s. com*/ 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;//from ww w. j a v a2 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 {/* w ww . jav a 2s. 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); } }
From source file:merge_split.MergeSplit.java
License:Apache License
private void RotateButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_RotateButtonActionPerformed try {//from w w w . j a v a 2 s . c om PDDocument samplePdf = new PDDocument(); File file = new File(RotateFileField.getText()); PDDocument doc1; if (rotatecode.equals("ok")) { doc1 = PDDocument.load(file); } else { doc1 = PDDocument.load(file, rotatecode); } doc1.setAllSecurityToBeRemoved(true); TreeSet tree = findPages(RotatePagesField.getText()); for (int j = 0; j < doc1.getNumberOfPages(); j++) { PDPage page = doc1.getPage(j); if (tree.contains(j + 1)) { if (Rotate90.isSelected()) { page.setRotation(90); samplePdf.addPage(page); } else if (Rotate180.isSelected()) { page.setRotation(180); samplePdf.addPage(page); } else if (Rotate270.isSelected()) { page.setRotation(270); samplePdf.addPage(page); } } else { samplePdf.addPage(page); } } System.out.println("Number:" + samplePdf.getNumberOfPages()); String destination = RotateDestinationField.getText() + "\\" + RotateNameField.getText() + ".pdf"; PDDocumentInformation info = samplePdf.getDocumentInformation(); info.setAuthor(RotateAuthorField.getText()); File output = new File(destination); samplePdf.save(output); samplePdf.close(); } catch (IOException ex) { Logger.getLogger(MergeSplit.class.getName()).log(Level.SEVERE, null, ex); JOptionPane.showMessageDialog(null, "Your input is incorrect. Please fill all the fields.", "Input warning", JOptionPane.WARNING_MESSAGE); } }
From source file:merge_split.MergeSplit.java
License:Apache License
private void RotateFileButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_RotateFileButtonActionPerformed String fileName;/*from w w w . j a v a2 s .co m*/ int returnVal = jFileChooser1.showOpenDialog((Component) evt.getSource()); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = jFileChooser1.getSelectedFile(); fileName = file.toString(); PDDocument doc = null; try { doc = PDDocument.load(file); if (doc.isEncrypted()) { doc.setAllSecurityToBeRemoved(true); } } catch (IOException ex) { } rotatecode = ""; if (doc == null) { JFrame frame = new JFrame("Input Dialog Example 3"); rotatecode = JOptionPane.showInputDialog(frame, "Enter password", "PDF is encrypted", JOptionPane.WARNING_MESSAGE); try { doc = PDDocument.load(file, rotatecode); } 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"; } RotatePagesField.setText(currentpages); RotateFileField.setText(fileName); String name = file.getName(); int pos = name.lastIndexOf("."); if (pos > 0) { name = name.substring(0, pos); } name = name + "Rotated"; RotateNameField.setText(name); try { doc.close(); } catch (IOException ex) { JOptionPane.showMessageDialog(null, "Problem finishing process.", "Problem finishing process", JOptionPane.WARNING_MESSAGE); } } } else { System.out.println("File access cancelled by user."); } }
From source file:merge_split.MergeSplit.java
License:Apache License
private void RotateButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_RotateButton1ActionPerformed PDDocument document = new PDDocument(); InputStream in = null;// w w w . j a v a 2 s .c o m BufferedImage bimg = null; try { in = new FileInputStream((String) ImageFileField.getText()); bimg = ImageIO.read(in); } catch (IOException ex) { JOptionPane.showMessageDialog(null, "Image could not be read.", "Image could not be read", JOptionPane.WARNING_MESSAGE); } float width = bimg.getWidth(); float height = bimg.getHeight(); PDPage page = new PDPage(new PDRectangle(width, height)); document.addPage(page); PDImageXObject imgpdf; try { imgpdf = PDImageXObject.createFromFile((String) ImageFileField.getText(), document); try (PDPageContentStream contentStream = new PDPageContentStream(document, page)) { contentStream.drawImage(imgpdf, 0, 0); } in.close(); } catch (IOException ex) { JOptionPane.showMessageDialog(null, "Image could not be converted.", "Proccess could not be finished", JOptionPane.WARNING_MESSAGE); } String destination = ImageDestinationField.getText() + "\\" + ImageNameField.getText() + ".pdf"; PDDocumentInformation info = document.getDocumentInformation(); info.setAuthor(ImageAuthorField.getText()); File output = new File(destination); try { document.save(output); } catch (IOException ex) { JOptionPane.showMessageDialog(null, "Not all fields were filled.", "Input Problem", JOptionPane.WARNING_MESSAGE); } try { document.close(); } catch (IOException ex) { JOptionPane.showMessageDialog(null, "Not all fields were filled.", "Input Problem", JOptionPane.WARNING_MESSAGE); } }