List of usage examples for org.apache.pdfbox.pdmodel PDDocument close
@Override public void close() throws IOException
From source file:merge_split.MergeSplit.java
License:Apache License
private void ConvertFileButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ConvertFileButtonActionPerformed String fileName;/*from ww w. ja va 2 s . c om*/ 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) { } convertcode = ""; if (doc == null) { JFrame frame = new JFrame("Input Dialog Example 3"); convertcode = 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"; } ConvertPagesField.setText(currentpages); ConvertFileField.setText(fileName); String name = file.getName(); int pos = name.lastIndexOf("."); if (pos > 0) { name = name.substring(0, pos); } ConvertNameField.setText(name); try { doc.close(); } catch (IOException ex) { JOptionPane.showMessageDialog(null, "Problem accessing file.", "Problem accessing file", JOptionPane.WARNING_MESSAGE); } } } else { System.out.println("File access cancelled by user."); } }
From source file:merge_split.MergeSplit.java
License:Apache License
private void ConvertButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ConvertButtonActionPerformed PDDocument document = null; try {//ww w .ja v a 2 s. com document = PDDocument.load(new File((String) ConvertFileField.getText()), convertcode); } catch (IOException ex) { JOptionPane.showMessageDialog(null, "Problem opening pdf.", "Problem opening pdf", JOptionPane.WARNING_MESSAGE); } TreeSet tree = findPages((String) ConvertPagesField.getText()); PDFRenderer pdfRenderer = new PDFRenderer(document); for (int page = 0; page < document.getNumberOfPages(); ++page) { BufferedImage bim = null; try { bim = pdfRenderer.renderImageWithDPI(page, 300, ImageType.RGB); } catch (IOException ex) { JOptionPane.showMessageDialog(null, "Problem rendering image.", "Problem rendering image", JOptionPane.WARNING_MESSAGE); } // suffix in filename will be used as the file format String destination = ConvertDestinationField.getText() + "\\" + ConvertNameField.getText(); String image = ".png"; if (pngbutton.isSelected()) { image = ".png"; } else if (bmpbutton.isSelected()) { image = ".bmp"; } else if (gifbutton.isSelected()) { image = ".gif"; } else if (jpgbutton.isSelected()) { image = ".jpg"; } try { if (tree.contains(page + 1)) { ImageIOUtil.writeImage(bim, destination + "-" + (page + 1) + image, 300); } } catch (IOException ex) { JOptionPane.showMessageDialog(null, "Problem output image.", "Problem output image", JOptionPane.WARNING_MESSAGE); java.util.logging.Logger.getLogger(MergeSplit.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } } try { document.close(); } catch (IOException ex) { Logger.getLogger(MergeSplit.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:merge_split.MergeSplit.java
License:Apache License
private void SplitButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_SplitButtonActionPerformed try {//from www . j a v a 2 s. com File file = new File(SplitFileField.getText()); PDDocument doc1; if (splitcode.equals("ok")) { doc1 = PDDocument.load(file); } else { doc1 = PDDocument.load(file, splitcode); } doc1.setAllSecurityToBeRemoved(true); if (MultipleButton.isSelected()) { PDDocument pdf1 = new PDDocument(); PDDocument pdf2 = new PDDocument(); TreeSet tree = findPages(SplitPagesField.getText()); for (int j = 0; j < doc1.getNumberOfPages(); j++) { PDPage page = doc1.getPage(j); if (tree.contains(j + 1)) { pdf1.addPage(page); } else { pdf2.addPage(page); } } String destination1 = SplitDestinationField.getText() + "\\" + SplitNameField.getText() + "1.pdf"; String destination2 = SplitDestinationField.getText() + "\\" + SplitNameField.getText() + "2.pdf"; PDDocumentInformation info = pdf1.getDocumentInformation(); info.setAuthor(SplitAuthorField.getText()); PDDocumentInformation info2 = pdf2.getDocumentInformation(); info2.setAuthor(SplitAuthorField.getText()); if (pdf1.getNumberOfPages() > 0) { File output1 = new File(destination1); pdf1.save(output1); } if (pdf2.getNumberOfPages() > 0) { File output2 = new File(destination2); pdf2.save(output2); } pdf1.close(); pdf2.close(); } else if (SingleButton.isSelected()) { for (int j = 0; j < doc1.getNumberOfPages(); j++) { PDDocument pdf1 = new PDDocument(); PDPage page = doc1.getPage(j); pdf1.addPage(page); int pagenumber = j + 1; String destination1 = SplitDestinationField.getText() + "\\" + SplitNameField.getText() + pagenumber + ".pdf"; PDDocumentInformation info = pdf1.getDocumentInformation(); info.setAuthor(SplitAuthorField.getText()); if (pdf1.getNumberOfPages() > 0) { File output1 = new File(destination1); pdf1.save(output1); } pdf1.close(); } } doc1.close(); } catch (IOException ex) { JOptionPane.showMessageDialog(null, "Your input is incorrect. Please fill all the fields.", "Input warning", JOptionPane.WARNING_MESSAGE); java.util.logging.Logger.getLogger(MergeSplit.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } }
From source file:merge_split.MergeSplit.java
License:Apache License
private void SplitFileButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_SplitFileButtonActionPerformed String fileName;/*from w w w .j a v a 2 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) { } splitcode = ""; if (doc == null) { JFrame frame = new JFrame("Input Dialog Example 3"); splitcode = 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"; } SplitPagesField.setText(currentpages); SplitFileField.setText(fileName); String name = file.getName(); int pos = name.lastIndexOf("."); if (pos > 0) { name = name.substring(0, pos); } name = name + "Split"; SplitNameField.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:mil.tatrc.physiology.utilities.Excel2PDF.java
License:Apache License
public static void convert(String from, String to) throws IOException { FileInputStream xlFile = new FileInputStream(new File(from)); // Read workbook into HSSFWorkbook XSSFWorkbook xlWBook = new XSSFWorkbook(xlFile); //We will create output PDF document objects at this point PDDocument pdf = new PDDocument(); //pdf.addTitle(); for (int s = 0; s < xlWBook.getNumberOfSheets(); s++) { XSSFSheet xlSheet = xlWBook.getSheetAt(s); Log.info("Processing Sheet : " + xlSheet.getSheetName()); PDPage page = new PDPage(PDRectangle.A4); page.setRotation(90);//from w w w . j a va 2s .c om pdf.addPage(page); PDRectangle pageSize = page.getMediaBox(); PDPageContentStream contents = new PDPageContentStream(pdf, page); contents.transform(new Matrix(0, 1, -1, 0, pageSize.getWidth(), 0));// including a translation of pageWidth to use the lower left corner as 0,0 reference contents.setFont(PDType1Font.HELVETICA_BOLD, 16); contents.beginText(); contents.newLineAtOffset(50, pageSize.getWidth() - 50); contents.showText(xlSheet.getSheetName()); contents.endText(); contents.close(); int rows = xlSheet.getPhysicalNumberOfRows(); for (int r = 0; r < rows; r++) { XSSFRow row = xlSheet.getRow(r); if (row == null) continue; int cells = row.getPhysicalNumberOfCells(); if (cells == 0) continue;// Add an empty Roe } } /* //We will use the object below to dynamically add new data to the table PdfPCell table_cell; //Loop through rows. while(rowIterator.hasNext()) { Row row = rowIterator.next(); Iterator<Cell> cellIterator = row.cellIterator(); while(cellIterator.hasNext()) { Cell cell = cellIterator.next(); //Fetch CELL switch(cell.getCellType()) { //Identify CELL type //you need to add more code here based on //your requirement / transformations case Cell.CELL_TYPE_STRING: //Push the data from Excel to PDF Cell table_cell=new PdfPCell(new Phrase(cell.getStringCellValue())); //feel free to move the code below to suit to your needs my_table.addCell(table_cell); break; } //next line } } */ pdf.save(new File(to)); pdf.close(); xlWBook.close(); xlFile.close(); //close xls }
From source file:mj.ocraptor.extraction.tika.parser.pdf.PDFParser.java
License:Apache License
public void parse(InputStream stream, ContentHandler handler, Metadata metadata, ParseContext context) throws IOException, SAXException, TikaException { PDDocument pdfDocument = null; TemporaryResources tmp = new TemporaryResources(); // config from context, or default if not set via context PDFParserConfig localConfig = context.get(PDFParserConfig.class, defaultConfig); try {//from w ww . j a va 2s .c o m // PDFBox can process entirely in memory, or can use a temp file // for unpacked / processed resources // Decide which to do based on if we're reading from a file or not // already TikaInputStream tstream = TikaInputStream.cast(stream); if (tstream != null && tstream.hasFile()) { // File based, take that as a cue to use a temporary file RandomAccess scratchFile = new RandomAccessFile(tmp.createTemporaryFile(), "rw"); if (localConfig.getUseNonSequentialParser() == true) { pdfDocument = PDDocument.loadNonSeq(new CloseShieldInputStream(stream), scratchFile); } else { pdfDocument = PDDocument.load(new CloseShieldInputStream(stream), scratchFile, true); } } else { // Go for the normal, stream based in-memory parsing if (localConfig.getUseNonSequentialParser() == true) { pdfDocument = PDDocument.loadNonSeq(new CloseShieldInputStream(stream), new RandomAccessBuffer()); } else { pdfDocument = PDDocument.load(new CloseShieldInputStream(stream), true); } } if (pdfDocument.isEncrypted()) { String password = null; // Did they supply a new style Password Provider? PasswordProvider passwordProvider = context.get(PasswordProvider.class); if (passwordProvider != null) { password = passwordProvider.getPassword(metadata); } // Fall back on the old style metadata if set if (password == null && metadata.get(PASSWORD) != null) { password = metadata.get(PASSWORD); } // If no password is given, use an empty string as the default if (password == null) { password = ""; } try { pdfDocument.decrypt(password); } catch (Exception e) { // Ignore } } metadata.set(Metadata.CONTENT_TYPE, "application/pdf"); extractMetadata(pdfDocument, metadata); PDF2XHTML.process(pdfDocument, handler, context, metadata, localConfig); } catch (Exception e) { // TODO: logging e.printStackTrace(); } finally { if (pdfDocument != null) { pdfDocument.close(); } if (tmp != null) { tmp.dispose(); tmp.close(); } } handler.endDocument(); }
From source file:model.ParsePDF.java
License:Open Source License
/** * Find all passed Exams with and without grade and save them to a vector. * //from w ww. j a v a2s .co m * @param file * @throws IOException */ public void findPassedCourses(String file) throws IOException { PDDocument pddDocument = PDDocument.load(new File(file)); PDFTextStripper textStripper = new PDFTextStripper(); String x = textStripper.getText(pddDocument); String[] lines = getLines(x); // find all passed exams and save them in a Vector called courses. for (int i = 0; i < lines.length; i++) { // System.out.println(lines[i]); if (lines[i].contains("Fach:")) { setSubject(lines[i]); } if (lines[i].contains("Abschluss:")) { setCertificate(lines[i]); } if (lines[i].contains("BE")) { courses.addElement(lines[i]); } } pddDocument.close(); }
From source file:model.util.pdf.PDFUtils.java
License:Apache License
/** * Infamous main method./*from w w w .j ava2s . c om*/ * 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:model.util.pdf.PDFUtils.java
License:Apache License
/** * Test: Create pdf from image and pdf file. * * @param _inputFile pdf input// w w w .ja va 2 s .com * @param _imagePath image input * @param _outputFile pdf output * * @throws IOException occurs if reading the data fails. */ public void saveAsPdf(String _imagePath, String _outputFile) throws IOException { PDDocument doc = null; try { // create new document and insert empty page to the document. doc = new PDDocument(); PDPage page = new PDPage(); doc.addPage(page); // createFromFile is the easiest way with an image file // if you already have the image in a BufferedImage, // call LosslessFactory.createFromImage() instead PDImageXObject pdImage = PDImageXObject.createFromFile(_imagePath, doc); PDPageContentStream contentStream = new PDPageContentStream(doc, page, true, true); // contentStream.drawImage(ximage, 20, 20 ); // better method inspired by http://stackoverflow.com/a/22318681/535646 // reduce this value if the image is too large float scale = 1f; contentStream.drawImage(pdImage, 20, 20, pdImage.getWidth() * scale, pdImage.getHeight() * scale); contentStream.close(); doc.save(_outputFile); } finally { if (doc != null) { doc.close(); } } }
From source file:module.fileSupport.metadata.parsing.parsers.PDFParser.java
License:Open Source License
@Override protected String extract(InputStream stream) { StringWriter writer = null;/*ww w. j av a 2s. c o m*/ try { PDDocument pdfDocument = PDDocument.load(stream); writer = new StringWriter(); PDFTextStripper stripper = new PDFTextStripper(); stripper.writeText(pdfDocument, writer); pdfDocument.close(); } catch (Exception e) { e.printStackTrace(); return null; } return writer.toString(); }