List of usage examples for com.lowagie.text.pdf PdfReader getInfo
public HashMap getInfo()
HashMap
of String
. From source file:it.pdfsam.console.tools.pdf.PdfConcat.java
License:Open Source License
/** * Execute the concat command. On error an exception is thrown. * @throws ConcatException/*from w w w .j av a 2 s.c o m*/ */ public void execute() throws ConcatException { try { percentageChanged(0, 0); out_message = ""; String file_name; int pageOffset = 0; ArrayList master = new ArrayList(); int f = 0; Document pdf_document = null; PdfConcatenator pdf_writer = null; int total_processed_pages = 0; String[] page_selection = u_string.split(":"); File tmp_o_file = TmpFileNameGenerator.generateTmpFile(o_file.getParent()); PdfReader pdf_reader; for (Iterator f_list_itr = f_list.iterator(); f_list_itr.hasNext();) { String current_p_selection; //get page selection. If arrayoutofbounds default behaviour is "all" try { current_p_selection = page_selection[f].toLowerCase(); if (current_p_selection.equals("")) current_p_selection = "all"; } catch (Exception e) { current_p_selection = "all"; } //validation if (!(Pattern.compile("([0-9]+[-][0-9]+)|(all)", Pattern.CASE_INSENSITIVE) .matcher(current_p_selection).matches())) { String errorMsg = ""; try { tmp_o_file.delete(); } catch (Exception e) { errorMsg = " Unable to delete temporary file."; } throw new ConcatException( "ValidationError: Syntax error on " + current_p_selection + "." + errorMsg); } file_name = f_list_itr.next().toString(); //reader creation pdf_reader = new PdfReader(new RandomAccessFileOrArray(file_name), null); pdf_reader.consolidateNamedDestinations(); int pdf_number_of_pages = pdf_reader.getNumberOfPages(); //default behaviour int start = 0; int end_page = pdf_number_of_pages; if (!(current_p_selection.equals("all"))) { boolean valid = true; String exceptionMsg = ""; String[] limits = current_p_selection.split("-"); try { start = Integer.parseInt(limits[0]); end_page = Integer.parseInt(limits[1]); } catch (Exception ex) { valid = false; exceptionMsg += "ValidationError: Syntax error on " + current_p_selection + "."; try { tmp_o_file.delete(); } catch (Exception e) { exceptionMsg += " Unable to delete temporary file."; } } if (valid) { //validation if (start < 0) { valid = false; exceptionMsg = "ValidationError: Syntax error. " + (start) + " must be positive in " + current_p_selection + "."; try { tmp_o_file.delete(); } catch (Exception e) { exceptionMsg += " Unable to delete temporary file."; } } else if (end_page > pdf_number_of_pages) { valid = false; exceptionMsg = "ValidationError: Cannot merge at page " + end_page + ". No such page."; try { tmp_o_file.delete(); } catch (Exception e) { exceptionMsg += " Unable to delete temporary file."; } } else if (start > end_page) { valid = false; exceptionMsg = "ValidationError: Syntax error. " + (start) + " is bigger than " + end_page + " in " + current_p_selection + "."; try { tmp_o_file.delete(); } catch (Exception e) { exceptionMsg += " Unable to delete temporary file."; } } } if (!valid) { throw new ConcatException(exceptionMsg); } } List bookmarks = SimpleBookmark.getBookmark(pdf_reader); if (bookmarks != null) { //if the end page is not the end of the doc, delete bookmarks after it if (end_page < pdf_number_of_pages) { SimpleBookmark.eliminatePages(bookmarks, new int[] { end_page + 1, pdf_number_of_pages }); } // if start page isn't the first page of the document, delete bookmarks before it if (start > 0) { SimpleBookmark.eliminatePages(bookmarks, new int[] { 1, start }); //bookmarks references must be taken back SimpleBookmark.shiftPageNumbers(bookmarks, -start, null); } if (pageOffset != 0) { SimpleBookmark.shiftPageNumbers(bookmarks, pageOffset, null); } master.addAll(bookmarks); } pageOffset += (end_page - start); out_message += LogFormatter.formatMessage(file_name + ": " + end_page + " pages-\n"); if (f == 0) { if (copyfields_boolean) { // step 1: we create a writer pdf_writer = new PdfCopyFieldsConcatenator(new FileOutputStream(tmp_o_file), compressed_boolean); HashMap meta = pdf_reader.getInfo(); meta.put("Creator", MainConsole.CREATOR); } else { // step 1: creation of a document-object pdf_document = new Document(pdf_reader.getPageSizeWithRotation(1)); // step 2: we create a writer that listens to the document pdf_writer = new PdfSimpleConcatenator(pdf_document, new FileOutputStream(tmp_o_file), compressed_boolean); // step 3: we open the document MainConsole.setDocumentCreator(pdf_document); pdf_document.open(); } out_message += LogFormatter.formatMessage("Temporary file created-\n"); } // step 4: we add content pdf_reader.selectPages(start + "-" + end_page); pdf_writer.addDocument(pdf_reader); //fix 03/07 //pdf_reader = null; pdf_reader.close(); pdf_writer.freeReader(pdf_reader); total_processed_pages += end_page - start + 1; out_message += LogFormatter.formatMessage((end_page - start) + " pages processed correctly-\n"); f++; try { percentageChanged((f * 100) / f_list.size(), (end_page - start)); } catch (RuntimeException re) { out_message += LogFormatter.formatMessage("RuntimeException: " + re.getMessage() + "\n"); } } if (master.size() > 0) { pdf_writer.setOutlines(master); } out_message += LogFormatter.formatMessage("Total processed pages: " + total_processed_pages + "-\n"); // step 5: we close the document if (pdf_document != null) { pdf_document.close(); } pdf_writer.close(); // step 6: temporary buffer moved to output file renameTemporaryFile(tmp_o_file, o_file, overwrite_boolean); } catch (Exception e) { throw new ConcatException(e); } finally { workCompleted(); } }
From source file:it.pdfsam.console.tools.pdf.PdfEncrypt.java
License:Open Source License
/** * Execute the encrypt command. On error an exception is thrown. * @throws EncryptException//from w w w . j a v a 2 s . co m */ public void execute() throws EncryptException { try { workingIndeterminate(); out_message = ""; int f = 0; for (Iterator f_list_itr = f_list.iterator(); f_list_itr.hasNext();) { String file_name = f_list_itr.next().toString(); prefixParser = new PrefixParser(prefix_value, new File(file_name).getName()); File tmp_o_file = TmpFileNameGenerator.generateTmpFile(o_dir.getAbsolutePath()); out_message += LogFormatter.formatMessage("Temporary file created-\n"); PdfReader pdfReader = new PdfReader(new RandomAccessFileOrArray(file_name), null); HashMap meta = pdfReader.getInfo(); meta.put("Creator", MainConsole.CREATOR); PdfStamper pdfStamper = new PdfStamper(pdfReader, new FileOutputStream(tmp_o_file)); if (compressed_boolean) { pdfStamper.setFullCompression(); } pdfStamper.setMoreInfo(meta); pdfStamper.setEncryption(etype, u_pwd, a_pwd, user_permissions); pdfStamper.close(); /*PdfEncryptor.encrypt(pdf_reader,new FileOutputStream(tmp_o_file), etype, u_pwd, a_pwd,user_permissions, meta);*/ File out_file = new File(o_dir, prefixParser.generateFileName()); renameTemporaryFile(tmp_o_file, out_file, overwrite_boolean); f++; } out_message += LogFormatter.formatMessage("Pdf files encrypted in " + o_dir.getAbsolutePath() + "-\n" + PdfEncryptor.getPermissionsVerbose(user_permissions)); } catch (Exception e) { throw new EncryptException(e); } finally { workCompleted(); } }
From source file:lucee.runtime.text.pdf.PDFDocument.java
License:Open Source License
public Struct getInfo() { PdfReader pr = null; try {//from w ww . ja v a2s. c o m pr = getPdfReader(); //PdfDictionary catalog = pr.getCatalog(); int permissions = pr.getPermissions(); boolean encrypted = pr.isEncrypted(); Struct info = new StructImpl(); info.setEL("FilePath", getFilePath()); // access info.setEL("ChangingDocument", allowed(encrypted, permissions, PdfWriter.ALLOW_MODIFY_CONTENTS)); info.setEL("Commenting", allowed(encrypted, permissions, PdfWriter.ALLOW_MODIFY_ANNOTATIONS)); info.setEL("ContentExtraction", allowed(encrypted, permissions, PdfWriter.ALLOW_SCREENREADERS)); info.setEL("CopyContent", allowed(encrypted, permissions, PdfWriter.ALLOW_COPY)); info.setEL("DocumentAssembly", allowed(encrypted, permissions, PdfWriter.ALLOW_ASSEMBLY + PdfWriter.ALLOW_MODIFY_CONTENTS)); info.setEL("FillingForm", allowed(encrypted, permissions, PdfWriter.ALLOW_FILL_IN + PdfWriter.ALLOW_MODIFY_ANNOTATIONS)); info.setEL("Printing", allowed(encrypted, permissions, PdfWriter.ALLOW_PRINTING)); info.setEL("Secure", ""); info.setEL("Signing", allowed(encrypted, permissions, PdfWriter.ALLOW_MODIFY_ANNOTATIONS + PdfWriter.ALLOW_MODIFY_CONTENTS + PdfWriter.ALLOW_FILL_IN)); info.setEL("Encryption", encrypted ? "Password Security" : "No Security");// MUST info.setEL("TotalPages", Caster.toDouble(pr.getNumberOfPages())); info.setEL("Version", "1." + pr.getPdfVersion()); info.setEL("permissions", "" + permissions); info.setEL("permiss", "" + PdfWriter.ALLOW_FILL_IN); info.setEL("Application", ""); info.setEL("Author", ""); info.setEL("CenterWindowOnScreen", ""); info.setEL("Created", ""); info.setEL("FitToWindow", ""); info.setEL("HideMenubar", ""); info.setEL("HideToolbar", ""); info.setEL("HideWindowUI", ""); info.setEL("Keywords", ""); info.setEL("Language", ""); info.setEL("Modified", ""); info.setEL("PageLayout", ""); info.setEL("Producer", ""); info.setEL("Properties", ""); info.setEL("ShowDocumentsOption", ""); info.setEL("ShowWindowsOption", ""); info.setEL("Subject", ""); info.setEL("Title", ""); info.setEL("Trapped", ""); // info HashMap imap = pr.getInfo(); Iterator it = imap.entrySet().iterator(); Map.Entry entry; while (it.hasNext()) { entry = (Entry) it.next(); info.setEL(Caster.toString(entry.getKey(), null), entry.getValue()); } return info; } catch (PageException pe) { throw new PageRuntimeException(pe); } finally { if (pr != null) pr.close(); } }
From source file:net.laubenberger.bogatyr.helper.HelperPdf.java
License:Open Source License
/** * Modifies the meta data of given PDF and stores it in a new {@link File}. * <strong>Meta data example:"</strong> metadata.put("Title", "Example"); * metadata.put("Author", "Stefan Laubenberger"); metadata.put("Subject", * "Example PDF meta data"); metadata.put("Keywords", "Example, PDF"); * metadata.put("Creator", "http://www.laubenberger.net/"); * metadata.put("Producer", "Silvan Spross"); * //from ww w .ja v a 2 s . com * @param source * {@link File} * @param dest * {@link File} for the modified PDF * @param metadata * list with the new meta data informations * @throws DocumentException * @throws IOException * @since 0.7.0 */ @SuppressWarnings("unchecked") public static void setMetaData(final File source, final File dest, final Map<String, String> metadata) throws IOException, DocumentException { // $JUnit$ if (log.isDebugEnabled()) log.debug(HelperLog.methodStart(source, dest, metadata)); if (null == source) { throw new RuntimeExceptionIsNull("source"); //$NON-NLS-1$ } if (null == dest) { throw new RuntimeExceptionIsNull("dest"); //$NON-NLS-1$ } if (HelperObject.isEquals(source, dest)) { throw new RuntimeExceptionIsEquals("source", "dest"); //$NON-NLS-1$ //$NON-NLS-2$ } if (null == metadata) { throw new RuntimeExceptionIsNull("metadata"); //$NON-NLS-1$ } PdfReader reader = null; PdfStamper stamper = null; try { reader = new PdfReader(source.getAbsolutePath()); stamper = new PdfStamper(reader, new FileOutputStream(dest)); final HashMap<String, String> info = reader.getInfo(); info.putAll(metadata); stamper.setMoreInfo(info); } finally { if (null != stamper) { stamper.close(); } if (null != reader) { reader.close(); } } if (log.isDebugEnabled()) log.debug(HelperLog.methodExit()); }
From source file:net.laubenberger.bogatyr.helper.HelperPdf.java
License:Open Source License
/** * Returns the metadata of a given PDF as {@link Map}. * /* ww w .j a v a 2 s . c o m*/ * @param file * input as PDF * @return {@link Map} containinfg the metadata of the given PDF * @throws IOException * @see File * @since 0.9.4 */ @SuppressWarnings("unchecked") public static Map<String, String> getMetaData(final File file) throws IOException { // $JUnit$ if (log.isDebugEnabled()) log.debug(HelperLog.methodStart(file)); if (null == file) { throw new RuntimeExceptionIsNull("file"); //$NON-NLS-1$ } PdfReader reader = null; Map<String, String> result; try { reader = new PdfReader(file.getAbsolutePath()); result = reader.getInfo(); } finally { if (null != reader) { reader.close(); } } if (log.isDebugEnabled()) log.debug(HelperLog.methodExit(result)); return result; }
From source file:net.laubenberger.wichtel.helper.HelperPdf.java
License:Open Source License
/** * Modifies the meta data of given PDF and stores it in a new {@link File}. * <strong>Meta data example:"</strong> metadata.put("Title", "Example"); * metadata.put("Author", "Stefan Laubenberger"); metadata.put("Subject", * "Example PDF meta data"); metadata.put("Keywords", "Example, PDF"); * metadata.put("Creator", "http://www.laubenberger.net/"); * metadata.put("Producer", "Silvan Spross"); * // w w w .j a v a2 s .c om * @param source * {@link File} * @param dest * {@link File} for the modified PDF * @param metadata * list with the new meta data informations * @throws DocumentException * @throws IOException * @since 0.0.1 */ @SuppressWarnings("unchecked") public static void setMetaData(final File source, final File dest, final Map<String, String> metadata) throws IOException, DocumentException { // $JUnit$ if (log.isDebugEnabled()) log.debug(HelperLog.methodStart(source, dest, metadata)); if (null == source) { throw new RuntimeExceptionIsNull("source"); //$NON-NLS-1$ } if (null == dest) { throw new RuntimeExceptionIsNull("dest"); //$NON-NLS-1$ } if (HelperObject.isEquals(source, dest)) { throw new RuntimeExceptionIsEquals("source", "dest"); //$NON-NLS-1$ //$NON-NLS-2$ } if (null == metadata) { throw new RuntimeExceptionIsNull("metadata"); //$NON-NLS-1$ } try (FileOutputStream fos = new FileOutputStream(dest)) { final PdfReader reader = new PdfReader(source.getAbsolutePath()); final PdfStamper stamper = new PdfStamper(reader, fos); final HashMap<String, String> info = reader.getInfo(); info.putAll(metadata); stamper.setMoreInfo(info); stamper.close(); reader.close(); } if (log.isDebugEnabled()) log.debug(HelperLog.methodExit()); }
From source file:net.mitnet.tools.pdf.book.pdf.itext.PdfReaderHelper.java
License:Open Source License
public PdfReaderHelper(PdfReader pdfReader) { this.pdfReader = pdfReader; this.pdfInfo = pdfReader.getInfo(); }
From source file:org.apache.camel.dataformat.jasperreports.JasperReportsTestBase.java
License:Open Source License
protected Map<String, String> getPdfInfo(MockEndpoint mock) throws IOException { Exchange exchange = mock.getReceivedExchanges().get(0); byte[] bytes = exchange.getIn().getBody(byte[].class); // read and parse a pdf PdfReader reader = new PdfReader(bytes); return reader.getInfo(); }
From source file:org.lucee.extension.pdf.PDFStruct.java
License:Open Source License
public Struct getInfo() { PdfReader pr = null; try {// w w w . j a v a 2s. c o m pr = getPdfReader(); // PdfDictionary catalog = pr.getCatalog(); int permissions = pr.getPermissions(); boolean encrypted = pr.isEncrypted(); Struct info = CFMLEngineFactory.getInstance().getCreationUtil().createStruct(); info.setEL("FilePath", getFilePath()); // access info.setEL("ChangingDocument", allowed(encrypted, permissions, PdfWriter.ALLOW_MODIFY_CONTENTS)); info.setEL("Commenting", allowed(encrypted, permissions, PdfWriter.ALLOW_MODIFY_ANNOTATIONS)); info.setEL("ContentExtraction", allowed(encrypted, permissions, PdfWriter.ALLOW_SCREENREADERS)); info.setEL("CopyContent", allowed(encrypted, permissions, PdfWriter.ALLOW_COPY)); info.setEL("DocumentAssembly", allowed(encrypted, permissions, PdfWriter.ALLOW_ASSEMBLY + PdfWriter.ALLOW_MODIFY_CONTENTS)); info.setEL("FillingForm", allowed(encrypted, permissions, PdfWriter.ALLOW_FILL_IN + PdfWriter.ALLOW_MODIFY_ANNOTATIONS)); info.setEL("Printing", allowed(encrypted, permissions, PdfWriter.ALLOW_PRINTING)); info.setEL("Secure", ""); info.setEL("Signing", allowed(encrypted, permissions, PdfWriter.ALLOW_MODIFY_ANNOTATIONS + PdfWriter.ALLOW_MODIFY_CONTENTS + PdfWriter.ALLOW_FILL_IN)); info.setEL("Encryption", encrypted ? "Password Security" : "No Security");// MUST info.setEL("TotalPages", CFMLEngineFactory.getInstance().getCastUtil().toDouble(pr.getNumberOfPages())); info.setEL("Version", "1." + pr.getPdfVersion()); info.setEL("permissions", "" + permissions); info.setEL("permiss", "" + PdfWriter.ALLOW_FILL_IN); info.setEL("Application", ""); info.setEL("Author", ""); info.setEL("CenterWindowOnScreen", ""); info.setEL("Created", ""); info.setEL("FitToWindow", ""); info.setEL("HideMenubar", ""); info.setEL("HideToolbar", ""); info.setEL("HideWindowUI", ""); info.setEL("Keywords", ""); info.setEL("Language", ""); info.setEL("Modified", ""); info.setEL("PageLayout", ""); info.setEL("Producer", ""); info.setEL("Properties", ""); info.setEL("ShowDocumentsOption", ""); info.setEL("ShowWindowsOption", ""); info.setEL("Subject", ""); info.setEL("Title", ""); info.setEL("Trapped", ""); // info HashMap imap = pr.getInfo(); Iterator it = imap.entrySet().iterator(); Map.Entry entry; while (it.hasNext()) { entry = (Entry) it.next(); info.setEL(CFMLEngineFactory.getInstance().getCastUtil().toString(entry.getKey(), null), entry.getValue()); } return info; } catch (PageException pe) { throw CFMLEngineFactory.getInstance().getExceptionUtil().createPageRuntimeException(pe); } finally { if (pr != null) pr.close(); } }
From source file:org.mnsoft.pdfocr.CreatorSetter.java
License:Open Source License
/** * @param args/*from ww w. j ava 2 s . co m*/ * @throws DocumentException * @throws IOException * @throws IOException * @throws BadPdfFormatException */ @SuppressWarnings("rawtypes") public static void main(String[] args) throws DocumentException, IOException { /* * Verify arguments */ if ((args == null) || (args.length < 2)) { System.err.println("Usage: first parameter: Creator to set, following parameters: Files to work on."); System.exit(1); } final String creator = args[0]; for (int i = 1; i < args.length; i++) { final File f = new File(args[i]); if ((f == null) || !f.exists() || !f.isFile() || !f.getName().endsWith(".pdf")) { System.err.println("! ERROR: Could not read " + args[i] + " or this is not a .pdf"); continue; } final String p = f.getAbsolutePath(); /* * Open the reader */ PdfReader reader; try { reader = new PdfReader(p); } catch (Exception e) { System.err.println("! ERROR: " + e.getMessage() + " File: " + p); continue; } /* * Get the document information */ Map info = reader.getInfo(); /* * Get the document creator. If the document * has already been worked on, continue with * the next document. */ String doc_creator = (String) info.get("Creator"); if (creator.equals(doc_creator)) { System.out.println("+ INFO: File " + p + " had already the right creator."); continue; } /* * Get the document time stamp so that we can set it later. */ final Date doc_timestamp = new Date(f.lastModified()); /* * Get the number of pages in the original file */ int nOri = reader.getNumberOfPages(); System.out.print("+ INFO: Working on: " + p + " (" + nOri + " pages) ... "); /* * Get the remaining meta data */ String doc_title = ((String) info.get("Title") == null) ? "" : (String) info.get("Title"); String doc_subject = ((String) info.get("Subject") == null) ? "" : (String) info.get("Subject"); String doc_keywords = ((String) info.get("Keywords") == null) ? "" : (String) info.get("Keywords"); String doc_author = ((String) info.get("Author") == null) ? "" : (String) info.get("Author"); reader.close(); /* * Set the creator to our marker */ doc_creator = creator; /* * Merge the new document with the meta * data from the original document */ try { reader = new PdfReader(p); } catch (Exception e) { System.err.println("! ERROR: " + e.getMessage() + " File: " + p); continue; } /* * Get the document information */ info = reader.getInfo(); /* * Get the document creator. If the document * has already been worked on, we assume we * have had a successful output from the OCR * engine */ String doc_creator_copy = (String) info.get("Creator"); if (creator.equals(doc_creator_copy)) { System.out.println(); continue; } /* * Step 1: creation of a document object */ final Document document = new Document(reader.getPageSizeWithRotation(1)); /* * Step 2: we create a writer that listens to the document */ PdfCopy writer = new PdfCopy(document, new FileOutputStream(p + ".tmp")); /* * Step 3: we add the meta data */ document.addTitle(doc_title); document.addSubject(doc_subject); document.addKeywords(doc_keywords); document.addCreator(creator); document.addAuthor(doc_author); /* * Step 4: we open the document */ document.open(); PdfImportedPage page; int j = 0; /* * Step 5: we add content */ while (j < nOri) { j++; page = writer.getImportedPage(reader, j); writer.addPage(page); System.out.print("[" + j + "] "); } PRAcroForm form = reader.getAcroForm(); if (form != null) { writer.copyAcroForm(reader); } System.out.println(); /* * Step 6: we close the document */ document.close(); reader.close(); /* * Set the file access time and * rename the file. */ File file = new File(p + ".tmp"); if (file.exists()) { deleteFile(p); file.setLastModified(doc_timestamp.getTime()); file.renameTo(new File(p)); } } }