List of usage examples for com.lowagie.text.pdf PdfCopy addPage
public void addPage(PdfImportedPage iPage) throws IOException, BadPdfFormatException
From source file:org.kuali.kfs.module.ar.web.struts.CustomerInvoiceAction.java
License:Open Source License
/** * * This method...//from ww w. ja v a 2s. c o m * @param mapping * @param form * @param request * @param response * @return * @throws Exception */ public ActionForward print(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { CustomerInvoiceForm ciForm = (CustomerInvoiceForm) form; String org = ciForm.getOrgCode(); String chart = ciForm.getChartCode(); Date date = ciForm.getRunDate(); StringBuilder fileName = new StringBuilder(); AccountsReceivableReportService reportService = SpringContext .getBean(AccountsReceivableReportService.class); List<File> reports = new ArrayList<File>(); if (ciForm.getOrgType() != null && chart != null && org != null) { if (ciForm.getOrgType().equals("B")) { reports = reportService.generateInvoicesByBillingOrg(chart, org, date); } else if (ciForm.getOrgType().equals("P")) { reports = reportService.generateInvoicesByProcessingOrg(chart, org, date); } fileName.append(chart); fileName.append(org); if (date != null) { fileName.append(date); } } else if (ciForm.getUserId() != null) { reports = reportService.generateInvoicesByInitiator(ciForm.getUserId(), date); fileName.append(ciForm.getUserId()); } if (reports.size() > 0) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); int pageOffset = 0; ArrayList master = new ArrayList(); int f = 0; Document document = null; PdfCopy writer = null; for (Iterator<File> itr = reports.iterator(); itr.hasNext();) { // we create a reader for a certain document String reportName = itr.next().getAbsolutePath(); PdfReader reader = new PdfReader(reportName); 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; 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, baos); // 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); } writer.freeReader(reader); f++; } if (!master.isEmpty()) { writer.setOutlines(master); // step 5: we close the document } document.close(); fileName.append("-InvoiceBatchPDFs.pdf"); WebUtils.saveMimeOutputStreamAsFile(response, "application/pdf", baos, fileName.toString()); ciForm.setMessage(reports.size() + " Reports Generated"); return null; } ciForm.setMessage("No Reports Generated"); return mapping.findForward(KFSConstants.MAPPING_BASIC); }
From source file:org.kuali.kfs.module.ar.web.struts.CustomerStatementAction.java
License:Educational Community License
public ActionForward printStatementPDF(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { CustomerStatementForm csForm = (CustomerStatementForm) form; String chartCode = request.getParameter("chartCode"); chartCode = chartCode == null ? "" : chartCode; String orgCode = request.getParameter("orgCode"); orgCode = orgCode == null ? "" : orgCode; String customerNumber = request.getParameter("customerNumber"); customerNumber = customerNumber == null ? "" : customerNumber; String accountNumber = request.getParameter("accountNumber"); accountNumber = accountNumber == null ? "" : accountNumber; String statementFormat = request.getParameter("statementFormat"); String includeZeroBalanceCustomers = request.getParameter("includeZeroBalanceCustomers"); AccountsReceivableReportService reportService = SpringContext .getBean(AccountsReceivableReportService.class); List<CustomerStatementResultHolder> reports = new ArrayList<CustomerStatementResultHolder>(); StringBuilder fileName = new StringBuilder(); String contentDisposition = ""; if (!StringUtils.isBlank(chartCode) && !StringUtils.isBlank(orgCode)) { reports = reportService.generateStatementByBillingOrg(chartCode, orgCode, statementFormat, includeZeroBalanceCustomers); fileName.append(chartCode);//from ww w. j a va 2 s. com fileName.append(orgCode); } else if (!StringUtils.isBlank(customerNumber)) { reports = reportService.generateStatementByCustomer(customerNumber.toUpperCase(), statementFormat, includeZeroBalanceCustomers); fileName.append(customerNumber); } else if (!StringUtils.isBlank(accountNumber)) { reports = reportService.generateStatementByAccount(accountNumber, statementFormat, includeZeroBalanceCustomers); fileName.append(accountNumber); } if (reports.size() != 0) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { int pageOffset = 0; ArrayList<PdfReader> master = new ArrayList<PdfReader>(); int f = 0; // File file = new File(fileName); Document document = null; PdfCopy writer = null; for (CustomerStatementResultHolder customerStatementResultHolder : reports) { File file = customerStatementResultHolder.getFile(); // we create a reader for a certain document String reportName = file.getAbsolutePath(); PdfReader reader = new PdfReader(reportName); reader.consolidateNamedDestinations(); // we retrieve the total number of pages int n = reader.getNumberOfPages(); List<PdfReader> 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, baos); // 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); } writer.freeReader(reader); f++; } if (!master.isEmpty()) writer.setOutlines(master); // step 5: we close the document document.close(); // csForm.setReports(file); StringBuffer sbContentDispValue = new StringBuffer(); String useJavascript = request.getParameter("useJavascript"); if (useJavascript == null || useJavascript.equalsIgnoreCase("false")) { sbContentDispValue.append("attachment"); } else { sbContentDispValue.append("inline"); } sbContentDispValue.append("; filename="); sbContentDispValue.append(fileName); contentDisposition = sbContentDispValue.toString(); } catch (Exception e) { e.printStackTrace(); } fileName.append("-StatementBatchPDFs.pdf"); response.setContentType("application/pdf"); response.setHeader("Content-disposition", contentDisposition); response.setHeader("Expires", "0"); response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0"); response.setHeader("Pragma", "public"); response.setContentLength(baos.size()); // write to output ServletOutputStream sos = response.getOutputStream(); baos.writeTo(sos); sos.flush(); sos.close(); // update reported data for the detailed statement if (statementFormat.equalsIgnoreCase(ArConstants.STATEMENT_FORMAT_DETAIL)) { CustomerInvoiceDocumentService customerInvoiceDocumentService = SpringContext .getBean(CustomerInvoiceDocumentService.class); for (CustomerStatementResultHolder data : reports) { // update reported invoice info if (data.getInvoiceNumbers() != null) { List<String> invoiceNumbers = data.getInvoiceNumbers(); for (String number : invoiceNumbers) { customerInvoiceDocumentService.updateReportedDate(number); } } // update reported customer info customerInvoiceDocumentService.updateReportedInvoiceInfo(data); } } return null; } csForm.setMessage("No Reports Generated"); return mapping.findForward(KFSConstants.MAPPING_BASIC); }
From source file:org.kuali.kfs.module.tem.document.web.struts.TravelActionBase.java
License:Open Source License
/** * * @param request//from ww w.j a v a2 s . com * @param response * @param reportFile * @param fileName * @throws IOException */ @SuppressWarnings("rawtypes") protected void displayPDF(HttpServletRequest request, HttpServletResponse response, File reportFile, StringBuilder fileName) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); String contentDisposition = ""; try { ArrayList master = new ArrayList(); PdfCopy writer = null; // create a reader for the document String reportName = reportFile.getAbsolutePath(); PdfReader reader = new PdfReader(reportName); reader.consolidateNamedDestinations(); // retrieve the total number of pages int n = reader.getNumberOfPages(); List bookmarks = SimpleBookmark.getBookmark(reader); if (bookmarks != null) { master.addAll(bookmarks); } // step 1: create a document-object com.lowagie.text.Document pdfDoc = new com.lowagie.text.Document(reader.getPageSizeWithRotation(1)); // step 2: create a writer that listens to the document writer = new PdfCopy(pdfDoc, baos); // step 3: open the document pdfDoc.open(); // step 4: add content PdfImportedPage page; for (int i = 0; i < n;) { ++i; page = writer.getImportedPage(reader, i); writer.addPage(page); } writer.freeReader(reader); if (!master.isEmpty()) { writer.setOutlines(master); } // step 5: we close the document pdfDoc.close(); StringBuffer sbContentDispValue = new StringBuffer(); String useJavascript = request.getParameter("useJavascript"); if (useJavascript == null || useJavascript.equalsIgnoreCase("false")) { sbContentDispValue.append("attachment"); } else { sbContentDispValue.append("inline"); } sbContentDispValue.append("; filename="); sbContentDispValue.append(fileName); contentDisposition = sbContentDispValue.toString(); } catch (Exception e) { e.printStackTrace(); } response.setContentType("application/pdf"); response.setHeader("Content-Disposition", contentDisposition); response.setHeader("Expires", "0"); response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0"); response.setHeader("Pragma", "public"); response.setContentLength(baos.size()); // write to output ServletOutputStream sos; sos = response.getOutputStream(); baos.writeTo(sos); sos.flush(); sos.close(); }
From source file:org.lucee.extension.pdf.tag.Document.java
License:Open Source License
private void render(OutputStream os, boolean doBookmarks, boolean doHtmlBookmarks) throws IOException, PageException, DocumentException { byte[] pdf = null; // merge multiple docs to 1 if (documents.size() > 1) { PDFDocument[] pdfDocs = new PDFDocument[documents.size()]; PdfReader[] pdfReaders = new PdfReader[pdfDocs.length]; Iterator<PDFDocument> it = documents.iterator(); int index = 0; // generate pdf with pd4ml while (it.hasNext()) { pdfDocs[index] = it.next();// w ww.j av a 2 s. c o m pdfReaders[index] = new PdfReader( pdfDocs[index].render(getDimension(), unitFactor, pageContext, doHtmlBookmarks)); index++; } // collect together ByteArrayOutputStream baos = new ByteArrayOutputStream(); com.lowagie.text.Document document = new com.lowagie.text.Document( pdfReaders[0].getPageSizeWithRotation(1)); PdfCopy copy = new PdfCopy(document, baos); document.open(); String name; ArrayList bookmarks = doBookmarks ? new ArrayList() : null; try { int size, totalPage = 0; Map parent; for (int doc = 0; doc < pdfReaders.length; doc++) { size = pdfReaders[doc].getNumberOfPages(); PdfImportedPage ip; // bookmarks if (doBookmarks) { name = pdfDocs[doc].getName(); if (!Util.isEmpty(name)) { // TODO bookmarks.add(parent=PDFUtil.generateGoToBookMark(name, totalPage+1)); } else parent = null; if (doHtmlBookmarks) { java.util.List pageBM = SimpleBookmark.getBookmark(pdfReaders[doc]); if (pageBM != null) { if (totalPage > 0) SimpleBookmark.shiftPageNumbers(pageBM, totalPage, null); // TODO if(parent!=null)PDFUtil.setChildBookmarks(parent,pageBM); // TODO else bookmarks.addAll(pageBM); } } } totalPage++; for (int page = 1; page <= size; page++) { if (page > 1) totalPage++; ip = copy.getImportedPage(pdfReaders[doc], page); // ip.getPdfDocument().setHeader(arg0); // ip.getPdfDocument().setFooter(arg0); copy.addPage(ip); } } if (doBookmarks && !bookmarks.isEmpty()) copy.setOutlines(bookmarks); } finally { document.close(); } pdf = baos.toByteArray(); } else if (documents.size() == 1) { pdf = (documents.get(0)).render(getDimension(), unitFactor, pageContext, doHtmlBookmarks); } else { pdf = getDocument().render(getDimension(), unitFactor, pageContext, doHtmlBookmarks); } // permission/encryption if (PDFDocument.ENC_NONE != encryption) { PdfReader reader = new PdfReader(pdf); com.lowagie.text.Document document = new com.lowagie.text.Document(reader.getPageSize(1)); Info info = CFMLEngineFactory.getInstance().getInfo(); document.addCreator("Lucee PDF Extension"); ByteArrayOutputStream baos = new ByteArrayOutputStream(); PdfCopy copy = new PdfCopy(document, baos); // PdfWriter writer = PdfWriter.getInstance(document, pdfOut); copy.setEncryption(PDFDocument.ENC_128BIT == encryption, userpassword, ownerpassword, permissions); document.open(); int size = reader.getNumberOfPages(); for (int page = 1; page <= size; page++) { copy.addPage(copy.getImportedPage(reader, page)); } document.close(); pdf = baos.toByteArray(); } // write out if (os != null) Util.copy(new ByteArrayInputStream(pdf), os, true, false); if (!Util.isEmpty(name)) { pageContext.setVariable(name, pdf); } }
From source file:org.lucee.extension.pdf.util.PDFUtil.java
License:Open Source License
/** * @param docs/*from w w w . j a v a 2 s.c o m*/ * @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();/*from w w w . j a v a2s.co m*/ 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 av a 2 s .c om*/ * @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 ww w .j a va2 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.ofbiz.content.compdoc.CompDocServices.java
License:Apache License
public static Map<String, Object> renderCompDocPdf(DispatchContext dctx, Map<String, ? extends Object> context) { LocalDispatcher dispatcher = dctx.getDispatcher(); Locale locale = (Locale) context.get("locale"); String rootDir = (String) context.get("rootDir"); String webSiteId = (String) context.get("webSiteId"); String https = (String) context.get("https"); Delegator delegator = dctx.getDelegator(); String contentId = (String) context.get("contentId"); String contentRevisionSeqId = (String) context.get("contentRevisionSeqId"); String oooHost = (String) context.get("oooHost"); String oooPort = (String) context.get("oooPort"); GenericValue userLogin = (GenericValue) context.get("userLogin"); try {/*www . j a v a 2s . co m*/ List<EntityCondition> exprList = FastList.newInstance(); exprList.add(EntityCondition.makeCondition("contentIdTo", EntityOperator.EQUALS, contentId)); exprList.add( EntityCondition.makeCondition("contentAssocTypeId", EntityOperator.EQUALS, "COMPDOC_PART")); exprList.add(EntityCondition.makeCondition("rootRevisionContentId", EntityOperator.EQUALS, contentId)); if (UtilValidate.isNotEmpty(contentRevisionSeqId)) { exprList.add(EntityCondition.makeCondition("contentRevisionSeqId", EntityOperator.LESS_THAN_EQUAL_TO, contentRevisionSeqId)); } List<GenericValue> compDocParts = EntityQuery.use(delegator) .select("rootRevisionContentId", "itemContentId", "maxRevisionSeqId", "contentId", "dataResourceId", "contentIdTo", "contentAssocTypeId", "fromDate", "sequenceNum") .from("ContentAssocRevisionItemView").where(exprList).orderBy("sequenceNum").filterByDate() .queryList(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); Document document = new Document(); document.setPageSize(PageSize.LETTER); //Rectangle rect = document.getPageSize(); //PdfWriter writer = PdfWriter.getInstance(document, baos); PdfCopy writer = new PdfCopy(document, baos); document.open(); int pgCnt = 0; for (GenericValue contentAssocRevisionItemView : compDocParts) { //String thisContentId = contentAssocRevisionItemView.getString("contentId"); //String thisContentRevisionSeqId = contentAssocRevisionItemView.getString("maxRevisionSeqId"); String thisDataResourceId = contentAssocRevisionItemView.getString("dataResourceId"); GenericValue dataResource = EntityQuery.use(delegator).from("DataResource") .where("dataResourceId", thisDataResourceId).queryOne(); String inputMimeType = null; if (dataResource != null) { inputMimeType = dataResource.getString("mimeTypeId"); } byte[] inputByteArray = null; PdfReader reader = null; if (inputMimeType != null && inputMimeType.equals("application/pdf")) { ByteBuffer byteBuffer = DataResourceWorker.getContentAsByteBuffer(delegator, thisDataResourceId, https, webSiteId, locale, rootDir); inputByteArray = byteBuffer.array(); reader = new PdfReader(inputByteArray); } else if (inputMimeType != null && inputMimeType.equals("text/html")) { ByteBuffer byteBuffer = DataResourceWorker.getContentAsByteBuffer(delegator, thisDataResourceId, https, webSiteId, locale, rootDir); inputByteArray = byteBuffer.array(); String s = new String(inputByteArray); Debug.logInfo("text/html string:" + s, module); continue; } else if (inputMimeType != null && inputMimeType.equals("application/vnd.ofbiz.survey.response")) { String surveyResponseId = dataResource.getString("relatedDetailId"); String surveyId = null; String acroFormContentId = null; GenericValue surveyResponse = null; if (UtilValidate.isNotEmpty(surveyResponseId)) { surveyResponse = EntityQuery.use(delegator).from("SurveyResponse") .where("surveyResponseId", surveyResponseId).queryOne(); if (surveyResponse != null) { surveyId = surveyResponse.getString("surveyId"); } } if (UtilValidate.isNotEmpty(surveyId)) { GenericValue survey = EntityQuery.use(delegator).from("Survey").where("surveyId", surveyId) .queryOne(); if (survey != null) { acroFormContentId = survey.getString("acroFormContentId"); if (UtilValidate.isNotEmpty(acroFormContentId)) { // TODO: is something supposed to be done here? } } } if (surveyResponse != null) { if (UtilValidate.isEmpty(acroFormContentId)) { // Create AcroForm PDF Map<String, Object> survey2PdfResults = dispatcher.runSync("buildPdfFromSurveyResponse", UtilMisc.toMap("surveyResponseId", surveyId)); if (ServiceUtil.isError(survey2PdfResults)) { return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ContentSurveyErrorBuildingPDF", locale), null, null, survey2PdfResults); } ByteBuffer outByteBuffer = (ByteBuffer) survey2PdfResults.get("outByteBuffer"); inputByteArray = outByteBuffer.array(); reader = new PdfReader(inputByteArray); } else { // Fill in acroForm Map<String, Object> survey2AcroFieldResults = dispatcher.runSync( "setAcroFieldsFromSurveyResponse", UtilMisc.toMap("surveyResponseId", surveyResponseId)); if (ServiceUtil.isError(survey2AcroFieldResults)) { return ServiceUtil .returnError( UtilProperties.getMessage(resource, "ContentSurveyErrorSettingAcroFields", locale), null, null, survey2AcroFieldResults); } ByteBuffer outByteBuffer = (ByteBuffer) survey2AcroFieldResults.get("outByteBuffer"); inputByteArray = outByteBuffer.array(); reader = new PdfReader(inputByteArray); } } } else { ByteBuffer inByteBuffer = DataResourceWorker.getContentAsByteBuffer(delegator, thisDataResourceId, https, webSiteId, locale, rootDir); Map<String, Object> convertInMap = UtilMisc.<String, Object>toMap("userLogin", userLogin, "inByteBuffer", inByteBuffer, "inputMimeType", inputMimeType, "outputMimeType", "application/pdf"); if (UtilValidate.isNotEmpty(oooHost)) convertInMap.put("oooHost", oooHost); if (UtilValidate.isNotEmpty(oooPort)) convertInMap.put("oooPort", oooPort); Map<String, Object> convertResult = dispatcher.runSync("convertDocumentByteBuffer", convertInMap); if (ServiceUtil.isError(convertResult)) { return ServiceUtil.returnError( UtilProperties.getMessage(resource, "ContentConvertingDocumentByteBuffer", locale), null, null, convertResult); } ByteBuffer outByteBuffer = (ByteBuffer) convertResult.get("outByteBuffer"); inputByteArray = outByteBuffer.array(); reader = new PdfReader(inputByteArray); } if (reader != null) { int n = reader.getNumberOfPages(); for (int i = 0; i < n; i++) { PdfImportedPage pg = writer.getImportedPage(reader, i + 1); //cb.addTemplate(pg, left, height * pgCnt); writer.addPage(pg); pgCnt++; } } } document.close(); ByteBuffer outByteBuffer = ByteBuffer.wrap(baos.toByteArray()); Map<String, Object> results = ServiceUtil.returnSuccess(); results.put("outByteBuffer", outByteBuffer); return results; } catch (GenericEntityException e) { return ServiceUtil.returnError(e.toString()); } catch (IOException e) { Debug.logError(e, "Error in CompDoc operation: ", module); return ServiceUtil.returnError(e.toString()); } catch (Exception e) { Debug.logError(e, "Error in CompDoc operation: ", module); return ServiceUtil.returnError(e.toString()); } }
From source file:org.openbravo.erpCommon.utility.reporting.printing.PrintController.java
License:Open Source License
private void concatReport(Report[] reports, HttpServletResponse response) { try {/*from ww w . ja v a 2s .co m*/ int pageOffset = 0; // ArrayList master = new ArrayList(); int f = 0; String filename = ""; Report outFile = null; if (reports.length == 1) filename = reports[0].getFilename(); Document document = null; PdfCopy writer = null; while (f < reports.length) { if (filename == null || filename.equals("")) { outFile = reports[f]; if (multiReports) { filename = outFile.getTemplateInfo().getReportFilename(); filename = filename.replaceAll("@our_ref@", ""); filename = filename.replaceAll("@cus_ref@", ""); filename = filename.replaceAll(" ", "_"); filename = filename.replaceAll("-", ""); filename = filename + ".pdf"; } else { filename = outFile.getFilename(); } } response.setHeader("Content-disposition", "attachment" + "; filename=" + filename); // we create a reader for a certain document PdfReader reader = new PdfReader(reports[f].getTargetLocation()); reader.consolidateNamedDestinations(); // we retrieve the total number of pages int n = reader.getNumberOfPages(); 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, response.getOutputStream()); // 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); } if (reports[f].isDeleteable()) { File file = new File(reports[f].getTargetLocation()); if (file.exists() && !file.isDirectory()) { file.delete(); } } f++; } document.close(); } catch (Exception e) { log4j.error(e); } }