List of usage examples for com.lowagie.text Document addCreator
public boolean addCreator(String creator)
From source file:org.mapfish.print.config.layout.MetaData.java
License:Open Source License
public void render(PJsonObject params, RenderingContext context) { final Document doc = context.getDocument(); if (title != null) { doc.addTitle(PDFUtils.evalString(context, params, title)); }//from www . j a v a2 s . c o m if (author != null) { doc.addAuthor(PDFUtils.evalString(context, params, author)); } if (subject != null) { doc.addSubject(PDFUtils.evalString(context, params, subject)); } if (keywords != null) { doc.addKeywords(PDFUtils.evalString(context, params, keywords)); } if (creator != null) { doc.addCreator(PDFUtils.evalString(context, params, creator)); } }
From source file:org.mnsoft.pdfocr.CreatorSetter.java
License:Open Source License
/** * @param args//w w w .j ava2s. 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 ww . j a va 2 s. co 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.nuxeo.dam.pdf.export.PDFCreator.java
License:Open Source License
public boolean createPDF(String title, OutputStream out) throws ClientException { try {/*from w ww. j a v a 2s .co m*/ Document document = new Document(); PdfWriter.getInstance(document, out); document.addTitle(title); document.addAuthor(Functions.principalFullName(currentUser)); document.addCreator(Functions.principalFullName(currentUser)); document.open(); document.add(new Paragraph("\n\n\n\n\n\n\n\n\n\n")); Font titleFont = new Font(Font.HELVETICA, 36, Font.BOLD); Paragraph titleParagraph = new Paragraph(title, titleFont); titleParagraph.setAlignment(Element.ALIGN_CENTER); document.add(titleParagraph); Font authorFont = new Font(Font.HELVETICA, 20); Paragraph authorParagraph = new Paragraph("By " + Functions.principalFullName(currentUser), authorFont); authorParagraph.setAlignment(Element.ALIGN_CENTER); document.add(authorParagraph); document.newPage(); boolean foundOnePicture = false; for (DocumentModel doc : docs) { if (!doc.hasSchema(PICTURE_SCHEMA)) { continue; } foundOnePicture = true; PictureResourceAdapter picture = doc.getAdapter(PictureResourceAdapter.class); Blob blob = picture.getPictureFromTitle(ORIGINAL_JPEG_VIEW); Rectangle pageSize = document.getPageSize(); if (blob != null) { Paragraph imageTitle = new Paragraph(doc.getTitle(), font); imageTitle.setAlignment(Paragraph.ALIGN_CENTER); document.add(imageTitle); Image image = Image.getInstance(blob.getByteArray()); image.scaleToFit(pageSize.getWidth() - 20, pageSize.getHeight() - 100); image.setAlignment(Image.MIDDLE); Paragraph imageParagraph = new Paragraph(); imageParagraph.add(image); imageParagraph.setAlignment(Paragraph.ALIGN_MIDDLE); document.add(imageParagraph); document.newPage(); } } if (foundOnePicture) { document.close(); return true; } } catch (Exception e) { throw ClientException.wrap(e); } return false; }
From source file:org.oscarehr.phr.web.PHRUserManagementAction.java
License:Open Source License
public ByteArrayOutputStream generateUserRegistrationLetter(String demographicNo, String username, String password) throws Exception { log.debug("Demographic " + demographicNo + " username " + username + " password " + password); DemographicDao demographicDao = (DemographicDao) SpringUtils.getBean("demographicDao"); Demographic demographic = demographicDao.getDemographic(demographicNo); final String PAGESIZE = "printPageSize"; Document document = new Document(); ByteArrayOutputStream baosPDF = new ByteArrayOutputStream(); PdfWriter writer = null;/*from ww w . j a v a 2 s . c o m*/ try { writer = PdfWriter.getInstance(document, baosPDF); String title = "TITLE"; String template = "MyOscarLetterHead.pdf"; Properties printCfg = getCfgProp(); String[] cfgVal = null; StringBuilder tempName = null; // get the print prop values Properties props = new Properties(); props.setProperty("letterDate", UtilDateUtilities.getToday("yyyy-MM-dd")); props.setProperty("name", demographic.getFirstName() + " " + demographic.getLastName()); props.setProperty("dearname", demographic.getFirstName() + " " + demographic.getLastName()); props.setProperty("address", demographic.getAddress()); props.setProperty("city", demographic.getCity() + ", " + demographic.getProvince()); props.setProperty("postalCode", demographic.getPostal()); props.setProperty("credHeading", "MyOscar User Account Details"); props.setProperty("username", "Username: " + username); props.setProperty("password", "Password: " + password); //Temporary - the intro will change to be dynamic props.setProperty("intro", "We are pleased to provide you with a log in and password for your new MyOSCAR Personal Health Record. This account will allow you to connect electronically with our clinic. Please take a few minutes to review the accompanying literature for further information.We look forward to you benefiting from this service."); document.addTitle(title); document.addSubject(""); document.addKeywords("pdf, itext"); document.addCreator("OSCAR"); document.addAuthor(""); document.addHeader("Expires", "0"); Rectangle pageSize = PageSize.LETTER; document.setPageSize(pageSize); document.open(); // create a reader for a certain document String propFilename = oscar.OscarProperties.getInstance().getProperty("pdfFORMDIR", "") + "/" + template; PdfReader reader = null; try { reader = new PdfReader(propFilename); log.debug("Found template at " + propFilename); } catch (Exception dex) { log.debug("change path to inside oscar from :" + propFilename); reader = new PdfReader("/oscar/form/prop/" + template); log.debug("Found template at /oscar/form/prop/" + template); } // retrieve the total number of pages int n = reader.getNumberOfPages(); // retrieve the size of the first page Rectangle pSize = reader.getPageSize(1); float width = pSize.getWidth(); float height = pSize.getHeight(); log.debug("Width :" + width + " Height: " + height); PdfContentByte cb = writer.getDirectContent(); ColumnText ct = new ColumnText(cb); int fontFlags = 0; document.newPage(); PdfImportedPage page1 = writer.getImportedPage(reader, 1); cb.addTemplate(page1, 1, 0, 0, 1, 0, 0); BaseFont bf; // = normFont; String encoding; cb.setRGBColorStroke(0, 0, 255); String[] fontType; for (Enumeration e = printCfg.propertyNames(); e.hasMoreElements();) { tempName = new StringBuilder(e.nextElement().toString()); cfgVal = printCfg.getProperty(tempName.toString()).split(" *, *"); if (cfgVal[4].indexOf(";") > -1) { fontType = cfgVal[4].split(";"); if (fontType[1].trim().equals("italic")) fontFlags = Font.ITALIC; else if (fontType[1].trim().equals("bold")) fontFlags = Font.BOLD; else if (fontType[1].trim().equals("bolditalic")) fontFlags = Font.BOLDITALIC; else fontFlags = Font.NORMAL; } else { fontFlags = Font.NORMAL; fontType = new String[] { cfgVal[4].trim() }; } if (fontType[0].trim().equals("BaseFont.HELVETICA")) { fontType[0] = BaseFont.HELVETICA; encoding = BaseFont.CP1252; //latin1 encoding } else if (fontType[0].trim().equals("BaseFont.HELVETICA_OBLIQUE")) { fontType[0] = BaseFont.HELVETICA_OBLIQUE; encoding = BaseFont.CP1252; } else if (fontType[0].trim().equals("BaseFont.ZAPFDINGBATS")) { fontType[0] = BaseFont.ZAPFDINGBATS; encoding = BaseFont.ZAPFDINGBATS; } else { fontType[0] = BaseFont.COURIER; encoding = BaseFont.CP1252; } bf = BaseFont.createFont(fontType[0], encoding, BaseFont.NOT_EMBEDDED); // write in a rectangle area if (cfgVal.length >= 9) { Font font = new Font(bf, Integer.parseInt(cfgVal[5].trim()), fontFlags); ct.setSimpleColumn(Integer.parseInt(cfgVal[1].trim()), (height - Integer.parseInt(cfgVal[2].trim())), Integer.parseInt(cfgVal[7].trim()), (height - Integer.parseInt(cfgVal[8].trim())), Integer.parseInt(cfgVal[9].trim()), (cfgVal[0].trim().equals("left") ? Element.ALIGN_LEFT : (cfgVal[0].trim().equals("right") ? Element.ALIGN_RIGHT : Element.ALIGN_CENTER))); ct.setText(new Phrase(12, props.getProperty(tempName.toString(), ""), font)); ct.go(); continue; } // draw line directly if (tempName.toString().startsWith("__$line")) { cb.setRGBColorStrokeF(0f, 0f, 0f); cb.setLineWidth(Float.parseFloat(cfgVal[4].trim())); cb.moveTo(Float.parseFloat(cfgVal[0].trim()), Float.parseFloat(cfgVal[1].trim())); cb.lineTo(Float.parseFloat(cfgVal[2].trim()), Float.parseFloat(cfgVal[3].trim())); // stroke the lines cb.stroke(); // write text directly } else if (tempName.toString().startsWith("__")) { cb.beginText(); cb.setFontAndSize(bf, Integer.parseInt(cfgVal[5].trim())); cb.showTextAligned( (cfgVal[0].trim().equals("left") ? PdfContentByte.ALIGN_LEFT : (cfgVal[0].trim().equals("right") ? PdfContentByte.ALIGN_RIGHT : PdfContentByte.ALIGN_CENTER)), (cfgVal.length >= 7 ? (cfgVal[6].trim()) : props.getProperty(tempName.toString(), "")), Integer.parseInt(cfgVal[1].trim()), (height - Integer.parseInt(cfgVal[2].trim())), 0); cb.endText(); } else if (tempName.toString().equals("forms_promotext")) { if (OscarProperties.getInstance().getProperty("FORMS_PROMOTEXT") != null) { cb.beginText(); cb.setFontAndSize(bf, Integer.parseInt(cfgVal[5].trim())); cb.showTextAligned( (cfgVal[0].trim().equals("left") ? PdfContentByte.ALIGN_LEFT : (cfgVal[0].trim().equals("right") ? PdfContentByte.ALIGN_RIGHT : PdfContentByte.ALIGN_CENTER)), OscarProperties.getInstance().getProperty("FORMS_PROMOTEXT"), Integer.parseInt(cfgVal[1].trim()), (height - Integer.parseInt(cfgVal[2].trim())), 0); cb.endText(); } } else { // write prop text cb.beginText(); cb.setFontAndSize(bf, Integer.parseInt(cfgVal[5].trim())); cb.showTextAligned( (cfgVal[0].trim().equals("left") ? PdfContentByte.ALIGN_LEFT : (cfgVal[0].trim().equals("right") ? PdfContentByte.ALIGN_RIGHT : PdfContentByte.ALIGN_CENTER)), (cfgVal.length >= 7 ? ((props.getProperty(tempName.toString(), "").equals("") ? "" : cfgVal[6].trim())) : props.getProperty(tempName.toString(), "")), Integer.parseInt(cfgVal[1].trim()), (height - Integer.parseInt(cfgVal[2].trim())), 0); cb.endText(); } } } catch (DocumentException dex) { baosPDF.reset(); throw dex; } finally { if (document != null) document.close(); if (writer != null) writer.close(); } return baosPDF; }
From source file:org.pdfsam.console.business.pdf.handlers.AlternateMixCmdExecutor.java
License:Open Source License
public void execute(AbstractParsedCommand parsedCommand) throws ConsoleException { if ((parsedCommand != null) && (parsedCommand instanceof MixParsedCommand)) { MixParsedCommand inputCommand = (MixParsedCommand) parsedCommand; setWorkIndeterminate();/*from ww w . ja va 2s . c o m*/ Document pdfDocument = null; int[] limits1 = { 1, 1 }; int[] limits2 = { 1, 1 }; try { File tmpFile = FileUtility.generateTmpFile(inputCommand.getOutputFile()); pdfReader1 = PdfUtility.readerFor(inputCommand.getFirstInputFile()); pdfReader1.removeUnusedObjects(); pdfReader1.consolidateNamedDestinations(); limits1[1] = pdfReader1.getNumberOfPages(); pdfReader2 = PdfUtility.readerFor(inputCommand.getSecondInputFile()); pdfReader2.removeUnusedObjects(); pdfReader2.consolidateNamedDestinations(); limits2[1] = pdfReader2.getNumberOfPages(); pdfDocument = new Document(pdfReader1.getPageSizeWithRotation(1)); LOG.debug("Creating a new document."); pdfWriter = new PdfCopy(pdfDocument, new FileOutputStream(tmpFile)); setPdfVersionSettingOnWriter(inputCommand, pdfWriter); setCompressionSettingOnWriter(inputCommand, pdfWriter); pdfDocument.addCreator(ConsoleServicesFacade.CREATOR); pdfDocument.open(); PdfImportedPage page; boolean finished1 = false; boolean finished2 = false; int current1 = (inputCommand.isReverseFirst()) ? limits1[1] : limits1[0]; int current2 = (inputCommand.isReverseSecond()) ? limits2[1] : limits2[0]; while (!finished1 || !finished2) { if (!finished1) { for (int i = 0; (i < inputCommand.getStep() && !finished1); i++) { if (current1 >= limits1[0] && current1 <= limits1[1]) { page = pdfWriter.getImportedPage(pdfReader1, current1); pdfWriter.addPage(page); current1 = (inputCommand.isReverseFirst()) ? (current1 - 1) : (current1 + 1); } else { LOG.info("First file processed."); pdfReader1.close(); finished1 = true; } } } if (!finished2) { for (int i = 0; (i < inputCommand.getSecondStep() && !finished2); i++) { if (current2 >= limits2[0] && current2 <= limits2[1] && !finished2) { page = pdfWriter.getImportedPage(pdfReader2, current2); pdfWriter.addPage(page); current2 = (inputCommand.isReverseSecond()) ? (current2 - 1) : (current2 + 1); } else { LOG.info("Second file processed."); pdfReader2.close(); finished2 = true; } } } } pdfWriter.freeReader(pdfReader1); pdfWriter.freeReader(pdfReader2); pdfDocument.close(); FileUtility.renameTemporaryFile(tmpFile, inputCommand.getOutputFile(), inputCommand.isOverwrite()); LOG.debug("File " + inputCommand.getOutputFile().getCanonicalPath() + " created."); LOG.info("Alternate mix with step first document " + inputCommand.getStep() + " and step second document " + inputCommand.getSecondStep() + " completed."); } catch (Exception e) { throw new MixException(e); } finally { setWorkCompleted(); } } else { throw new ConsoleException(ConsoleException.ERR_BAD_COMMAND); } }
From source file:org.pdfsam.console.business.pdf.handlers.ConcatCmdExecutor.java
License:Open Source License
public void execute(AbstractParsedCommand parsedCommand) throws ConsoleException { if ((parsedCommand != null) && (parsedCommand instanceof ConcatParsedCommand)) { ConcatParsedCommand inputCommand = (ConcatParsedCommand) parsedCommand; setPercentageOfWorkDone(0);// w w w .ja v a 2 s.com // xml or csv parsing PdfFile[] fileList = inputCommand.getInputFileList(); if (fileList == null || !(fileList.length > 0)) { File listFile = inputCommand.getInputCvsOrXmlFile(); if (listFile != null && listFile.exists()) { fileList = parseListFile(listFile); } else if (inputCommand.getInputDirectory() != null) { fileList = getPdfFiles(inputCommand.getInputDirectory()); } } // no input file found if (fileList == null || !(fileList.length > 0)) { throw new ConcatException(ConcatException.CMD_NO_INPUT_FILE); } // init int pageOffset = 0; ArrayList master = new ArrayList(); Document pdfDocument = null; int totalProcessedPages = 0; try { String[] pageSelections = inputCommand.getPageSelections(); File tmpFile = FileUtility.generateTmpFile(inputCommand.getOutputFile()); int length = ArrayUtils.getLength(pageSelections); for (int i = 0; i < fileList.length; i++) { String currentPageSelection = ValidationUtility.ALL_STRING; int currentDocumentPages = 0; if (!ArrayUtils.isEmpty(pageSelections) && i <= length) { currentPageSelection = pageSelections[i].toLowerCase(); } String[] selectionGroups = StringUtils.split(currentPageSelection, ","); pdfReader = PdfUtility.readerFor(fileList[i]); pdfReader.removeUnusedObjects(); pdfReader.consolidateNamedDestinations(); int pdfNumberOfPages = pdfReader.getNumberOfPages(); BookmarksProcessor bookmarkProcessor = new BookmarksProcessor( SimpleBookmark.getBookmark(pdfReader), pdfNumberOfPages); List boundsList = getBounds(pdfNumberOfPages, selectionGroups); ValidationUtility.assertNotIntersectedBoundsList(boundsList); String boundsString = ""; for (Iterator iter = boundsList.iterator(); iter.hasNext();) { Bounds bounds = (Bounds) iter.next(); boundsString += (boundsString.length() > 0) ? "," + bounds.toString() : bounds.toString(); // bookmarks List bookmarks = bookmarkProcessor.processBookmarks(bounds.getStart(), bounds.getEnd(), pageOffset); if (bookmarks != null) { master.addAll(bookmarks); } int relativeOffset = (bounds.getEnd() - bounds.getStart()) + 1; currentDocumentPages += relativeOffset; pageOffset += relativeOffset; } // add pages LOG.info(fileList[i].getFile().getAbsolutePath() + ": " + currentDocumentPages + " pages to be added."); if (pdfWriter == null) { if (inputCommand.isCopyFields()) { // step 1: we create a writer pdfWriter = new PdfCopyFieldsConcatenator(new FileOutputStream(tmpFile), inputCommand.isCompress()); LOG.debug("PdfCopyFieldsConcatenator created."); // output document version if (inputCommand.getOutputPdfVersion() != null) { pdfWriter.setPdfVersion(inputCommand.getOutputPdfVersion().charValue()); } HashMap meta = pdfReader.getInfo(); meta.put("Creator", ConsoleServicesFacade.CREATOR); } else { // step 1: creation of a document-object pdfDocument = new Document(pdfReader.getPageSizeWithRotation(1)); // step 2: we create a writer that listens to the document pdfWriter = new PdfSimpleConcatenator(pdfDocument, new FileOutputStream(tmpFile), inputCommand.isCompress()); LOG.debug("PdfSimpleConcatenator created."); // output document version if (inputCommand.getOutputPdfVersion() != null) { pdfWriter.setPdfVersion(inputCommand.getOutputPdfVersion().charValue()); } // step 3: we open the document pdfDocument.addCreator(ConsoleServicesFacade.CREATOR); pdfDocument.open(); } } // step 4: we add content pdfReader.selectPages(boundsString); pdfWriter.addDocument(pdfReader); // fix 03/07 // pdfReader = null; pdfReader.close(); pdfWriter.freeReader(pdfReader); totalProcessedPages += currentDocumentPages; LOG.info(currentDocumentPages + " pages processed correctly."); setPercentageOfWorkDone(((i + 1) * WorkDoneDataModel.MAX_PERGENTAGE) / fileList.length); } if (master.size() > 0) { pdfWriter.setOutlines(master); } LOG.info("Total processed pages: " + totalProcessedPages + "."); if (pdfDocument != null) { pdfDocument.close(); } // rotations if (inputCommand.getRotations() != null && inputCommand.getRotations().length > 0) { LOG.info("Applying pages rotation."); File rotatedTmpFile = applyRotations(tmpFile, inputCommand); FileUtility.deleteFile(tmpFile); FileUtility.renameTemporaryFile(rotatedTmpFile, inputCommand.getOutputFile(), inputCommand.isOverwrite()); } else { FileUtility.renameTemporaryFile(tmpFile, inputCommand.getOutputFile(), inputCommand.isOverwrite()); } LOG.debug("File " + inputCommand.getOutputFile().getCanonicalPath() + " created."); } catch (ConsoleException consoleException) { throw consoleException; } catch (Exception e) { throw new ConcatException(e); } finally { setWorkCompleted(); } } else { throw new ConsoleException(ConsoleException.ERR_BAD_COMMAND); } }
From source file:org.pdfsam.console.business.pdf.handlers.PageLabelsCmdExecutor.java
License:Open Source License
public void execute(AbstractParsedCommand parsedCommand) throws ConsoleException { if ((parsedCommand != null) && (parsedCommand instanceof PageLabelsParsedCommand)) { PageLabelsParsedCommand inputCommand = (PageLabelsParsedCommand) parsedCommand; setPercentageOfWorkDone(0);//from ww w . j a va 2 s . co m Document currentDocument; try { File tmpFile = FileUtility.generateTmpFile(inputCommand.getOutputFile()); LOG.debug("Opening " + inputCommand.getInputFile().getFile().getAbsolutePath()); pdfReader = PdfUtility.readerFor(inputCommand.getInputFile()); pdfReader.removeUnusedObjects(); pdfReader.consolidateNamedDestinations(); int n = pdfReader.getNumberOfPages(); currentDocument = new Document(pdfReader.getPageSizeWithRotation(1)); pdfWriter = new PdfCopy(currentDocument, new FileOutputStream(tmpFile)); // set compressed setCompressionSettingOnWriter(inputCommand, pdfWriter); // set pdf version setPdfVersionSettingOnWriter(inputCommand, pdfWriter, Character.valueOf(pdfReader.getPdfVersion())); // set creator currentDocument.addCreator(ConsoleServicesFacade.CREATOR); currentDocument.open(); for (int count = 1; count <= n; count++) { pdfWriter.addPage(pdfWriter.getImportedPage(pdfReader, count)); } pdfReader.close(); pdfWriter.freeReader(pdfReader); // set labels PdfPageLabels pageLabels = new PdfPageLabels(); PageLabel[] labels = inputCommand.getLabels(); // last step is creating the file int stepsNumber = labels.length + 1; for (int i = 0; i < labels.length; i++) { if (labels[i].getPageNumber() <= n) { pageLabels.addPageLabel(labels[i].getPageNumber(), getPageLabelStyle(labels[i].getStyle()), labels[i].getPrefix(), labels[i].getLogicalPageNumber()); } else { LOG.warn("Page number out of range, label starting at page " + labels[i].getPageNumber() + " will be ignored"); } setPercentageOfWorkDone((i * WorkDoneDataModel.MAX_PERGENTAGE) / stepsNumber); } pdfWriter.setPageLabels(pageLabels); currentDocument.close(); pdfWriter.close(); FileUtility.renameTemporaryFile(tmpFile, inputCommand.getOutputFile(), inputCommand.isOverwrite()); LOG.debug("Page labels set on file " + inputCommand.getOutputFile()); } catch (Exception e) { throw new PageLabelsException(e); } finally { setWorkCompleted(); } } else { throw new ConsoleException(ConsoleException.ERR_BAD_COMMAND); } }
From source file:org.pdfsam.console.business.pdf.handlers.SplitCmdExecutor.java
License:Open Source License
/** * Execute the split of a pdf document when split type is S_BURST * //from w ww.ja v a 2 s . com * @param inputCommand * @throws Exception */ private void executeBurst(SplitParsedCommand inputCommand) throws Exception { int currentPage; Document currentDocument; pdfReader = PdfUtility.readerFor(inputCommand.getInputFile()); pdfReader.removeUnusedObjects(); pdfReader.consolidateNamedDestinations(); // we retrieve the total number of pages int n = pdfReader.getNumberOfPages(); int fileNum = 0; LOG.info("Found " + n + " pages in input pdf document."); for (currentPage = 1; currentPage <= n; currentPage++) { LOG.debug("Creating a new document."); fileNum++; File tmpFile = FileUtility.generateTmpFile(inputCommand.getOutputFile()); FileNameRequest request = new FileNameRequest(currentPage, fileNum, null); File outFile = new File(inputCommand.getOutputFile().getCanonicalPath(), prefixParser.generateFileName(request)); currentDocument = new Document(pdfReader.getPageSizeWithRotation(currentPage)); pdfWriter = new PdfSmartCopy(currentDocument, new FileOutputStream(tmpFile)); currentDocument.addCreator(ConsoleServicesFacade.CREATOR); setCompressionSettingOnWriter(inputCommand, pdfWriter); // set pdf version setPdfVersionSettingOnWriter(inputCommand, pdfWriter, Character.valueOf(pdfReader.getPdfVersion())); currentDocument.open(); PdfImportedPage importedPage = pdfWriter.getImportedPage(pdfReader, currentPage); pdfWriter.addPage(importedPage); currentDocument.close(); FileUtility.renameTemporaryFile(tmpFile, outFile, inputCommand.isOverwrite()); LOG.debug("File " + outFile.getCanonicalPath() + " created."); setPercentageOfWorkDone((currentPage * WorkDoneDataModel.MAX_PERGENTAGE) / n); } pdfReader.close(); LOG.info("Burst done."); }
From source file:org.pdfsam.console.business.pdf.handlers.SplitCmdExecutor.java
License:Open Source License
/** * Execute the split of a pdf document when split type is S_ODD or S_EVEN * //from w ww . j a va 2 s . c o m * @param inputCommand * @throws Exception */ private void executeSplitOddEven(SplitParsedCommand inputCommand) throws Exception { pdfReader = PdfUtility.readerFor(inputCommand.getInputFile()); pdfReader.removeUnusedObjects(); pdfReader.consolidateNamedDestinations(); // we retrieve the total number of pages int n = pdfReader.getNumberOfPages(); int fileNum = 0; LOG.info("Found " + n + " pages in input pdf document."); int currentPage; Document currentDocument = new Document(pdfReader.getPageSizeWithRotation(1)); boolean isTimeToClose = false; PdfImportedPage importedPage; File tmpFile = null; File outFile = null; for (currentPage = 1; currentPage <= n; currentPage++) { // check if i've to read one more page or to open a new doc isTimeToClose = ((currentPage != 1) && ((SplitParsedCommand.S_ODD.equals(inputCommand.getSplitType()) && ((currentPage % 2) != 0)) || (SplitParsedCommand.S_EVEN.equals(inputCommand.getSplitType()) && ((currentPage % 2) == 0)))); if (!isTimeToClose) { LOG.debug("Creating a new document."); fileNum++; tmpFile = FileUtility.generateTmpFile(inputCommand.getOutputFile()); FileNameRequest request = new FileNameRequest(currentPage, fileNum, null); outFile = new File(inputCommand.getOutputFile(), prefixParser.generateFileName(request)); currentDocument = new Document(pdfReader.getPageSizeWithRotation(currentPage)); pdfWriter = new PdfSmartCopy(currentDocument, new FileOutputStream(tmpFile)); // set creator currentDocument.addCreator(ConsoleServicesFacade.CREATOR); setCompressionSettingOnWriter(inputCommand, pdfWriter); setPdfVersionSettingOnWriter(inputCommand, pdfWriter, Character.valueOf(pdfReader.getPdfVersion())); currentDocument.open(); } importedPage = pdfWriter.getImportedPage(pdfReader, currentPage); pdfWriter.addPage(importedPage); // if it's time to close the document if ((isTimeToClose) || (currentPage == n) || ((currentPage == 1) && (SplitParsedCommand.S_ODD.equals(inputCommand.getSplitType())))) { currentDocument.close(); FileUtility.renameTemporaryFile(tmpFile, outFile, inputCommand.isOverwrite()); LOG.debug("File " + outFile.getCanonicalPath() + " created."); } setPercentageOfWorkDone((currentPage * WorkDoneDataModel.MAX_PERGENTAGE) / n); } pdfReader.close(); LOG.info("Split " + inputCommand.getSplitType() + " done."); }