List of usage examples for org.apache.pdfbox.pdmodel PDDocument close
@Override public void close() throws IOException
From source file:fr.acxio.tools.agia.file.pdf.BasicPDDocumentContainer.java
License:Apache License
@Override public void close() throws IOException { if (document != null) { document.close();/*w w w .jav a2 s .co m*/ } for (int i = 0; parts != null && i < parts.size(); i++) { PDDocument aDocument = (PDDocument) parts.get(i); aDocument.close(); } }
From source file:fr.acxio.tools.agia.file.pdf.MergingPDDocumentFactory.java
License:Apache License
@Override public PDDocumentContainer fromParts(ResourcesFactory sResourcesFactory, Map<String, Object> sParameters) throws PDDocumentFactoryException { PDDocumentContainer aContainer = null; if (sResourcesFactory != null) { Map<String, Object> aParameters = getMergedParameters(sParameters); PDDocument aPart = null; List<PDDocument> aParts = new ArrayList<PDDocument>(); try {//from www. java 2 s .co m Resource[] aResources = sResourcesFactory.getResources(aParameters); if (aResources != null) { for (Resource aResource : aResources) { aPart = loadDocument(aResource.getFile(), aParameters); aParts.add(aPart); } } aContainer = new BasicPDDocumentContainer(null, aParts); } catch (Exception e) { Exception aException = e; try { if (aContainer != null) { aContainer.close(); } else if (aPart != null) { aPart.close(); } } catch (Exception ex) { aException = new PDDocumentFactoryException(ex); } throw new PDDocumentFactoryException(aException); } } return aContainer; }
From source file:fr.acxio.tools.agia.file.pdf.PageSplittingPDDocumentFactory.java
License:Apache License
@Override public PDDocumentContainer getDocument(File sFile, Map<String, Object> sParameters) throws PDDocumentFactoryException { Map<String, Object> aParameters = getMergedParameters(sParameters); PDDocumentContainer aResult = null;//from ww w . j a v a2s . c o m PDDocument document = null; try { document = loadDocument(sFile, aParameters); aResult = splitDocument(document, (Integer) aParameters.get(PARAM_STARTPAGE), (Integer) aParameters.get(PARAM_ENDPAGE), (Integer) aParameters.get(PARAM_SPLITATPAGE)); } catch (Exception e) { Exception aException = e; try { if (aResult != null) { aResult.close(); } else if (document != null) { document.close(); } } catch (Exception ex) { aException = new PDDocumentFactoryException(ex); } throw new PDDocumentFactoryException(aException); } return aResult; }
From source file:fr.acxio.tools.agia.file.pdf.PageSplittingPDDocumentFactory.java
License:Apache License
@Override public PDDocumentContainer getDocument(InputStream sInputStream, Map<String, Object> sParameters) throws PDDocumentFactoryException { Map<String, Object> aParameters = getMergedParameters(sParameters); PDDocumentContainer aResult = null;/*from w w w. j av a 2 s . c o m*/ PDDocument document = null; try { document = loadDocument(sInputStream, aParameters); aResult = splitDocument(document, (Integer) aParameters.get(PARAM_STARTPAGE), (Integer) aParameters.get(PARAM_ENDPAGE), (Integer) aParameters.get(PARAM_SPLITATPAGE)); } catch (Exception e) { Exception aException = e; try { if (aResult != null) { aResult.close(); } else if (document != null) { document.close(); } } catch (Exception ex) { aException = new PDDocumentFactoryException(ex); } throw new PDDocumentFactoryException(aException); } return aResult; }
From source file:fr.acxio.tools.agia.file.pdf.SplitPDFTasklet.java
License:Apache License
private int splitFile(Resource sSourceResource, ChunkContext sChunkContext) throws Exception { Map<String, Object> aDestinationParams = new HashMap<String, Object>(); aDestinationParams.put(ResourceFactoryConstants.PARAM_SOURCE, sSourceResource); aDestinationParams.put(ResourceFactoryConstants.PARAM_STEP_EXEC, ((sChunkContext != null) && (sChunkContext.getStepContext() != null)) ? sChunkContext.getStepContext().getStepExecution() : null);//ww w. j a v a 2 s . c om Resource aDestination = null; int aResult = 0; PDDocumentContainer aDocumentContainer = null; try { aDocumentContainer = documentFactory.getDocument(sSourceResource.getFile()); List<PDDocument> documents = aDocumentContainer.getParts(); for (int i = 0; i < documents.size(); i++) { PDDocument doc = documents.get(i); // Output file factory int aTryCount = 10; do { aDestination = destinationFactory.getResource(aDestinationParams); aTryCount--; } while (!forceReplace && (aTryCount > 0) && (aDestination != null) && aDestination.exists()); if ((aTryCount == 0) && !forceReplace) { throw new SplitPDFException("Cannot create a new destination filename"); } if (aDestination != null) { if (aDestination.exists() && LOGGER.isWarnEnabled()) { LOGGER.warn("Replacing {}", aDestination.getFile().getAbsolutePath()); } writeDocument(doc, aDestination.getFile().getAbsolutePath()); doc.close(); } else { throw new SplitPDFException("No destination specified"); } aResult++; } } finally { if (aDocumentContainer != null) { aDocumentContainer.close(); } } return aResult; }
From source file:fr.paris.lutece.plugins.lucene.service.indexer.PdfFileIndexer.java
License:Open Source License
/** * /*w w w. j a va 2 s .c o m*/ * {@inheritDoc} */ public String getContentToIndex(InputStream is) { String strContent = ""; PDDocument pdfDocument = null; try { pdfDocument = PDDocument.load(is); if (pdfDocument.isEncrypted()) { pdfDocument.decrypt(""); } StringWriter writer = new StringWriter(); PDFTextStripper stripper = new PDFTextStripper(); stripper.writeText(pdfDocument, writer); strContent = writer.getBuffer().toString(); } catch (CryptographyException e) { _log.error(e.getMessage(), e); } catch (IOException e) { _log.error(e.getMessage(), e); } catch (InvalidPasswordException e) { _log.error(e.getMessage(), e); } finally { if (pdfDocument != null) { try { pdfDocument.close(); } catch (IOException e) { _log.error(e.getMessage(), e); } } } return strContent; }
From source file:fr.univ_tours.etu.pdf.LucenePDFDocument.java
License:Apache License
/** * This will add the contents to the lucene document. * * @param document The document to add the contents to. * @param is The stream to get the contents from. * @param documentLocation The location of the document, used just for debug messages. * * @throws IOException If there is an error parsing the document. */// ww w . ja va 2s .c om private void addContent(Document document, InputStream is, String documentLocation) throws IOException { PDDocument pdfDocument = null; try { pdfDocument = PDDocument.load(is); // create a writer where to append the text content. StringWriter writer = new StringWriter(); if (stripper == null) { stripper = new PDFTextStripper(); } stripper.writeText(pdfDocument, writer); String contentsDirty = writer.getBuffer().toString(); //System.out.println(contentsDirty.substring(0,100)); String contents = contentsDirty.replaceAll("\\p{Sm}|\\p{Sk}|\\p{So}", " "); //System.out.println(contents); // addTextField(document, DocFields.CONTENTS, reader); TextField ne = this.getNamedEntities(contents); String lemmas = nlpNeTokenizer.getLemmaString(); //StringReader reader = new StringReader(contents); StringReader reader = new StringReader(lemmas); // Add the tag-stripped contents as a Reader-valued Text field so it will // get tokenized and indexed. FieldType type = new FieldType(); type.setIndexOptions(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS); type.setStored(false); type.setTokenized(true); document.add(new Field(DocFields.CONTENTS, reader, type)); PDDocumentInformation info = pdfDocument.getDocumentInformation(); if (info != null) { document.add(ne);//adding named entities addTextField(document, DocFields.AUTHOR, info.getAuthor()); try {//to avoid issues with CreationDate addUnstoredDate(document, DocFields.CREATION_DATE, info.getCreationDate().getTime()); } catch (Exception e) { System.out.println("Warning: some issue with CreationDate attribute!"); } addTextField(document, DocFields.CREATOR, info.getCreator()); addTextField(document, DocFields.KEYWORDS, info.getKeywords()); addTextField(document, DocFields.SUBJECT, info.getSubject()); addTextField(document, DocFields.TITLE, info.getTitle()); //addTextField(document, "Title", info.getTitle()); //addTextField(document, "ModificationDate", info.getModificationDate()); //addTextField(document, "Producer", info.getProducer()); //addTextField(document, "Trapped", info.getTrapped()); } int summarySize = Math.min(contents.length(), 1500); String summary = contents.substring(0, summarySize); // Add the summary as an UnIndexed field, so that it is stored and returned // with hit documents for display. addUnindexedField(document, DocFields.SUMMARY, summary); } finally { if (pdfDocument != null) { pdfDocument.close(); } } }
From source file:fr.univ_tours.etu.searcher.LucenePDFDocument.java
License:Apache License
/** * This will add the contents to the lucene document. * * @param document The document to add the contents to. * @param is The stream to get the contents from. * @param documentLocation The location of the document, used just for debug messages. * * @throws IOException If there is an error parsing the document. *//*from w ww . j a v a 2 s . c om*/ private void addContent(Document document, InputStream is, String documentLocation) throws IOException { PDDocument pdfDocument = null; try { pdfDocument = PDDocument.load(is); // create a writer where to append the text content. StringWriter writer = new StringWriter(); if (stripper == null) { stripper = new PDFTextStripper(); } stripper.writeText(pdfDocument, writer); // Note: the buffer to string operation is costless; // the char array value of the writer buffer and the content string // is shared as long as the buffer content is not modified, which will // not occur here. String contents = writer.getBuffer().toString(); StringReader reader = new StringReader(contents); // Add the tag-stripped contents as a Reader-valued Text field so it will // get tokenized and indexed. addTextField(document, "contents", reader); PDDocumentInformation info = pdfDocument.getDocumentInformation(); if (info != null) { addTextField(document, "Author", info.getAuthor()); addTextField(document, "CreationDate", info.getCreationDate()); addTextField(document, "Creator", info.getCreator()); addTextField(document, "Keywords", info.getKeywords()); addTextField(document, "ModificationDate", info.getModificationDate()); addTextField(document, "Producer", info.getProducer()); addTextField(document, "Subject", info.getSubject()); addTextField(document, "Title", info.getTitle()); addTextField(document, "Trapped", info.getTrapped()); } int summarySize = Math.min(contents.length(), 1500); String summary = contents.substring(0, summarySize); // Add the summary as an UnIndexed field, so that it is stored and returned // with hit documents for display. addUnindexedField(document, "summary", summary); } finally { if (pdfDocument != null) { pdfDocument.close(); } } }
From source file:function.PrintImageLocations.java
License:Apache License
/** * This will print the documents data./*w w w. j a v a 2s . c o m*/ * * @param args The command line arguments. * * @throws Exception If there is an error parsing the document. */ public static void main(String[] args) throws Exception { PDDocument document = null; try { document = PDDocument.load(new File("C:/Users/ATUL/Desktop/Page-layout/output1.pdf")); if (document.isEncrypted()) { document.decrypt(""); } PrintImageLocations printer = new PrintImageLocations(); List allPages = document.getDocumentCatalog().getAllPages(); for (int i = 0; i < allPages.size(); i++) { System.out.println("\n***********************************************************"); PDPage page = (PDPage) allPages.get(i); System.out.println("Processing page: " + (i + 1)); printer.processStream(page, page.findResources(), page.getContents().getStream()); } } finally { if (document != null) { document.close(); } } }
From source file:fys.BagagedatabaseController.java
private void sendToDatabase(int dr_id, int dr_personId, int dr_lafId, int tableFrom, int status, String airport, String frontname, String surname, String address, String shipaddress, String residence, String zipcode, String country, String phone, String mail, String labelnumber, String filePath, String flightnumber, String destination, int type, String brand, Integer color, String characteristics) throws IOException, SQLException { try {//from ww w .j a v a 2 s .c om conn = fys.connectToDatabase(conn); stmt = conn.createStatement(); //connectToDatabase(conn, stmt, "test", "root", "root"); String sql_person = "UPDATE bagagedatabase.person SET first_name='" + frontname + "'," + "surname='" + surname + "', address='" + address + "'," + "residence='" + residence + "', zip_code='" + zipcode + "'," + "country='" + country + "', phone='" + phone + "'," + "mail='" + mail + "'" + "WHERE person_id='" + dr_personId + "'"; stmt.executeUpdate(sql_person); String sql_lost = ""; String sql_airport = ""; String sql_status = ""; DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm"); Date date = new Date(); String dateTimeString = dateFormat.format(date); String[] tokens = dateTimeString.split(" "); if (tokens.length != 2) { throw new IllegalArgumentException(); } String dateString = tokens[0]; String timeString = tokens[1]; if (tableFrom == 0) { //0 = bagagedatabase.lost sql_lost = "UPDATE bagagedatabase.lost SET status='" + status + "'," + "picture='" + filePath + "', type='" + type + "', brand='" + brand + "'," + "color='" + color + "', characteristics='" + characteristics + "'" + "WHERE id='" + dr_id + "'"; //Registreer de status van een bagage. sql_status = "INSERT INTO luggage_status VALUES(" + dr_id + ", '" + dateString + "', '" + timeString + "', '" + status + "', 0);"; switch (status) { //case 0: Gaat van lost naar status Gevonden case 0: sql_airport = "UPDATE bagagedatabase.airport SET airport_found='" + airport + "'," + "label_number='" + labelnumber + "', flight_number='" + flightnumber + "'," + "destination='" + destination + "'" + "WHERE lost_and_found_id='" + dr_lafId + "'"; break; //case 3: Gaat van lost naar status Afgehandeld case 3: sql_airport = "UPDATE bagagedatabase.airport SET airport_found='" + airport + "'," + "label_number='" + labelnumber + "', flight_number='" + flightnumber + "'," + "destination='" + destination + "'" + "WHERE lost_and_found_id='" + dr_lafId + "'"; break; //default: Gaat van lost naar status Vermist, Vernietigd, Nooit Gevonden of Depot default: sql_airport = "UPDATE bagagedatabase.airport SET airport_lost='" + airport + "'," + "label_number='" + labelnumber + "', flight_number='" + flightnumber + "'," + "destination='" + destination + "'" + "WHERE lost_and_found_id='" + dr_lafId + "'"; break; } } else if (tableFrom == 1) { //1 = bagagedatabase.found sql_lost = "UPDATE bagagedatabase.found SET status='" + status + "'," + "picture='" + filePath + "', type='" + type + "', brand='" + brand + "'," + "color='" + color + "', characteristics='" + characteristics + "'" + "WHERE id='" + dr_id + "'"; //Registreer de status van een bagage. sql_status = "INSERT INTO luggage_status VALUES(" + dr_id + ", '" + dateString + "', '" + timeString + "', '" + status + "', 1);"; switch (status) { //case 1: Gaat van found naar status Vermist case 1: sql_airport = "UPDATE bagagedatabase.airport SET airport_lost='" + airport + "'," + "label_number='" + labelnumber + "', flight_number='" + flightnumber + "'," + "destination='" + destination + "'" + "WHERE lost_and_found_id='" + dr_lafId + "'"; break; //case 3: Gaat van found naar status Afgehandeld case 3: sql_airport = "UPDATE bagagedatabase.airport SET airport_lost='" + airport + "'," + "label_number='" + labelnumber + "', flight_number='" + flightnumber + "'," + "destination='" + destination + "'" + "WHERE lost_and_found_id='" + dr_lafId + "'"; break; //default: Gaat van found naar status Gevonden, Vernietigd, Nooit gevonden, Depot default: sql_airport = "UPDATE bagagedatabase.airport SET airport_found='" + airport + "'," + "label_number='" + labelnumber + "', flight_number='" + flightnumber + "'," + "destination='" + destination + "'" + "WHERE lost_and_found_id='" + dr_lafId + "'"; break; } } if (status != 6) { stmt.executeUpdate(sql_lost); } stmt.executeUpdate(sql_airport); if (status != fys.getStatusString(dr_status)) { stmt.executeUpdate(sql_status); } if (status != 3) { int pageid = 4; int type_email = 0; if (mailInput.getText() == null || !FYS.isValidEmailAddress(mailInput.getText()) || mailInput.getText().trim().isEmpty()) { } else { // Email bericht filteren op sommige woorden. String getmessage = fys.replaceEmail( fys.replaceEmail_tF( fys.Email_Message(type_email, fys.Email_Language(mailInput.getText()), pageid), mailInput.getText(), Integer.parseInt(tableFromLabel.getText())), mailInput.getText()); // Email versturen fys.sendEmail(mailInput.getText(), fys.Email_Subject(type_email, fys.Email_Language(mailInput.getText()), pageid), getmessage, "Sent message successfully...."); } } /*Indien de status wordt veranderd naar afgehandeld wordt er een DHL- formulier gemaakt. DISCLAIMER: Het DHL-formulier dat gemaakt wordt is gebaseerd op het officile DHL-emailshipment formulier dat is te vinden op 'http://www.dhl.com/en/express/resource_center/emailship.html'. Het formulier is gekopieerd en aangepast d.m.v. Adobe Acrobat DC en is louter bedoeld voor demonstratieve doeleinden. */ if (status == 3) { //Afgehandeld //Maak nieuwe PDF-document aan de hand van de template File pdfdoc = new File("src/fys/templates/dhltemplate.pdf"); PDDocument document; document = PDDocument.load(pdfdoc); //Laad alle inputvelden op het formulier PDAcroForm acroForm = document.getDocumentCatalog().getAcroForm(); List<PDField> fields = acroForm.getFields(); //Vul alle inputvelden in met de waardes uit de database for (PDField field : fields) { if (field.getFullyQualifiedName().equals("companyName_field")) { field.setValue("Corendon"); } if (field.getFullyQualifiedName().equals("country_field")) { field.setValue(country); } if (field.getFullyQualifiedName().equals("address_field")) { field.setValue(shipaddress); } if (field.getFullyQualifiedName().equals("city_field")) { field.setValue(residence); } if (field.getFullyQualifiedName().equals("postcode_field")) { field.setValue(zipcode); } if (field.getFullyQualifiedName().equals("contactPerson_field")) { field.setValue(frontname + " " + surname); } if (field.getFullyQualifiedName().equals("phone_field")) { field.setValue(phone); } if (field.getFullyQualifiedName().equals("type_field")) { field.setValue("International NonDocument"); } if (field.getFullyQualifiedName().equals("product_field")) { field.setValue("Express WorldWide"); } if (field.getFullyQualifiedName().equals("notification_field")) { field.setValue("fysepsilon@gmail.com "); } if (field.getFullyQualifiedName().equals("content_field")) { field.setValue(fys.getBaggageType(type)); } if (field.getFullyQualifiedName().equals("date_field")) { field.setValue(dateString); } } //Sla het document op document.save("src/fys/formulieren/dhlFormulier" + frontname + surname + dr_personId + ".pdf"); document.close(); int pageid = 5; int type_email = 0; if (mailInput.getText() == null || !FYS.isValidEmailAddress(mailInput.getText()) || mailInput.getText().trim().isEmpty()) { } else { // Email bericht filteren op sommige woorden. String getmessage = fys.replaceEmail( fys.replaceEmail_tF( fys.Email_Message(type_email, fys.Email_Language(mailInput.getText()), pageid), mailInput.getText(), Integer.parseInt(tableFromLabel.getText())), mailInput.getText()); // Email versturen fys.sendEmail(mailInput.getText(), fys.Email_Subject(type_email, fys.Email_Language(mailInput.getText()), pageid), getmessage, "Sent message successfully...."); } } if (status == 4) { //Nooit gevonden int pageid = 6; //Pagina id int type_email = 3; //Onbekend int language_email = 1; //Nederlands ?! String email_paymentdepartment = "fysepsilon@gmail.com"; // Betalingsafdeling mail if (mailInput.getText() == null || !FYS.isValidEmailAddress(mailInput.getText()) || mailInput.getText().trim().isEmpty()) { } else { // Email bericht filteren op sommige woorden. String getmessage = fys.replaceEmail( fys.replaceEmail_tF(fys.Email_Message(type_email, language_email, pageid), mailInput.getText(), Integer.parseInt(tableFromLabel.getText())), mailInput.getText()); // Email versturen fys.sendEmail(email_paymentdepartment, fys.Email_Subject(type_email, language_email, pageid), getmessage, "Sent message successfully...."); } } pictureButton.setText(taal[44]); fys.changeToAnotherFXML(taal[100], "bagagedatabase.fxml"); conn.close(); } catch (SQLException ex) { // handle any errors System.out.println("SQLException: " + ex.getMessage()); System.out.println("SQLState: " + ex.getSQLState()); System.out.println("VendorError: " + ex.getErrorCode()); } }