List of usage examples for com.lowagie.text Document addTitle
public boolean addTitle(String title)
From source file:org.mnsoft.pdfocr.PDFTrans.java
License:Open Source License
/** * @param args the command line arguments *///from w w w . jav a2 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.nuxeo.dam.pdf.export.PDFCreator.java
License:Open Source License
public boolean createPDF(String title, OutputStream out) throws ClientException { try {//from w w w.java2 s.c o 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.openepics.discs.names.ui.ReportManager.java
License:Open Source License
public void preProcessPDF(Object document) throws IOException, BadElementException, DocumentException { Document pdf = (Document) document; pdf.setPageSize(PageSize.LETTER.rotate()); // pdf.open(); // pdf.setPageSize(PageSize.LETTER.rotate()); pdf.addCreationDate();//from w ww. j a va 2s. co m pdf.addHeader("Header", "Proteus: Naming Convention Rep"); pdf.addTitle("Proteus: Naming Convention Report"); // ServletContext servletContext = (ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext(); // String logo = servletContext.getRealPath("") + File.separator + "images" + File.separator + "prime_logo.png"; // pdf.add(Image.getInstance(logo)); }
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 w w w . j a v a 2 s .com 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:oscar.eform.util.EFormPDFServlet.java
License:Open Source License
private void addDocumentProps(Document document, String title, Properties props) { document.addTitle(title); document.addSubject(""); document.addKeywords("pdf, itext"); document.addCreator("OSCAR"); document.addAuthor(""); document.addHeader("Expires", "0"); // A0-A10, LEGAL, LETTER, HALFLETTER, _11x17, LEDGER, NOTE, B0-B5, ARCH_A-ARCH_E, FLSA // and FLSE// w w w .j a v a 2 s . c o m // the following shows a temp way to get a print page size final String PAGESIZE = "printPageSize"; Rectangle pageSize = PageSize.LETTER; if ("PageSize.HALFLETTER".equals(props.getProperty(PAGESIZE))) pageSize = PageSize.HALFLETTER; if ("PageSize.A6".equals(props.getProperty(PAGESIZE))) pageSize = PageSize.A6; document.setPageSize(pageSize); document.open(); }
From source file:oscar.form.pdfservlet.FrmCustomedPDFServlet.java
License:Open Source License
protected ByteArrayOutputStream generatePDFDocumentBytes(final HttpServletRequest req, final ServletContext ctx) throws DocumentException { logger.debug("***in generatePDFDocumentBytes2 FrmCustomedPDFServlet.java***"); // added by vic, hsfo Enumeration<String> em = req.getParameterNames(); while (em.hasMoreElements()) { logger.debug("para=" + em.nextElement()); }/* w ww. j av a 2s. co m*/ em = req.getAttributeNames(); while (em.hasMoreElements()) logger.debug("attr: " + em.nextElement()); if (HSFO_RX_DATA_KEY.equals(req.getParameter("__title"))) { return generateHsfoRxPDF(req); } String newline = System.getProperty("line.separator"); ByteArrayOutputStream baosPDF = new ByteArrayOutputStream(); PdfWriter writer = null; String method = req.getParameter("__method"); String origPrintDate = null; String numPrint = null; if (method != null && method.equalsIgnoreCase("rePrint")) { origPrintDate = req.getParameter("origPrintDate"); numPrint = req.getParameter("numPrints"); } logger.debug("method in generatePDFDocumentBytes " + method); String clinicName; String clinicTel; String clinicFax; // check if satellite clinic is used String useSatelliteClinic = req.getParameter("useSC"); logger.debug(useSatelliteClinic); if (useSatelliteClinic != null && useSatelliteClinic.equalsIgnoreCase("true")) { String scAddress = req.getParameter("scAddress"); logger.debug("clinic detail" + "=" + scAddress); HashMap<String, String> hm = parseSCAddress(scAddress); clinicName = hm.get("clinicName"); clinicTel = hm.get("clinicTel"); clinicFax = hm.get("clinicFax"); } else { // parameters need to be passed to header and footer clinicName = req.getParameter("clinicName"); logger.debug("clinicName" + "=" + clinicName); clinicTel = req.getParameter("clinicPhone"); clinicFax = req.getParameter("clinicFax"); } String patientPhone = req.getParameter("patientPhone"); String patientCityPostal = req.getParameter("patientCityPostal"); String patientAddress = req.getParameter("patientAddress"); String patientName = req.getParameter("patientName"); String sigDoctorName = req.getParameter("sigDoctorName"); String rxDate = req.getParameter("rxDate"); String rx = req.getParameter("rx"); String patientDOB = req.getParameter("patientDOB"); String showPatientDOB = req.getParameter("showPatientDOB"); String imgFile = req.getParameter("imgFile"); String patientHIN = req.getParameter("patientHIN"); String patientChartNo = req.getParameter("patientChartNo"); String pracNo = req.getParameter("pracNo"); Locale locale = req.getLocale(); boolean isShowDemoDOB = false; if (showPatientDOB != null && showPatientDOB.equalsIgnoreCase("true")) { isShowDemoDOB = true; } if (!isShowDemoDOB) patientDOB = ""; if (rx == null) { rx = ""; } String additNotes = req.getParameter("additNotes"); String[] rxA = rx.split(newline); List<String> listRx = new ArrayList<String>(); String listElem = ""; // parse rx and put into a list of rx; for (String s : rxA) { if (s.equals("") || s.equals(newline) || s.length() == 1) { listRx.add(listElem); listElem = ""; } else { listElem = listElem + s; listElem += newline; } } // get the print prop values Properties props = new Properties(); StringBuilder temp = new StringBuilder(); for (Enumeration<String> e = req.getParameterNames(); e.hasMoreElements();) { temp = new StringBuilder(e.nextElement().toString()); props.setProperty(temp.toString(), req.getParameter(temp.toString())); } for (Enumeration<String> e = req.getAttributeNames(); e.hasMoreElements();) { temp = new StringBuilder(e.nextElement().toString()); props.setProperty(temp.toString(), req.getAttribute(temp.toString()).toString()); } Document document = new Document(); try { String title = req.getParameter("__title") != null ? req.getParameter("__title") : "Unknown"; // specify the page of the picture using __graphicPage, it may be used multiple times to specify multiple pages // however the same graphic will be applied to all pages // ie. __graphicPage=2&__graphicPage=3 String[] cfgGraphicFile = req.getParameterValues("__cfgGraphicFile"); int cfgGraphicFileNo = cfgGraphicFile == null ? 0 : cfgGraphicFile.length; if (cfgGraphicFile != null) { // for (String s : cfgGraphicFile) { // p("cfgGraphicFile", s); // } } String[] graphicPage = req.getParameterValues("__graphicPage"); ArrayList<String> graphicPageArray = new ArrayList<String>(); if (graphicPage != null) { // for (String s : graphicPage) { // p("graphicPage", s); // } graphicPageArray = new ArrayList<String>(Arrays.asList(graphicPage)); } // A0-A10, LEGAL, LETTER, HALFLETTER, _11x17, LEDGER, NOTE, B0-B5, ARCH_A-ARCH_E, FLSA // and FLSE // the following shows a temp way to get a print page size Rectangle pageSize = PageSize.LETTER; String pageSizeParameter = req.getParameter("rxPageSize"); if (pageSizeParameter != null) { if ("PageSize.HALFLETTER".equals(pageSizeParameter)) { pageSize = PageSize.HALFLETTER; } else if ("PageSize.A6".equals(pageSizeParameter)) { pageSize = PageSize.A6; } else if ("PageSize.A4".equals(pageSizeParameter)) { pageSize = PageSize.A4; } } /* * if ("PageSize.HALFLETTER".equals(props.getProperty(PAGESIZE))) { pageSize = PageSize.HALFLETTER; } else if ("PageSize.A6".equals(props.getProperty(PAGESIZE))) { pageSize = PageSize.A6; } else if * ("PageSize.A4".equals(props.getProperty(PAGESIZE))) { pageSize = PageSize.A4; } */ // p("size of page ", props.getProperty(PAGESIZE)); document.setPageSize(pageSize); // 285=left margin+width of box, 5f is space for looking nice document.setMargins(15, pageSize.getWidth() - 285f + 5f, 170, 60);// left, right, top , bottom writer = PdfWriter.getInstance(document, baosPDF); writer.setPageEvent(new EndPage(clinicName, clinicTel, clinicFax, patientPhone, patientCityPostal, patientAddress, patientName, patientDOB, sigDoctorName, rxDate, origPrintDate, numPrint, imgFile, patientHIN, patientChartNo, pracNo, locale)); document.addTitle(title); document.addSubject(""); document.addKeywords("pdf, itext"); document.addCreator("OSCAR"); document.addAuthor(""); document.addHeader("Expires", "0"); document.open(); document.newPage(); PdfContentByte cb = writer.getDirectContent(); BaseFont bf; // = normFont; cb.setRGBColorStroke(0, 0, 255); // render prescriptions for (String rxStr : listRx) { bf = BaseFont.createFont(BaseFont.COURIER, BaseFont.CP1252, BaseFont.NOT_EMBEDDED); Paragraph p = new Paragraph(new Phrase(rxStr, new Font(bf, 10))); p.setKeepTogether(true); p.setSpacingBefore(5f); document.add(p); } // render additional notes if (additNotes != null && !additNotes.equals("")) { bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED); Paragraph p = new Paragraph(new Phrase(additNotes, new Font(bf, 10))); p.setKeepTogether(true); p.setSpacingBefore(10f); document.add(p); } // render optometristEyeParam if (req.getAttribute("optometristEyeParam") != null) { bf = BaseFont.createFont(BaseFont.COURIER, BaseFont.CP1252, BaseFont.NOT_EMBEDDED); Paragraph p = new Paragraph( new Phrase("Eye " + (String) req.getAttribute("optometristEyeParam"), new Font(bf, 10))); p.setKeepTogether(true); p.setSpacingBefore(15f); document.add(p); } // render QrCode if (PrescriptionQrCodeUIBean.isPrescriptionQrCodeEnabledForCurrentProvider()) { Integer scriptId = Integer.parseInt(req.getParameter("scriptId")); byte[] qrCodeImage = PrescriptionQrCodeUIBean.getPrescriptionHl7QrCodeImage(scriptId); Image qrCode = Image.getInstance(qrCodeImage); document.add(qrCode); } } catch (DocumentException dex) { baosPDF.reset(); throw dex; } catch (Exception e) { logger.error("Error", e); } finally { if (document != null) { document.close(); } if (writer != null) { writer.close(); } } logger.debug("***END in generatePDFDocumentBytes2 FrmCustomedPDFServlet.java***"); return baosPDF; }
From source file:pentaho.kettle.step.plugs.pdfout.PDFOutputGenerate.java
License:Apache License
public void generatePDF(String OutputFileName) throws IOException { if (Const.isWindows()) { if (OutputFileName.startsWith("file:///")) OutputFileName = OutputFileName.substring(8); OutputFileName = OutputFileName.replace("\\", "\\\\"); }/*from www. ja va 2 s .c om*/ Document document = new Document(); PdfWriter writer; try { writer = PdfWriter.getInstance(document, new FileOutputStream(OutputFileName)); document.open(); document.add(new Paragraph("Hello Rishu Here !!")); /* * Setting up File Attributes - Document Description */ document.addAuthor("Rishu Shrivastava"); document.addCreationDate(); document.addCreator("Rishu"); document.addTitle("Set Attribute Example"); document.addSubject("An example to show how attributes can be added to pdf files."); document.close(); writer.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (DocumentException e) { e.printStackTrace(); } }
From source file:questions.metadata.UpdateModDate.java
public static void main(String[] args) { Document document = new Document(); try {/* w w w .ja va2s.c o m*/ PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(ORIGINAL)); document.addTitle("Hello World example"); document.addSubject("This example shows how to add metadata"); document.addKeywords("Metadata, iText, XMP"); document.addCreator("My program using iText"); document.addAuthor("Bruno Lowagie"); writer.createXmpMetadata(); document.open(); document.add(new Paragraph("Hello World")); } catch (DocumentException de) { System.err.println(de.getMessage()); } catch (IOException ioe) { System.err.println(ioe.getMessage()); } document.close(); try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } PdfReader reader; try { reader = new PdfReader(ORIGINAL); PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(MODIFIED)); stamper.close(); } catch (IOException e) { e.printStackTrace(); } catch (DocumentException e) { e.printStackTrace(); } }
From source file:rollyroll.com.servlet.ModuloServlet.java
private void exportar_ModulosaPDF(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { try {/*from w w w . j a v a2 s .co m*/ // String[] headers = new String[]{"CODIGO", "NOMBRE", "ACCION", "ORDEN", "ICONO", "ESTADO"}; String[] headers = new String[] { "NOMBRE", "ACCION", "ICONO" }; ArrayList<Modulo> lista = null; lista = moduloService.listar_Modulos(); PdfPTable table = new PdfPTable(headers.length); table.setHorizontalAlignment(0); table.setWidthPercentage(95); float[] espaciocolumna = new float[] { 25f, 38f, 50f }; table.setWidths(espaciocolumna); for (int i = 0; i < headers.length; i++) { String header = headers[i]; PdfPCell cell = new PdfPCell(); cell.setBackgroundColor(Color.YELLOW); cell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER); cell.setPhrase(new Phrase(header.toUpperCase(), new Font(Font.HELVETICA, 10, Font.BOLD))); table.addCell(cell); } table.completeRow(); PdfPCell cell; // int codigomodulo = 0; String nombremodulo = ""; String accionmodulo = ""; // int ordenmodulo = 0; String iconomodulo = ""; // int estadomodulo = 0; for (Modulo modulo : lista) { // codigomodulo += Integer.parseInt(modulo.getCodigomodulo()); nombremodulo += modulo.getNombremodulo(); accionmodulo += modulo.getAccionmodulo(); // ordenmodulo += Integer.parseInt(modulo.getOrdenmoduloS()); iconomodulo += modulo.getIconomodulo(); // estadomodulo += Byte.parseByte(modulo.getEstadomoduloS()); // cell = new PdfPCell(); // cell.setPhrase(new Phrase(modulo.getCodigomoduloS(), new Font(Font.HELVETICA, 10, Font.NORMAL))); // cell.setHorizontalAlignment(PdfPTable.ALIGN_CENTER); // table.addCell(cell); // cell = new PdfPCell(); cell.setPhrase(new Phrase(modulo.getNombremodulo(), new Font(Font.HELVETICA, 10, Font.NORMAL))); cell.setHorizontalAlignment(PdfPTable.ALIGN_CENTER); table.addCell(cell); cell = new PdfPCell(); cell.setPhrase(new Phrase(modulo.getAccionmodulo(), new Font(Font.HELVETICA, 10, Font.NORMAL))); cell.setHorizontalAlignment(PdfPTable.ALIGN_CENTER); table.addCell(cell); // cell = new PdfPCell(); // cell.setPhrase(new Phrase(modulo.getOrdenmoduloS(), new Font(Font.HELVETICA, 10, Font.NORMAL))); // cell.setHorizontalAlignment(PdfPTable.ALIGN_CENTER); // table.addCell(cell); cell = new PdfPCell(); cell.setPhrase(new Phrase(modulo.getIconomodulo(), new Font(Font.HELVETICA, 10, Font.NORMAL))); cell.setHorizontalAlignment(PdfPTable.ALIGN_CENTER); table.addCell(cell); // cell = new PdfPCell(); // cell.setPhrase(new Phrase(modulo.getEstadomoduloS(), new Font(Font.HELVETICA, 10, Font.NORMAL))); // cell.setHorizontalAlignment(PdfPTable.ALIGN_CENTER); // table.addCell(cell); } table.completeRow(); //incia diseo de documento exportado Document document = new Document(PageSize.A4.rotate(), 20, 5, 5, 5); ByteArrayOutputStream baos = new ByteArrayOutputStream(); PdfWriter.getInstance(document, baos); document.open(); document.addTitle("Reporte de Ventas Generales"); document.add( new Paragraph("Reporte: Ventas Generales 2016", new Font(Font.HELVETICA, 16, Font.UNDERLINE))); document.add(new Paragraph("_")); document.add(table); document.add(Chunk.NEWLINE); document.add(new Paragraph( "Leyenda: AB: Inicio, BA: Retorno (Importante: No se consideran unidades sin GPS)")); document.addAuthor("Quispe Roque Alex Christian"); table = new PdfPTable(4); table.setHorizontalAlignment(0); table.setWidthPercentage(40); espaciocolumna = new float[] { 10f, 40f, 20f, 20f }; table.setWidths(espaciocolumna); cell = new PdfPCell(); cell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER); cell.setPhrase(new Phrase("RESUMEN", new Font(Font.HELVETICA, 10, Font.BOLD))); cell.setColspan(7); table.addCell(cell); table.completeRow(); //aqui iniciamos asignacion de datos //=================================================================== // cell = new PdfPCell(); // cell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER); // cell.setPhrase(new Phrase("", new Font(Font.HELVETICA, 10, Font.BOLD))); // table.addCell(cell); // // cell = new PdfPCell(); // cell.setBackgroundColor(Color.yellow); // cell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER); // cell.setPhrase(new Phrase("FLOTA OPERATIVA", new Font(Font.HELVETICA, 10, Font.BOLD))); // table.addCell(cell); // // cell = new PdfPCell(); // cell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER); // cell.setPhrase(new Phrase(lista.size() + "", new Font(Font.HELVETICA, 10, Font.BOLD))); // table.addCell(cell); // // cell = new PdfPCell(); // cell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER); // cell.setPhrase(new Phrase("UNIDADES", new Font(Font.HELVETICA, 10, Font.BOLD))); // table.addCell(cell); // table.completeRow(); // // //================================================================================== // cell = new PdfPCell(); // cell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER); // cell.setPhrase(new Phrase("2", new Font(Font.HELVETICA, 10, Font.BOLD))); // table.addCell(cell); // // cell = new PdfPCell(); // cell.setBackgroundColor(Color.yellow); // cell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER); // cell.setPhrase(new Phrase("NRO DE VIAJES", new Font(Font.HELVETICA, 10, Font.BOLD))); // table.addCell(cell); // // cell = new PdfPCell(); // cell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER); // cell.setPhrase(new Phrase((totalAB + totalBA) + "", new Font(Font.HELVETICA, 10, Font.BOLD))); // table.addCell(cell); // // cell = new PdfPCell(); // cell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER); // cell.setPhrase(new Phrase("VIAJES", new Font(Font.HELVETICA, 10, Font.BOLD))); // table.addCell(cell); // // table.completeRow(); //================================================================================== document.add(Chunk.NEWLINE); document.add(table); document.left(1); document.top(1); document.close(); response.setHeader("Expires", "0"); response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0"); // response.setHeader("Content-Disposition", "attachment; filename=ReporteGeneraldeModulos.pdf"); response.setHeader("Content-Disposition", "filename=ReporteGeneraldeModulos.pdf"); response.setHeader("Pragma", "public"); response.setContentType("application/pdf"); response.setContentLength(baos.size()); ServletOutputStream out = response.getOutputStream(); baos.writeTo(out); out.flush(); } catch (Exception e) { RequestDispatcher rd2; rd2 = request.getRequestDispatcher("vista/include/error_404.jsp"); rd2.forward(request, response); System.out.println( "rollyroll.com.servlet.ModuloServlet.exportar_ModulosaPDF() => ERROR GRAVE AL GENERAR PDF"); e.getMessage(); } }
From source file:se.idega.idegaweb.commune.school.business.StudentAddressLabelsWriter.java
License:Open Source License
/** * Creates PDF address labels for the specified school classes. *///www .j a va 2s . c o m protected MemoryFileBuffer getPDFBuffer(IWApplicationContext iwac, Collection receivers) throws Exception { this.business = getSchoolCommuneBusiness(iwac); this.userBusiness = getCommuneUserBusiness(iwac); IWResourceBundle iwrb = iwac.getIWMainApplication().getBundle(CommuneBlock.IW_BUNDLE_IDENTIFIER) .getResourceBundle(iwac.getApplicationSettings().getApplicationLocale()); MemoryFileBuffer buffer = new MemoryFileBuffer(); MemoryOutputStream mos = new MemoryOutputStream(buffer); Document document = new Document(PageSize.A4, 50, 50, 50, 50); PdfWriter writer = PdfWriter.getInstance(document, mos); document.addTitle("Student address labels"); document.addAuthor("Idega Reports"); document.addSubject("Student address labels"); document.open(); this.font = new Font(Font.HELVETICA, 9, Font.BOLD); int studentCount = 0; Iterator iter = receivers.iterator(); while (iter.hasNext()) { if (studentCount > 0 && studentCount % NR_OF_ADDRESSES_PER_PAGE == 0) { document.newPage(); } addAddress(writer, iwrb, (MailReceiver) iter.next(), studentCount++); } if (studentCount == 0) { throw new Exception("No students."); } document.close(); writer.setPdfVersion(PdfWriter.VERSION_1_2); buffer.setMimeType(MIME_PDF); return buffer; }