List of usage examples for com.lowagie.text.pdf PdfCopy copyAcroForm
public void copyAcroForm(PdfReader reader) throws IOException, BadPdfFormatException
From source file:org.lucee.extension.pdf.util.PDFUtil.java
License:Open Source License
/** * @param docs/*from w ww. j ava2 s. com*/ * @param os * @param removePages * if true, pages defined in PDFDocument will be removed, otherwise all other pages will be removed * @param version * @throws PageException * @throws IOException * @throws DocumentException */ public static void concat(PDFStruct[] docs, OutputStream os, boolean keepBookmark, boolean removePages, boolean stopOnError, char version) throws PageException, IOException, DocumentException { Document document = null; PdfCopy writer = null; PdfReader reader; Set pages; boolean isInit = false; PdfImportedPage page; try { int pageOffset = 0; ArrayList master = new ArrayList(); for (int i = 0; i < docs.length; i++) { // we create a reader for a certain document pages = docs[i].getPages(); try { reader = docs[i].getPdfReader(); } catch (Throwable t) { if (t instanceof ThreadDeath) throw (ThreadDeath) t; if (!stopOnError) continue; throw CFMLEngineFactory.getInstance().getCastUtil().toPageException(t); } reader.consolidateNamedDestinations(); // we retrieve the total number of pages int n = reader.getNumberOfPages(); List bookmarks = keepBookmark ? SimpleBookmark.getBookmark(reader) : null; if (bookmarks != null) { removeBookmarks(bookmarks, pages, removePages); if (pageOffset != 0) SimpleBookmark.shiftPageNumbers(bookmarks, pageOffset, null); master.addAll(bookmarks); } if (!isInit) { isInit = true; document = new Document(reader.getPageSizeWithRotation(1)); writer = new PdfCopy(document, os); if (version != 0) writer.setPdfVersion(version); document.open(); } for (int y = 1; y <= n; y++) { if (pages != null && removePages == pages.contains(Integer.valueOf(y))) { continue; } pageOffset++; page = writer.getImportedPage(reader, y); writer.addPage(page); } PRAcroForm form = reader.getAcroForm(); if (form != null) writer.copyAcroForm(reader); } if (master.size() > 0) writer.setOutlines(master); } finally { CFMLEngineFactory.getInstance().getIOUtil().closeSilent(document); } }
From source file:org.lucee.extension.pdf.util.PDFUtil.java
License:Open Source License
public static void encrypt(PDFStruct doc, OutputStream os, String newUserPassword, String newOwnerPassword, int permissions, int encryption) throws PageException, DocumentException, IOException { byte[] user = newUserPassword == null ? null : newUserPassword.getBytes(); byte[] owner = newOwnerPassword == null ? null : newOwnerPassword.getBytes(); PdfReader pr = doc.getPdfReader();// w ww . ja va2s . com List bookmarks = SimpleBookmark.getBookmark(pr); int n = pr.getNumberOfPages(); Document document = new Document(pr.getPageSizeWithRotation(1)); PdfCopy writer = new PdfCopy(document, os); if (encryption != ENCRYPT_NONE) writer.setEncryption(user, owner, permissions, encryption); document.open(); PdfImportedPage page; for (int i = 1; i <= n; i++) { page = writer.getImportedPage(pr, i); writer.addPage(page); } PRAcroForm form = pr.getAcroForm(); if (form != null) writer.copyAcroForm(pr); if (bookmarks != null) writer.setOutlines(bookmarks); document.close(); }
From source file:org.mnsoft.pdfocr.CreatorSetter.java
License:Open Source License
/** * @param args/*from w ww .j a v a2 s . c o 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)); } } }
From source file:org.mnsoft.pdfocr.PDFTrans.java
License:Open Source License
/** * @param args the command line arguments *///from w w w . j av a 2 s. c o m @SuppressWarnings({ "deprecation", "rawtypes" }) public static void main(String[] args) { if (args.length < 2) { usage(); } String input_file = null, output_file = null, doc_title = null, doc_subject = null, doc_keywords = null, doc_creator = null, doc_author = null, user_passwd = null, owner_passwd = null; boolean encrypt = false; boolean encryption_bits = PdfWriter.STRENGTH128BITS; int permissions = 0; boolean print_info = false; boolean print_keywords = false; /* * parse options */ for (int i = 0; i < args.length; i++) { if (args[i].equals("--title")) { doc_title = args[++i]; } else if (args[i].equals("--subject")) { doc_subject = args[++i]; } else if (args[i].equals("--keywords")) { doc_keywords = args[++i]; } else if (args[i].equals("--creator")) { doc_creator = args[++i]; } else if (args[i].equals("--author")) { doc_author = args[++i]; } else if (args[i].equals("--print-info")) { print_info = true; } else if (args[i].equals("--print-keywords")) { print_keywords = true; } else if (args[i].equals("--user-password")) { encrypt = true; user_passwd = args[++i]; } else if (args[i].equals("--master-password")) { encrypt = true; owner_passwd = args[++i]; } else if (args[i].equals("--encryption-bits")) { i++; encrypt = true; if (args[i].equals("128")) { encryption_bits = PdfWriter.STRENGTH128BITS; } else if (args[i].equals("40")) { encryption_bits = PdfWriter.STRENGTH40BITS; } else { usage(); } continue; } else if (args[i].equals("--permissions")) { i++; StringTokenizer st = new StringTokenizer(args[i], ","); while (st.hasMoreTokens()) { String s = st.nextToken(); if (s.equals("print")) { permissions |= PdfWriter.AllowPrinting; } else if (s.equals("degraded-print")) { permissions |= PdfWriter.AllowDegradedPrinting; } else if (s.equals("copy")) { permissions |= PdfWriter.AllowCopy; } else if (s.equals("modify-contents")) { permissions |= PdfWriter.AllowModifyContents; } else if (s.equals("modify-annotations")) { permissions |= PdfWriter.AllowModifyAnnotations; } else if (s.equals("assembly")) { permissions |= PdfWriter.AllowAssembly; } else if (s.equals("fill-in")) { permissions |= PdfWriter.AllowFillIn; } else if (s.equals("screen-readers")) { permissions |= PdfWriter.AllowScreenReaders; } else { warning("Unknown permission '" + s + "' ignored"); } } continue; } else if (args[i].startsWith("--")) { error("Unknown option '" + args[i] + "'"); } else if (input_file == null) { input_file = args[i]; } else if (output_file == null) { output_file = args[i]; } else { usage(); } } if (!print_keywords) { if ((input_file == null) || (output_file == null)) { usage(); } if (input_file.equals(output_file)) { error("Input and output files must be different"); } } try { /* * we create a reader for the input file */ if (!print_keywords) { System.out.println("Reading " + input_file + "..."); } PdfReader reader = new PdfReader(input_file); /* * we retrieve the total number of pages */ final int n = reader.getNumberOfPages(); if (!print_keywords) { System.out.println("There are " + n + " pages in the original file."); } /* * get the document information */ final Map info = reader.getInfo(); /* * print the document information if asked to do so */ if (print_info) { System.out.println("Document information:"); final Iterator it = info.entrySet().iterator(); while (it.hasNext()) { final Map.Entry entry = (Map.Entry) it.next(); System.out.println(entry.getKey() + " = \"" + entry.getValue() + "\""); } } if (print_keywords) { String keywords = "" + info.get("Keywords"); if ((null == keywords) || "null".equals(keywords)) { keywords = ""; } System.out.println(keywords); System.exit(0); } /* * if any meta data field is unspecified, * copy the value from the input document */ if (doc_title == null) { doc_title = (String) info.get("Title"); } if (doc_subject == null) { doc_subject = (String) info.get("Subject"); } if (doc_keywords == null) { doc_keywords = (String) info.get("Keywords"); } if (doc_creator == null) { doc_creator = (String) info.get("Creator"); } if (doc_author == null) { doc_author = (String) info.get("Author"); } // null metadata field are simply set to the empty string if (doc_title == null) { doc_title = ""; } if (doc_subject == null) { doc_subject = ""; } if (doc_keywords == null) { doc_keywords = ""; } if (doc_creator == null) { doc_creator = ""; } if (doc_author == null) { doc_author = ""; } /* * 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 */ final PdfCopy writer = new PdfCopy(document, new FileOutputStream(output_file)); /* * step 3.1: we add the meta data */ document.addTitle(doc_title); document.addSubject(doc_subject); document.addKeywords(doc_keywords); document.addCreator(doc_creator); document.addAuthor(doc_author); /* * step 3.2: we set up the protection and encryption parameters */ if (encrypt) { writer.setEncryption(encryption_bits, user_passwd, owner_passwd, permissions); } /* * step 4: we open the document */ System.out.print("Writing " + output_file + "... "); document.open(); PdfImportedPage page; int i = 0; // step 5: we add content while (i < n) { i++; page = writer.getImportedPage(reader, i); writer.addPage(page); System.out.print("[" + i + "] "); } final PRAcroForm form = reader.getAcroForm(); if (form != null) { writer.copyAcroForm(reader); } System.out.println(); // step 6: we close the document document.close(); } catch (Exception e) { error(e.getClass().getName() + ": " + e.getMessage()); } }
From source file:org.silverpeas.core.importexport.control.ImportExport.java
License:Open Source License
/** * @param userDetail/*w w w .j a v a 2 s. c om*/ * @param itemsToExport * @return * @throws ImportExportException */ public ExportPDFReport processExportPDF(UserDetail userDetail, List<WAAttributeValuePair> itemsToExport, NodePK rootPK) throws ImportExportException { ExportPDFReport report = new ExportPDFReport(); report.setDateDebut(new Date()); PublicationsTypeManager pubTypeManager = getPublicationsTypeManager(); String fileExportName = generateExportDirName(userDetail, "fusion"); String tempDir = FileRepositoryManager.getTemporaryPath(); File fileExportDir = new File(tempDir + fileExportName); if (!fileExportDir.exists()) { try { FileFolderManager.createFolder(fileExportDir); } catch (org.silverpeas.core.util.UtilException ex) { throw new ImportExportException("ImportExport", "importExport.EX_CANT_CREATE_FOLDER", ex); } } File pdfFileName = new File(tempDir + fileExportName + ".pdf"); try { // cration des rpertoires avec le nom des thmes et des publications List<AttachmentDetail> pdfList = pubTypeManager.processPDFExport(report, userDetail, itemsToExport, fileExportDir.getPath(), true, rootPK); try { int pageOffset = 0; List master = new ArrayList(); Document document = null; PdfCopy writer = null; if (!pdfList.isEmpty()) { boolean firstPage = true; for (AttachmentDetail attDetail : pdfList) { PdfReader reader = null; try { reader = new PdfReader( fileExportDir.getPath() + File.separatorChar + attDetail.getLogicalName()); } catch (IOException ioe) { // Attached file is not physically present on disk, ignore it and log event SilverLogger.getLogger(this).error("Cannot find PDF {0}", new String[] { attDetail.getLogicalName() }, ioe); } if (reader != null) { reader.consolidateNamedDestinations(); int nbPages = reader.getNumberOfPages(); List bookmarks = SimpleBookmark.getBookmark(reader); if (bookmarks != null) { if (pageOffset != 0) { SimpleBookmark.shiftPageNumbers(bookmarks, pageOffset, null); } master.addAll(bookmarks); } pageOffset += nbPages; if (firstPage) { document = new Document(reader.getPageSizeWithRotation(1)); writer = new PdfCopy(document, new FileOutputStream(pdfFileName)); document.open(); firstPage = false; } for (int i = 1; i <= nbPages; i++) { try { PdfImportedPage page = writer.getImportedPage(reader, i); writer.addPage(page); } catch (Exception e) { // Can't import PDF file, ignore it and log event SilverLogger.getLogger(this).error("Cannot merge PDF {0}", new String[] { attDetail.getLogicalName() }, e); } } PRAcroForm form = reader.getAcroForm(); if (form != null) { writer.copyAcroForm(reader); } } } if (!master.isEmpty()) { writer.setOutlines(master); } writer.flush(); document.close(); } else { return null; } } catch (DocumentException e) { // Impossible de copier le document throw new ImportExportException("ImportExport", "root.EX_CANT_WRITE_FILE", e); } } catch (IOException e) { // Pb avec le rpertoire de destination throw new ImportExportException("ImportExport", "root.EX_CANT_WRITE_FILE", e); } report.setPdfFileName(pdfFileName.getName()); report.setPdfFileSize(pdfFileName.length()); report.setPdfFilePath(FileServerUtils.getUrlToTempDir(pdfFileName.getName())); report.setDateFin(new Date()); return report; }
From source file:org.squale.welcom.outils.pdf.advanced.WPdfMerge.java
License:Open Source License
/** * merge/*from w w w . jav a 2 s .c o m*/ * * @return byte array rempli */ private byte[] merge() { final ByteArrayOutputStream tmpout = new ByteArrayOutputStream(); int pageOffset = 0; int f = 0; Document document = null; final ArrayList master = new ArrayList(); PdfCopy writer = null; final Iterator it = readers.iterator(); while (it.hasNext()) { PdfReader reader = (PdfReader) it.next(); try { // Renome tout les champs; reader = new PdfReader(renameFieldUnique(reader)); reader.consolidateNamedDestinations(); // we retrieve the total number of pages final int n = reader.getNumberOfPages(); final List bookmarks = SimpleBookmark.getBookmark(reader); if (bookmarks != null) { if (pageOffset != 0) { SimpleBookmark.shiftPageNumbers(bookmarks, pageOffset, null); } master.addAll(bookmarks); } pageOffset += n; if (f == 0) { // step 1: creation of a document-object document = new Document(reader.getPageSizeWithRotation(1)); // step 2: we create a writer that listens to the document writer = new PdfCopy(document, tmpout); // step 3: we open the document document.open(); } // step 4: we add content PdfImportedPage page; for (int i = 0; i < n;) { ++i; page = writer.getImportedPage(reader, i); writer.addPage(page); } final PRAcroForm form = reader.getAcroForm(); if (form != null) { writer.copyAcroForm(reader); } f++; if (master.size() > 0) { writer.setOutlines(master); } // step 5: we close the document // document.close(); } catch (final Exception e) { e.printStackTrace(); } } if (document != null) { document.close(); } return tmpout.toByteArray(); }
From source file:oscar.util.ConcatPDF.java
License:Open Source License
/** * This class can be used to concatenate existing PDF files. * (This was an example known as PdfCopy.java) * @param args the command line arguments *//*w w w. j ava 2s. com*/ public static void concat(List<Object> alist, OutputStream out) { try { int pageOffset = 0; ArrayList master = new ArrayList(); int f = 0; Document document = null; PdfCopy writer = null; boolean fileAsStream = false; PdfReader reader = null; String name = ""; MiscUtils.getLogger().debug("Size of list = " + alist.size()); while (f < alist.size()) { // we create a reader for a certain document Object o = alist.get(f); if (o instanceof InputStream) { name = ""; fileAsStream = true; } else { name = (String) alist.get(f); fileAsStream = false; } if (fileAsStream) { reader = new PdfReader((InputStream) alist.get(f)); } else { reader = new PdfReader(name); } reader.consolidateNamedDestinations(); // we retrieve the total number of pages int n = reader.getNumberOfPages(); List bookmarks = SimpleBookmark.getBookmark(reader); if (bookmarks != null) { if (pageOffset != 0) SimpleBookmark.shiftPageNumbers(bookmarks, pageOffset, null); master.addAll(bookmarks); } pageOffset += n; MiscUtils.getLogger().debug("There are " + n + " pages in " + name); if (f == 0) { // step 1: creation of a document-object document = new Document(reader.getPageSizeWithRotation(1)); // step 2: we create a writer that listens to the document writer = new PdfCopy(document, out); // step 3: we open the document document.open(); } // step 4: we add content PdfImportedPage page; for (int i = 0; i < n;) { ++i; page = writer.getImportedPage(reader, i); writer.addPage(page); MiscUtils.getLogger().debug("Processed page " + i); } PRAcroForm form = reader.getAcroForm(); if (form != null) writer.copyAcroForm(reader); f++; } if (master.size() > 0) writer.setOutlines(master); // step 5: we close the document document.close(); } catch (Exception e) { MiscUtils.getLogger().error("Error", e); } }