List of usage examples for org.apache.pdfbox.pdmodel PDDocument close
@Override public void close() throws IOException
From source file:ExtractTextFromPdf.java
public static void main(String[] args) { PDFParser parser = null;// ww w .j a va 2 s. com PDDocument pdDoc = null; COSDocument cosDoc = null; PDFTextStripper pdfStripper; String parsedText; String fileName = "C:/Users/Kavya Gupta/Desktop/Texas_Title.pdf"; File file = new File(fileName); try { byte data[] = new byte[1024]; ((RandomAccessRead) file).read(data, 0, 1024); pdDoc = PDDocument.load(new File(fileName)); pdfStripper = new PDFTextStripper(); parsedText = pdfStripper.getText(pdDoc); System.out.println(parsedText.replaceAll("[^A-Za-z0-9. ]+", "")); } catch (Exception e) { e.printStackTrace(); try { if (cosDoc != null) cosDoc.close(); if (pdDoc != null) pdDoc.close(); } catch (Exception e1) { e.printStackTrace(); } } }
From source file:DecodePlate.java
License:Open Source License
public static void ProcessPlateWork() throws Exception { // Filter out fixes more than 50nm away from airport, no chart goes that far. // This helps us from trying to decode spurious strings as fix names and // helps us avoid duplicate name problems. nearDBFixes.clear();/*from w ww. j av a 2s.co m*/ for (DBFix dbfix : allDBFixes) { if (Lib.LatLonDist(dbfix.lat, dbfix.lon, airport.lat, airport.lon) <= maxFixDistNM) { dbfix.mentioned = false; nearDBFixes.put(dbfix.name, dbfix); } } // Also add in runways as fixes cuz some plates use them for fixes. for (Runway rwy : airport.runways.values()) { nearDBFixes.put(rwy.name, rwy); } // Open PDF and scan it. PDDocument pddoc = PDDocument.load(pdfName); PDDocumentCatalog doccat = pddoc.getDocumentCatalog(); PDPageNode pages = doccat.getPages(); List kids = new LinkedList(); pages.getAllKids(kids); if (kids.size() != 1) throw new Exception("pdf not a single Page"); Object kid = kids.get(0); PDPage page = (PDPage) kid; int imgWidth = (int) (page.getMediaBox().getWidth() / pdfDpi * csvDpi + 0.5F); int imgHeight = (int) (page.getMediaBox().getHeight() / pdfDpi * csvDpi + 0.5F); BufferedImage bi = new BufferedImage(imgWidth, imgHeight, BufferedImage.TYPE_INT_ARGB); Graphics2D g2d = bi.createGraphics(); PagePanel pagepanel = new PagePanel(page); pagepanel.paintComponent(g2d); pagepanel.resolveFixes(g2d); if (markedpngname != null) { if (!ImageIO.write(bi, "png", new File(markedpngname))) { throw new IOException("ImageIO.write(" + markedpngname + ") failed"); } } pddoc.close(); }
From source file:ReducePDFSize.java
License:Apache License
public static void main(String[] args) throws IOException { if (2 != args.length) { throw new RuntimeException("arg0 must be input file, org1 must be output file"); }//from w w w . j a va2 s . com String in = args[0]; String out = args[1]; PDDocument doc = null; try { doc = PDDocument.load(new File(in)); doc.setAllSecurityToBeRemoved(true); for (COSObject cosObject : doc.getDocument().getObjects()) { COSBase base = cosObject.getObject(); // if it's a stream: decode it, then re-write it using FLATE_DECODE if (base instanceof COSStream) { COSStream stream = (COSStream) base; byte[] bytes; try { bytes = new PDStream(stream).toByteArray(); } catch (IOException ex) { // NOTE: original example code from PDFBox just logged & "continue;"d here, 'skipping' this stream. // If this type of failure ever happens, we can (perhaps) consider (re)ignoring this type of failure? // // IIUC then that will leave the original (non-decoded / non-flated) stream in place? throw new RuntimeException("can't serialize byte[] from: " + cosObject.getObjectNumber() + " " + cosObject.getGenerationNumber() + " obj: " + ex.getMessage(), ex); } stream.removeItem(COSName.FILTER); OutputStream streamOut = stream.createOutputStream(COSName.FLATE_DECODE); streamOut.write(bytes); streamOut.close(); } } doc.getDocumentCatalog(); doc.save(out); } finally { if (doc != null) { doc.close(); } } }
From source file:SetField.java
License:Apache License
private void setField(String[] args) throws IOException, COSVisitorException { PDDocument pdf = null; try {/*w w w.jav a 2 s . c o m*/ if (args.length < 3) { usage(); } else { SetField example = new SetField(); pdf = PDDocument.load(args[0]); example.setField(pdf, Arrays.copyOfRange(args, 1, args.length)); pdf.save(args[0] + ".computed.pdf"); } } finally { if (pdf != null) { pdf.close(); } } }
From source file:ShowSignature.java
License:Apache License
private void showSignature(String[] args) throws IOException, CertificateException { if (args.length != 2) { usage();//w ww .j av a 2 s .co m } else { String password = args[0]; String infile = args[1]; PDDocument document = null; try { document = PDDocument.load(new File(infile), password); if (!document.isEncrypted()) { System.err.println("Warning: Document is not encrypted."); } COSDictionary trailer = document.getDocument().getTrailer(); COSDictionary root = (COSDictionary) trailer.getDictionaryObject(COSName.ROOT); COSDictionary acroForm = (COSDictionary) root.getDictionaryObject(COSName.ACRO_FORM); COSArray fields = (COSArray) acroForm.getDictionaryObject(COSName.FIELDS); for (int i = 0; i < fields.size(); i++) { COSDictionary field = (COSDictionary) fields.getObject(i); COSName type = field.getCOSName(COSName.FT); if (COSName.SIG.equals(type)) { COSDictionary cert = (COSDictionary) field.getDictionaryObject(COSName.V); if (cert != null) { System.out.println("Certificate found"); System.out.println("Name=" + cert.getDictionaryObject(COSName.NAME)); System.out.println("Modified=" + cert.getDictionaryObject(COSName.M)); COSName subFilter = (COSName) cert.getDictionaryObject(COSName.SUB_FILTER); if (subFilter != null) { if (subFilter.getName().equals("adbe.x509.rsa_sha1")) { COSString certString = (COSString) cert .getDictionaryObject(COSName.getPDFName("Cert")); byte[] certData = certString.getBytes(); CertificateFactory factory = CertificateFactory.getInstance("X.509"); ByteArrayInputStream certStream = new ByteArrayInputStream(certData); Collection<? extends Certificate> certs = factory .generateCertificates(certStream); System.out.println("certs=" + certs); } else if (subFilter.getName().equals("adbe.pkcs7.sha1")) { COSString certString = (COSString) cert.getDictionaryObject(COSName.CONTENTS); byte[] certData = certString.getBytes(); CertificateFactory factory = CertificateFactory.getInstance("X.509"); ByteArrayInputStream certStream = new ByteArrayInputStream(certData); Collection<? extends Certificate> certs = factory .generateCertificates(certStream); System.out.println("certs=" + certs); } else { System.err.println("Unknown certificate type:" + subFilter); } } else { throw new IOException("Missing subfilter for cert dictionary"); } } else { System.out.println("Signature found, but no certificate"); } } } } finally { if (document != null) { document.close(); } } } }
From source file:PDFUtil.java
License:Apache License
boolean create() { PDDocument doc = new PDDocument(); doc.addPage(new PDPage()); File testExist = new File(path); if (!testExist.exists()) { try {/*www . java 2 s.com*/ doc.save(path); } catch (IOException e) { System.out.println("Path doesn't existed"); String dir = path.substring(0, path.lastIndexOf('\\')); File temp = new File(dir); //noinspection ResultOfMethodCallIgnored temp.mkdirs(); try { doc.save(path); } catch (IOException ignored) { } return false; } finally { try { doc.close(); } catch (IOException ignored) { } } } else { System.out.println("File existed, can't create file"); return false; } return true; }
From source file:CreateSignature.java
License:Apache License
/** * Signs the given PDF file.//from w ww .j a v a 2s . c o m * @param inFile input PDF file * @param outFile output PDF file * @param tsaClient optional TSA client * @throws IOException if the input file could not be read */ public void signDetached(File inFile, File outFile, TSAClient tsaClient) throws IOException { if (inFile == null || !inFile.exists()) { throw new FileNotFoundException("Document for signing does not exist"); } FileOutputStream fos = new FileOutputStream(outFile); // sign PDDocument doc = PDDocument.load(inFile); signDetached(doc, fos, tsaClient); doc.close(); }
From source file:CreateVisibleSignature.java
License:Apache License
/** * Sign pdf file and create new file that ends with "_signed.pdf". * * @param inputFile The source pdf document file. * @param signedFile The file to be signed. * @throws IOException/*from w ww. j a va 2 s .com*/ */ public void signPDF(File inputFile, File signedFile) throws IOException { if (inputFile == null || !inputFile.exists()) { throw new IOException("Document for signing does not exist"); } // creating output document and prepare the IO streams. FileOutputStream fos = new FileOutputStream(signedFile); // load document PDDocument doc = PDDocument.load(inputFile); // create signature dictionary PDSignature signature = new PDSignature(); signature.setFilter(PDSignature.FILTER_ADOBE_PPKLITE); // default filter // subfilter for basic and PAdES Part 2 signatures signature.setSubFilter(PDSignature.SUBFILTER_ADBE_PKCS7_DETACHED); signature.setName("signer name"); signature.setLocation("signer location"); signature.setReason("reason for signature"); // the signing date, needed for valid signature signature.setSignDate(Calendar.getInstance()); // register signature dictionary and sign interface if (visibleSignatureProperties != null && visibleSignatureProperties.isVisualSignEnabled()) { options = new SignatureOptions(); options.setVisualSignature(visibleSignatureProperties); options.setPage(visibleSignatureProperties.getPage() - 1); doc.addSignature(signature, this, options); } else { doc.addSignature(signature, this); } // write incremental (only for signing purpose) doc.saveIncremental(fos); doc.close(); // do not close options before saving, because some COSStream objects within options // are transferred to the signed document. IOUtils.closeQuietly(options); }
From source file:adams.core.io.PDFBox.java
License:Open Source License
/** * Closes the document again./* ww w .java 2 s . c o m*/ * * @param document the document to close, can be null */ public static void close(PDDocument document) { if (document != null) { try { document.close(); } catch (Exception e) { // ignored } } }
From source file:algorithm.PDFFileAttacher.java
License:Apache License
private void attachAll(File outputFile, List<File> payloadList) throws IOException { PDDocument document = PDDocument.load(outputFile); List<PDComplexFileSpecification> fileSpecifications = getFileSpecifications(document, payloadList); PDDocumentNameDictionary namesDictionary = new PDDocumentNameDictionary(document.getDocumentCatalog()); PDEmbeddedFilesNameTreeNode filesTree = namesDictionary.getEmbeddedFiles(); filesTree = new PDEmbeddedFilesNameTreeNode(); Map<String, COSObjectable> fileMap = new HashMap<String, COSObjectable>(); for (int i = 0; i < fileSpecifications.size(); i++) { fileMap.put("PericlesMetadata-" + i, fileSpecifications.get(i)); }//from w w w .j a v a 2s . c om filesTree.setNames(fileMap); namesDictionary.setEmbeddedFiles(filesTree); document.getDocumentCatalog().setNames(namesDictionary); try { document.save(outputFile); } catch (COSVisitorException e) { } document.close(); }