List of usage examples for com.itextpdf.text.pdf PdfWriter getInstance
public static PdfWriter getInstance(final Document document, final OutputStream os) throws DocumentException
PdfWriter
. From source file:automatedbillingsoftware.helper.HtmlToPdf1.java
/** * Creates a PDF with the words "Hello World" * * @param file/*from w ww .j a va2s.co m*/ * @throws IOException * @throws DocumentException */ public void createPdf(String file, HashMap<String, Object> scopes) throws IOException, DocumentException { // step 1 Document document = new Document(); // step 2 PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file)); writer.setTagged(); // step 3 document.open(); // step 4 String readHtml = readHtml(HTML); String testTemplate = getTestTemplate(readHtml, scopes); XMLWorkerHelper.getInstance().parseXHtml(writer, document, new StringReader(testTemplate)); // XMLWorkerHelper.getInstance().parseXHtml(writer, ); // step 5 document.close(); }
From source file:avalonscrollmaker20.AnothakScribe.java
License:Open Source License
private void initializeDoc() { // Create a Document doc_scrolls = new Document(PageSize.LETTER, 18f, 18f, 18f, 18f); // Get a DocWriter instance try {// ww w .j a v a2s. com doc_writer = PdfWriter.getInstance(doc_scrolls, new FileOutputStream(doc_name)); doc_writer.setPdfVersion(PdfWriter.VERSION_1_6); } catch (Exception ex) { System.err.println(ex + "\nProgram closing."); System.exit(3); } // Open the Document doc_scrolls.addTitle(doc_name.substring(0, doc_name.length() - 3)); doc_scrolls.addSubject("A collection of Avalon-legal Anothak Scrolls"); doc_scrolls.addAuthor("Michael Weigle"); doc_scrolls.addCreator("Avalon Scrollmaker 2.0, powered by iText"); doc_scrolls.open(); }
From source file:basiclayout.ReportFrame.java
public ReportFrame(DefaultTableModel subtotal_model, String st1_date, String e1_date) throws DocumentException, IOException { this();//from w w w .j a v a 2 s .c o m report_model = (DefaultTableModel) reportTable.getModel(); reportTable.setRowSelectionAllowed(true); reportTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); document = new Document(); try { initialize_connection(); PdfWriter.getInstance((com.itextpdf.text.Document) document, new FileOutputStream("C:\\Users\\jaina_000\\Desktop\\test.pdf")); document.open(); table = new PdfPTable(5); table.setWidthPercentage(300 / 3f); table.setWidths(new int[] { 3, 3, 3, 3, 3 }); PdfPCell cell; cell = new PdfPCell(new Phrase("Category")); table.addCell(cell); cell = new PdfPCell(new Phrase("Title")); table.addCell(cell); cell = new PdfPCell(new Phrase("Date")); table.addCell(cell); cell = new PdfPCell(new Phrase("Amount")); table.addCell(cell); cell = new PdfPCell(new Phrase("Details")); table.addCell(cell); cell.setRowspan(5); final_total = 0; for (int i = 0; i < subtotal_model.getRowCount(); i++) { String subt_cat = subtotal_model.getValueAt(i, 0).toString(); resultset1 = statement1 .executeQuery("Select * from " + tableC + " WHERE CategoryName='" + subt_cat + "'"); resultset1.next(); resultset2 = statement2 .executeQuery("Select * from " + tableE + " WHERE CategoryId= '" + resultset1.getString(1) + "' " + "AND (Date BETWEEN '" + st1_date + "' AND '" + e1_date + "')"); sub_amt = 0; System.out.print("\n\nCategory: " + resultset1.getString(2)); rep_row[0] = resultset1.getString(2); for (int z = 1; z < 5; z++) { rep_row[z] = null; } report_model.addRow(rep_row); table.addCell(new PdfPCell(new Phrase((String) rep_row[0]))); table.addCell(new PdfPCell(new Phrase(""))); table.addCell(new PdfPCell(new Phrase(""))); table.addCell(new PdfPCell(new Phrase(""))); table.addCell(new PdfPCell(new Phrase(""))); cell.setRowspan(5); while (resultset2.next()) { rep_row[0] = null; System.out.print("\nTitle : " + resultset2.getString(5)); // Title rep_row[1] = resultset2.getString(5); System.out.print("\tDate : " + resultset2.getString(2)); // Date rep_row[2] = resultset2.getString(2); System.out.print("\tAmount: " + Math.abs(Integer.parseInt(resultset2.getString(4)))); rep_row[3] = Math.abs(Integer.parseInt(resultset2.getString(4))); System.out.print("\tDescription : " + resultset2.getString(6)); // Description rep_row[4] = resultset2.getString(6); table.addCell(new PdfPCell(new Phrase((String) rep_row[0]))); table.addCell(new PdfPCell(new Phrase((String) rep_row[1]))); table.addCell(new PdfPCell(new Phrase((String) rep_row[2]))); table.addCell(new PdfPCell(new Phrase(String.valueOf(rep_row[3])))); table.addCell(new PdfPCell(new Phrase((String) rep_row[4]))); sub_amt += Integer.parseInt(resultset2.getString(4)); report_model.addRow(rep_row); cell.setRowspan(5); } final_total += sub_amt; for (int z = 0; z < 5; z++) { rep_row[z] = null; } rep_row[2] = "Subtotal"; rep_row[3] = Math.abs(sub_amt); System.out.println("\nCategory Subtotal : " + Math.abs(sub_amt)); table.addCell(new PdfPCell(new Phrase((String) rep_row[0]))); table.addCell(new PdfPCell(new Phrase((String) rep_row[1]))); table.addCell(new PdfPCell(new Phrase((String) rep_row[2]))); table.addCell(new PdfPCell(new Phrase(String.valueOf(rep_row[3])))); table.addCell(new PdfPCell(new Phrase((String) rep_row[4]))); report_model.addRow(rep_row); cell.setRowspan(5); } for (int z = 0; z < 5; z++) { rep_row[z] = null; } report_model.addRow(rep_row); report_model.addRow(rep_row); System.out.print("\n\nFinal total: " + Math.abs(final_total)); rep_row[2] = "Final Total"; rep_row[3] = Math.abs(final_total); if (final_total < 0) { System.out.println(" (Expense)"); rep_row[4] = "(Expense)"; } else { System.out.println(" (Income)"); rep_row[4] = "(Income)"; } table.addCell(new PdfPCell(new Phrase((String) rep_row[0]))); table.addCell(new PdfPCell(new Phrase((String) rep_row[1]))); table.addCell(new PdfPCell(new Phrase((String) rep_row[2]))); table.addCell(new PdfPCell(new Phrase(String.valueOf(rep_row[3])))); table.addCell(new PdfPCell(new Phrase((String) rep_row[4]))); report_model.addRow(rep_row); cell.setRowspan(5); } catch (ClassNotFoundException | SQLException e) { } catch (FileNotFoundException ex) { Logger.getLogger(ReportFrame.class.getName()).log(Level.SEVERE, null, ex); } finally { close_connection(); } }
From source file:bd.gov.forms.web.FormBuilder.java
License:Open Source License
@RequestMapping(value = "/individualpdf", method = RequestMethod.GET) public String individualpdf(@RequestParam(value = "formId", required = true) String formId, @RequestParam(value = "entryId", required = true) String entryId, ModelMap model, HttpServletResponse response) throws IOException { byte[] fileContent = formDao.getTemplateContent(formId); Form form = formDao.getFormWithFields(formId); form.setEntryId(entryId);// w w w .j av a2 s . co m form = formDao.getEntry(form); String report = ""; Document document = new Document(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); if (fileContent != null) { report = new String(fileContent, "UTF8"); for (Field field : form.getFields()) { if (fieldTypeIsNotOfFileOrNoteOrSection(field)) { report = report.replaceAll("#" + field.getColName() + ":label#", field.getLabel()); report = report.replaceAll("#" + field.getColName() + ":value#", field.getStrVal()); } } } else { // step 2 try { response.reset(); response.setContentType("application/pdf"); response.setHeader("Content-disposition", "inline; filename=test.pdf"); response.setHeader("Cache-Control", "no-cache"); response.setDateHeader("Expires", 0); response.setHeader("Pragma", "No-cache"); PdfWriter writer = PdfWriter.getInstance(document, baos); // step 3 document.open(); PdfPCell space; space = new PdfPCell(); space.setBorder(Rectangle.NO_BORDER); space.setColspan(2); space.setFixedHeight(8); PdfPTable table = new PdfPTable(2); PdfPCell cell; report += "<table cellspacing='0' cellpadding='0' style='border:1px solid #aaa;width:98%;'>"; for (Field field : form.getFields()) { if (fieldTypeIsNotOfFileOrNoteOrSection(field)) { report += field.getLabel(); report += field.getStrVal(); table.setWidths(new int[] { 1, 2 }); table.addCell(field.getLabel()); //cell = new PdfPCell(); //cell.setCellEvent(new TextFields(1)); table.addCell(field.getStrVal()); } } document.add(table); document.close(); ServletOutputStream out = response.getOutputStream(); baos.writeTo(out); out.flush(); } catch (Exception ex) { System.out.println("Could not print reasone::" + ex.toString()); } } return null; }
From source file:bd.gov.forms.web.FormBuilder.java
License:Open Source License
@RequestMapping(value = "/pdfExport", method = RequestMethod.GET) public String pdfExport(@RequestParam(value = "formId", required = true) String formId, @RequestParam(value = "page", required = false) Integer page, @RequestParam(value = "colName", required = false) String colName, @RequestParam(value = "colVal", required = false) String colVal, @RequestParam(value = "sortCol", required = false) String sortCol, @RequestParam(value = "sortDir", required = false) String sortDir, ModelMap model, HttpServletResponse response, HttpServletRequest request) throws IOException { Document document = new Document(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); // step 2/*from w w w.ja v a2 s .c o m*/ try { response.reset(); response.setContentType("application/pdf"); response.setHeader("Content-disposition", "inline; filename=test.pdf"); response.setHeader("Cache-Control", "no-cache"); response.setDateHeader("Expires", 0); response.setHeader("Pragma", "No-cache"); PdfWriter writer = PdfWriter.getInstance(document, baos); // step 3 document.open(); Form form = null; //System.out.println("The form id is 1:"+formId); if (formId != null) { form = formDao.getFormWithFields(formId); } if (form != null) { if (form.getStatus() != 2) {//2-active, 3-deactive model.put("doneMessage", "msg.access.denied"); model.put("doneMsgType", "failed"); return "redirect:done.htm"; } initForm(form); } List<Field> fieldList = form.getFields(); if (fieldList.isEmpty()) { System.out.println("The list size is zero"); } PdfPCell space; space = new PdfPCell(); space.setBorder(Rectangle.NO_BORDER); space.setColspan(2); space.setFixedHeight(8); PdfPTable table = new PdfPTable(2); PdfPCell cell; //PdfPCell cell; table.setWidths(new int[] { 1, 2 }); int i = 0; for (Field f : fieldList) { if ("text".equals(f.getType())) { table.addCell(f.getLabel()); cell = new PdfPCell(); cell.setCellEvent(new TextFields(1, i)); table.addCell(cell); } else if ("textarea".equals(f.getType())) { table.addCell(f.getLabel()); cell = new PdfPCell(); cell.setCellEvent(new TextFields(1, i)); cell.setFixedHeight(60); table.addCell(cell); } else if ("select".equals(f.getType())) { table.addCell(f.getType()); cell = new PdfPCell(); cell.setCellEvent(new ChoiceFields(3, f.getList().toArray())); table.addCell(cell); //table.addCell(space); System.out.println("ajsdhd"); } i++; } /* for(Field f : fieldList) { if( "radio".equals(f.getType()) ) { System.out.println("List "+f.getList()+" Oppt"+f.getOptions()+ " df"+f.getColName()); writer = PdfWriter.getInstance(document, new FileOutputStream("TextFieldForm.pdf")); //writer.addJavaScript(Utilities.readFileToString("")); // add the radio buttons PdfContentByte canvas = writer.getDirectContent(); Font font = new Font(FontFamily.HELVETICA, 14); Rectangle rect; PdfFormField field; PdfFormField radiogroup = PdfFormField.createRadioButton(writer, true); radiogroup.setFieldName("language"); RadioCheckField radio; for (int i = 0; i < 2; i++) { rect = new Rectangle(40, 806 - i * 40, 60, 788 - i * 40); radio = new RadioCheckField(writer, rect, null, f.getLabel()); radio.setBorderColor(GrayColor.GRAYBLACK); radio.setBackgroundColor(GrayColor.GRAYWHITE); radio.setCheckType(RadioCheckField.TYPE_CIRCLE); field = radio.getRadioField(); radiogroup.addKid(field); writer.addAnnotation(field); ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT, new Phrase(f.getLabel(), font), 70, 790 - i * 40, 0); } //table.addCell(f.getLabel()); //cell = new PdfPCell(); //document.add(radiogroup); //writer.addAnnotation(radiogroup); } } */ // Add submit button PushbuttonField submitBtn = new PushbuttonField(writer, new Rectangle(400, 700, 370, 670), "submitPOST"); //submitBtn.setBackgroundColor(Color.GRAY); submitBtn.setBorderStyle(PdfBorderDictionary.STYLE_BEVELED); submitBtn.setText("Submit"); submitBtn.setOptions(PushbuttonField.VISIBLE_BUT_DOES_NOT_PRINT); PdfFormField submitField = submitBtn.getField(); submitField.setAction( PdfAction.createSubmitForm("http://localhost:8084/GovForm-07-02/formBuilder/pdfresponse.htm", null, PdfAction.SUBMIT_HTML_FORMAT)); writer.addAnnotation(submitField); document.add(table); System.out.println("Pdf creation successful"); document.close(); ServletOutputStream out = response.getOutputStream(); baos.writeTo(out); out.flush(); } catch (Exception ex) { System.out.println("Could not print reasone::" + ex.toString()); } //////////////////////////////////////// email part//////////////////////////// //email functionalities // Recipient's email ID needs to be mentioned. String to = "tanviranik@gmail.com"; // Sender's email ID needs to be mentioned String from = "tanvir_cse@yahoo.com"; // Assuming you are sending email from localhost String host = "localhost"; // Get system properties Properties properties = System.getProperties(); // Setup mail server properties.setProperty("mail.smtp.host", host); // Get the default Session object. Session session = Session.getDefaultInstance(properties); try { // Create a default MimeMessage object. MimeMessage message = new MimeMessage(session); // Set From: header field of the header. message.setFrom(new InternetAddress(from)); // Set To: header field of the header. message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); // Set Subject: header field message.setSubject("This is the Subject Line!"); // Now set the actual message message.setText("This is actual message"); // Send message Transport.send(message); System.out.println("Sent message successfully...."); } catch (MessagingException mex) { mex.printStackTrace(); } //////////////////////////////////////// email part//////////////////////////// return null; }
From source file:be.kcbj.placemat.Placemat.java
License:Open Source License
private void createPdf(File file, List<Sponsor> sponsors) throws IOException, DocumentException { System.out.println("Generating PDF file " + file.getAbsolutePath()); Layout layout = new Layout(sponsors); System.out.println("Layout = " + layout); Document document = new Document(); PdfWriter.getInstance(document, new FileOutputStream(file)); document.setPageSize(PageSize.A4.rotate()); document.setMargins(PADDING_DOC, PADDING_DOC, PADDING_DOC, PADDING_DOC); document.open();// w w w . java2s . c o m PdfPTable table = new PdfPTable(layout.getColumnCount()); table.setWidthPercentage(100); table.setSpacingBefore(0f); table.setSpacingAfter(0f); for (int i = 0; i < sponsors.size(); i++) { table.addCell(generateCell(sponsors.get(i), layout.getCellHeight())); } for (int i = 0; i < layout.getEmptyCellCount(); i++) { table.addCell(generateCell(new Sponsor(), layout.getCellHeight())); } document.add(table); document.close(); }
From source file:be.mxs.common.util.pdf.general.chuk.GeneralPDFCreator.java
public ByteArrayOutputStream generatePDFDocumentBytes(final HttpServletRequest req, ServletContext application, boolean filterApplied, int partsOfTransactionToPrint) throws DocumentException { ByteArrayOutputStream baosPDF = new ByteArrayOutputStream(); PdfWriter docWriter = null;//from ww w. j a va 2 s .co m this.req = req; this.application = application; sContextPath = req.getContextPath(); try { docWriter = PdfWriter.getInstance(doc, baosPDF); //*** META TAGS *********************************************************************** doc.addProducer(); doc.addAuthor(user.person.firstname + " " + user.person.lastname); doc.addCreationDate(); doc.addCreator("OpenClinic Software for Hospital Management"); doc.addTitle("Medical Record Data for " + patient.firstname + " " + patient.lastname); doc.addKeywords(patient.firstname + ", " + patient.lastname); doc.setPageSize(PageSize.A4); //*** FOOTER ************************************************************************** PDFFooter footer = new PDFFooter("OpenClinic pdf engine (c)2007, Post-Factum bvba\n" + MedwanQuery.getInstance().getLabel("web.occup", "medwan.common.patientrecord", sPrintLanguage) + " " + patient.getID("immatnew") + " " + patient.firstname + " " + patient.lastname); docWriter.setPageEvent(footer); doc.open(); //*** HEADER ************************************************************************** printDocumentHeader(req); //*** TITLE *************************************************************************** String title = getTran("Web.Occup", "medwan.common.occupational-health-record").toUpperCase(); // add date restriction to document title title += "\n(" + getTran("web", "printdate") + ": " + dateFormat.format(new Date()) + ")"; /* if(dateFrom!=null && dateTo!=null){ if(dateFrom.getTime() == dateTo.getTime()){ title+= "\n("+getTran("web","on")+" "+dateFormat.format(dateTo)+")"; } else{ title+= "\n("+getTran("pdf","date.from")+" "+dateFormat.format(dateFrom)+" "+getTran("pdf","date.to")+" "+dateFormat.format(dateTo)+")"; } } else if(dateFrom!=null){ title+= "\n("+getTran("web","since")+" "+dateFormat.format(dateFrom)+")"; } else if(dateTo!=null){ title+= "\n("+getTran("pdf","date.to")+" "+dateFormat.format(dateTo)+")"; }*/ Paragraph par = new Paragraph(title, FontFactory.getFont(FontFactory.HELVETICA, 12, Font.BOLD)); par.setAlignment(Paragraph.ALIGN_CENTER); doc.add(par); //*** OTHER DOCUMENT ELEMENTS ********************************************************* printAdminHeader(patient); //printKeyData(sessionContainerWO); printMedication(sessionContainerWO); printActiveDiagnosis(sessionContainerWO); printWarnings(sessionContainerWO); doc.add(new Paragraph(" ")); //*** VACCINATION CARD **************************************************************** new be.mxs.common.util.pdf.general.oc.examinations.PDFVaccinationCard().printCard(doc, sessionContainerWO, transactionVO, patient, req, sProject, sPrintLanguage, new Integer(partsOfTransactionToPrint)); //*** TRANSACTIONS ******************************************************************** Enumeration e = req.getParameterNames(); String paramName, paramValue, sTranID, sServerID; boolean transactionIDsSpecified = false; while (e.hasMoreElements()) { paramName = (String) e.nextElement(); // transactionIDs were specified as request-parameters if (paramName.startsWith("tranAndServerID_")) { transactionIDsSpecified = true; paramValue = checkString(req.getParameter(paramName)); sTranID = paramValue.substring(0, paramValue.indexOf("_")); sServerID = paramValue.substring(paramValue.indexOf("_") + 1); this.transactionVO = MedwanQuery.getInstance().loadTransaction(Integer.parseInt(sServerID), Integer.parseInt(sTranID)); loadTransaction(transactionVO, 2); // 2 = print whole transaction } } if (!transactionIDsSpecified) { printTransactions(filterApplied, partsOfTransactionToPrint); } doc.add(new Paragraph(" ")); printSignature(); } catch (DocumentException dex) { baosPDF.reset(); throw dex; } catch (Exception e) { e.printStackTrace(); } finally { if (doc != null) doc.close(); if (docWriter != null) docWriter.close(); } if (baosPDF.size() < 1) { throw new DocumentException("document has " + baosPDF.size() + " bytes"); } return baosPDF; }
From source file:be.mxs.common.util.pdf.general.dossierCreators.StaffDossierPDFCreator.java
public ByteArrayOutputStream generatePDFDocumentBytes(final HttpServletRequest req, ServletContext application) throws DocumentException { this.req = req; this.application = application; this.baosPDF = new ByteArrayOutputStream(); String sURL = req.getRequestURL().toString(); if (sURL.indexOf("openclinic", 10) > 0) { sURL = sURL.substring(0, sURL.indexOf("openclinic", 10)); }/* w ww. ja va 2s .c om*/ if (sURL.indexOf("openinsurance", 10) > 0) { sURL = sURL.substring(0, sURL.indexOf("openinsurance", 10)); } String sContextPath = req.getContextPath() + "/"; HttpSession session = req.getSession(); String sProjectDir = (String) session.getAttribute("activeProjectDir"); // if request from Chuk, project = chuk if (sContextPath.indexOf("chuk") > -1) { sContextPath = "openclinic/"; sProjectDir = "projects/chuk/"; } this.url = sURL; this.contextPath = sContextPath; this.projectDir = sProjectDir; try { docWriter = PdfWriter.getInstance(doc, baosPDF); //*** META TAGS *********************************************************************** doc.addProducer(); doc.addAuthor(user.person.firstname + " " + user.person.lastname); doc.addCreationDate(); doc.addCreator("OpenClinic Software for Hospital Management"); doc.addTitle("Medical Record Data for " + patient.firstname + " " + patient.lastname); doc.addKeywords(patient.firstname + ", " + patient.lastname); doc.setPageSize(PageSize.A4); doc.open(); //*** HEADER ************************************************************************** printDocumentHeader(req); //*** TITLE *************************************************************************** String sTitle = getTran("web", "staffDossier").toUpperCase(); printDocumentTitle(req, sTitle); //*** SECTIONS ************************************************************************ /* - 1 : Administratie persoonlijk - 2 : Administratie priv - 3 : Human resources contracten - 4 : Human resources Competenties - 5 : Human resources carrire - 6 : Human resources disciplinair dossier - 7 : Human resources verlof en afwezigheden - 8 : Human resources salaris - 9 : Human resources uurrooster */ boolean[] sections = new boolean[17]; // which sections are chosen ? Enumeration parameters = req.getParameterNames(); Vector paramNames = new Vector(); String sParamName, sParamValue; // sort the parameternames while (parameters.hasMoreElements()) { sParamName = (String) parameters.nextElement(); if (sParamName.startsWith("section_")) { paramNames.add(new Integer(sParamName.substring("section_".length()))); } } Collections.sort(paramNames); // on number int sectionIdx = 0; for (int i = 0; i < paramNames.size(); i++) { sectionIdx = ((Integer) paramNames.get(i)).intValue() - 1; sections[sectionIdx] = checkString(req.getParameter("section_" + (sectionIdx + 1))) .equalsIgnoreCase("on"); Debug.println("Adding section[" + sectionIdx + "] to document : " + sections[sectionIdx]); } sectionIdx = 0; if (sections[sectionIdx++]) { printPatientCard(patient, sections[1]); // 0, showPhoto printAdminData(patient); } if (sections[sectionIdx++]) { //printPhoto(patient); // 1 } if (sections[sectionIdx++]) { printAdminPrivateData(patient); // 2 } if (sections[sectionIdx++]) { printHRContracts(sessionContainerWO, patient); // 3 } if (sections[sectionIdx++]) { printHRSkills(sessionContainerWO, patient); // 4 } if (sections[sectionIdx++]) { printHRCareer(sessionContainerWO, patient); // 5 } if (sections[sectionIdx++]) { printHRDisciplinaryRecord(sessionContainerWO, patient); // 6 } if (sections[sectionIdx++]) { printHRLeaves(sessionContainerWO, patient); // 8 } if (sections[sectionIdx++]) { printHRSalary(sessionContainerWO, patient); // 9 } if (sections[sectionIdx++]) { printHRWorkSchedules(sessionContainerWO, patient); // 10 } if (sections[sectionIdx++]) { printHRTraining(sessionContainerWO, patient); // 11 } if (sections[sectionIdx++]) { printSignature(); // 12 : not in jsp } } catch (DocumentException dex) { baosPDF.reset(); throw dex; } catch (Exception e) { e.printStackTrace(); } finally { if (doc != null) doc.close(); if (docWriter != null) docWriter.close(); } if (baosPDF.size() < 1) { throw new DocumentException("ERROR : The pdf-document has " + baosPDF.size() + " bytes"); } return baosPDF; }
From source file:be.rheynaerde.poolsheets.AbstractPoolSheet.java
License:Open Source License
protected void buildSheet() throws DocumentException { Rectangle pageSize = configuration.isLandscape(AbstractPoolSheetConfiguration.TITLE_PAGE) ? PageSize.A4.rotate()/*from w w w.j a v a 2 s .com*/ : PageSize.A4; Document document = new Document(pageSize); ByteArrayOutputStream baos = new ByteArrayOutputStream(); PdfWriter.getInstance(document, baos); document.open(); document.addTitle(configuration.getTitle()); document.addCreator(CREATOR); buildTitle(document); buildTable(document); if (configuration.includeOrderOfBouts()) { if (configuration.putBoutOrderOnNewPage()) { pageSize = configuration.isLandscape(AbstractPoolSheetConfiguration.BOUT_ORDER_PAGE) ? PageSize.A4.rotate() : PageSize.A4; document.setPageSize(pageSize); document.newPage(); } buildBoutOrder(document); } document.close(); sheet = baos.toByteArray(); }
From source file:be.roots.taconic.pricingguide.service.PDFServiceImpl.java
License:Open Source License
private byte[] createModelPages(Contact contact, List<Model> models, Toc tableOfContents) throws IOException, DocumentException { ByteArrayOutputStream bos = new ByteArrayOutputStream(); Document document = iTextUtil.createNewDocument(); PdfWriter writer = PdfWriter.getInstance(document, bos); document.open();//from www .ja v a 2 s. c o m // create a PdfPTable for every model (so we can measure the height) final List<PdfPTable> modelPageTables = new ArrayList<>(); Collections.sort(models); for (Model model : models) { if (model != null) { modelPageTables.add(createModelPage(contact, model, writer)); } } // put the PdfPTable Models tables on PDF pages (multiple per page if possible) byte[] pages = new byte[] {}; int height = 0; List<String> pageNames = new ArrayList<>(); int i = 0; for (PdfPTable modelPageTable : modelPageTables) { // create a new pdf page, if necessary if (height != 0 && (height + modelPageTable.getTotalHeight() + 20 /* for the line separator */ ) >= iTextUtil.PAGE_HEIGHT) { writer.close(); document.close(); bos.close(); byte[] page = bos.toByteArray(); tableOfContents.addEntries(2, pageNames, page, true, Toc.MODEL_SORT_PREFIX + "___" + IntUtil.format(++i)); pages = iTextUtil.merge(pages, page); height = 0; pageNames.clear(); bos = new ByteArrayOutputStream(); document = iTextUtil.createNewDocument(); writer = PdfWriter.getInstance(document, bos); document.open(); } else if (height != 0) { // if not the first model on the page, draw a separator document.add(new Paragraph( new Chunk(new LineSeparator(.25f, 80f, BaseColor.LIGHT_GRAY, Element.ALIGN_CENTER, -2)))); document.add(new Paragraph(new Chunk(" "))); } // rerender the table (with a valid pdfWriter) document.add(createModelPage(contact, models.get(modelPageTables.indexOf(modelPageTable)), writer)); height += modelPageTable.getTotalHeight(); pageNames.add(models.get(modelPageTables.indexOf(modelPageTable)).getProductNameProcessed()); } writer.close(); document.close(); byte[] page = bos.toByteArray(); tableOfContents.addEntries(2, pageNames, page, true, Toc.MODEL_SORT_PREFIX + "___" + IntUtil.format(++i)); pages = iTextUtil.merge(pages, page); return pages; }