List of usage examples for com.lowagie.text HeaderFooter setAlignment
public void setAlignment(int alignment)
From source file:org.kuali.kfs.module.endow.report.util.TrialBalanceReportPrint.java
License:Educational Community License
/** * Generates the report in PDF using iText * // www. j a v a 2 s . c o m * @param reportRequestHeaderDataHolder * @param trialBalanceDataReportHolders * @return ByteArrayOutputStream */ public ByteArrayOutputStream printTrialBalanceReport( EndowmentReportHeaderDataHolder reportRequestHeaderDataHolder, List<TrialBalanceReportDataHolder> trialBalanceDataReportHolders, String listKemidsInHeader) { final org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(TrialBalanceReportPrint.class); Document document = new Document(); document.setPageSize(LETTER_PORTRAIT); document.addTitle("Endowment Trial Balance"); // get the stream for PDF ByteArrayOutputStream pdfStream = new ByteArrayOutputStream(); try { PdfWriter.getInstance(document, pdfStream); document.open(); // page HeaderFooter header = new HeaderFooter(new Phrase(new Date().toString() + " Page: ", headerFont), true); header.setBorder(Rectangle.NO_BORDER); header.setAlignment(Element.ALIGN_RIGHT); header.setPageNumber(0); document.setHeader(header); // print the report header if (printReportHeaderPage(reportRequestHeaderDataHolder, document, listKemidsInHeader)) { if (trialBalanceDataReportHolders != null && trialBalanceDataReportHolders.size() > 0) { document.setPageSize(LETTER_LANDSCAPE); document.resetPageCount(); header.setPageNumber(1); document.newPage(); printTrialBalanceReportBody(trialBalanceDataReportHolders, document); } else { LOG.error("Trial Balance Report Header Error"); } } document.close(); } catch (Exception e) { LOG.error("PDF Error: " + e.getMessage()); return null; } return pdfStream; }
From source file:org.kuali.kra.printing.service.impl.PrintingServiceImpl.java
License:Educational Community License
/** * @param pdfBytesList//from www. ja v a 2 s. com * List containing the PDF data bytes * @param bookmarksList * List of bookmarks corresponding to the PDF bytes. * @return * @throws PrintingException */ protected byte[] mergePdfBytes(List<byte[]> pdfBytesList, List<String> bookmarksList, boolean headerFooterRequired) throws PrintingException { Document document = null; PdfWriter writer = null; ByteArrayOutputStream mergedPdfReport = new ByteArrayOutputStream(); int totalNumOfPages = 0; PdfReader[] pdfReaderArr = new PdfReader[pdfBytesList.size()]; int pdfReaderCount = 0; for (byte[] fileBytes : pdfBytesList) { LOG.debug("File Size " + fileBytes.length + " For " + bookmarksList.get(pdfReaderCount)); PdfReader reader = null; try { reader = new PdfReader(fileBytes); pdfReaderArr[pdfReaderCount] = reader; pdfReaderCount = pdfReaderCount + 1; totalNumOfPages += reader.getNumberOfPages(); } catch (IOException e) { LOG.error(e.getMessage(), e); } } HeaderFooter footer = null; if (headerFooterRequired) { Calendar calendar = dateTimeService.getCurrentCalendar(); String dateString = formateCalendar(calendar); StringBuilder footerPhStr = new StringBuilder(); footerPhStr.append(" of "); footerPhStr.append(totalNumOfPages); footerPhStr.append(getWhitespaceString(WHITESPACE_LENGTH_76)); footerPhStr.append(getWhitespaceString(WHITESPACE_LENGTH_76)); footerPhStr.append(getWhitespaceString(WHITESPACE_LENGTH_60)); footerPhStr.append(dateString); Font font = FontFactory.getFont(FontFactory.TIMES, 8, Font.NORMAL, Color.BLACK); Phrase beforePhrase = new Phrase("Page ", font); Phrase afterPhrase = new Phrase(footerPhStr.toString(), font); footer = new HeaderFooter(beforePhrase, afterPhrase); footer.setAlignment(Element.ALIGN_BASELINE); footer.setBorderWidth(0f); } for (int count = 0; count < pdfReaderArr.length; count++) { PdfReader reader = pdfReaderArr[count]; int nop; if (reader == null) { LOG.debug("Empty PDF byetes found for " + bookmarksList.get(count)); continue; } else { nop = reader.getNumberOfPages(); } if (count == 0) { document = nop > 0 ? new com.lowagie.text.Document(reader.getPageSizeWithRotation(1)) : new com.lowagie.text.Document(); try { writer = PdfWriter.getInstance(document, mergedPdfReport); } catch (DocumentException e) { LOG.error(e.getMessage(), e); throw new PrintingException(e.getMessage(), e); } if (footer != null) { document.setFooter(footer); } // writer.setPageEvent(new Watermark()); // add watermark object here document.open(); } PdfContentByte cb = writer.getDirectContent(); int pageCount = 0; while (pageCount < nop) { document.setPageSize(reader.getPageSize(++pageCount)); document.newPage(); if (footer != null) { document.setFooter(footer); } PdfImportedPage page = writer.getImportedPage(reader, pageCount); cb.addTemplate(page, 1, 0, 0, 1, 0, 0); PdfOutline root = cb.getRootOutline(); if (pageCount == 1) { String pageName = bookmarksList.get(count); cb.addOutline(new PdfOutline(root, new PdfDestination(PdfDestination.FITH), pageName), pageName); } } } if (document != null) { try { document.close(); return mergedPdfReport.toByteArray(); } catch (Exception e) { LOG.error("Exception occured because the generated PDF document has no pages", e); } } return null; }
From source file:org.netxilia.server.rest.pdf.SheetPdfProvider.java
License:Open Source License
@Override public void writeTo(SheetFullName sheetName, Class<?> clazz, Type type, Annotation[] ann, MediaType mediaType, MultivaluedMap<String, Object> headers, OutputStream out) throws IOException, WebApplicationException { if (sheetName == null) { return;//www . j av a 2 s . com } /** * This is the table, added as an Element to the PDF document. It contains all the data, needed to represent the * visible table into the PDF */ Table tablePDF; /** * The default font used in the document. */ Font smallFont = FontFactory.getFont(FontFactory.HELVETICA, 7, Font.NORMAL, new Color(0, 0, 0)); ISheet summarySheet = null; ISheet sheet = null; try { sheet = workbookProcessor.getWorkbook(sheetName.getWorkbookId()).getSheet(sheetName.getSheetName()); try { // get the corresponding summary sheet SheetFullName summarySheetName = SheetFullName.summarySheetName(sheetName, userService.getCurrentUser()); summarySheet = workbookProcessor.getWorkbook(summarySheetName.getWorkbookId()) .getSheet(summarySheetName.getSheetName()); } catch (Exception e) { // no summary sheet - go without one } // Initialize the Document and register it with PdfWriter listener and the OutputStream Document document = new Document(PageSize.A4.rotate(), 60, 60, 40, 40); document.addCreationDate(); HeaderFooter footer = new HeaderFooter(new Phrase("", smallFont), true); footer.setBorder(Rectangle.NO_BORDER); footer.setAlignment(Element.ALIGN_CENTER); PdfWriter.getInstance(document, out); // Fill the virtual PDF table with the necessary data // Initialize the table with the appropriate number of columns tablePDF = initTable(sheet); // take tha maximum numbers of columns int columnCount = sheet.getDimensions().getNonBlocking().getColumnCount(); if (summarySheet != null) { columnCount = Math.max(columnCount, summarySheet.getDimensions().getNonBlocking().getColumnCount()); } generateHeaders(sheet, tablePDF, smallFont, columnCount); tablePDF.endHeaders(); generateRows(sheet, false, tablePDF, smallFont, columnCount); if (summarySheet != null) { generateRows(summarySheet, true, tablePDF, smallFont, columnCount); } document.open(); document.setFooter(footer); document.add(tablePDF); document.close(); out.flush(); out.close(); } catch (Exception e) { throw new IOException(e); } }
From source file:org.oscarehr.casemgmt.print.OscarChartPrinter.java
License:Open Source License
public void printDocHeaderFooter() throws DocumentException { String headerTitle = demographic.getFormattedName() + " " + demographic.getAge() + " " + demographic.getSex() + " DOB:" + demographic.getFormattedDob(); //set up document title and header ResourceBundle propResource = ResourceBundle.getBundle("oscarResources"); String title = propResource.getString("oscarEncounter.pdfPrint.title") + " " + (String) request.getAttribute("demoName") + "\n"; String gender = propResource.getString("oscarEncounter.pdfPrint.gender") + " " + (String) request.getAttribute("demoSex") + "\n"; String dob = propResource.getString("oscarEncounter.pdfPrint.dob") + " " + (String) request.getAttribute("demoDOB") + "\n"; String age = propResource.getString("oscarEncounter.pdfPrint.age") + " " + (String) request.getAttribute("demoAge") + "\n"; String mrp = propResource.getString("oscarEncounter.pdfPrint.mrp") + " " + (String) request.getAttribute("mrp") + "\n"; String[] info = new String[] { title, gender, dob, age, mrp }; ClinicData clinicData = new ClinicData(); clinicData.refreshClinicData();//from w w w . j a v a 2s. c o m String[] clinic = new String[] { clinicData.getClinicName(), clinicData.getClinicAddress(), clinicData.getClinicCity() + ", " + clinicData.getClinicProvince(), clinicData.getClinicPostal(), clinicData.getClinicPhone() }; if (newPage) { document.newPage(); newPage = false; } //Header will be printed at top of every page beginning with p2 Phrase headerPhrase = new Phrase(LEADING, headerTitle, boldFont); HeaderFooter header = new HeaderFooter(headerPhrase, false); header.setAlignment(HeaderFooter.ALIGN_CENTER); document.setHeader(header); getDocument().add(headerPhrase); getDocument().add(new Phrase("\n")); Paragraph p = new Paragraph("Tel:" + demographic.getPhone(), getFont()); p.setAlignment(Paragraph.ALIGN_LEFT); // getDocument().add(p); Paragraph p2 = new Paragraph("Date of Visit: ", getFont()); p2.setAlignment(Paragraph.ALIGN_RIGHT); // getDocument().add(p); PdfPTable table = new PdfPTable(2); table.setWidthPercentage(100f); table.getDefaultCell().setBorder(PdfPCell.NO_BORDER); PdfPCell cell1 = new PdfPCell(p); cell1.setBorder(PdfPCell.NO_BORDER); cell1.setHorizontalAlignment(Element.ALIGN_LEFT); PdfPCell cell2 = new PdfPCell(p2); cell2.setHorizontalAlignment(Element.ALIGN_RIGHT); cell2.setBorder(PdfPCell.NO_BORDER); table.addCell(cell1); table.addCell(cell2); getDocument().add(table); table = new PdfPTable(3); table.setWidthPercentage(100f); table.getDefaultCell().setBorder(PdfPCell.NO_BORDER); cell1 = new PdfPCell(getParagraph("Signed Provider:" + ((signingProvider != null) ? signingProvider : ""))); cell1.setBorder(PdfPCell.NO_BORDER); cell1.setHorizontalAlignment(Element.ALIGN_LEFT); cell2 = new PdfPCell(getParagraph("RFR:")); cell2.setHorizontalAlignment(Element.ALIGN_CENTER); cell2.setBorder(PdfPCell.NO_BORDER); PdfPCell cell3 = new PdfPCell(getParagraph("Ref:")); cell3.setHorizontalAlignment(Element.ALIGN_RIGHT); cell3.setBorder(PdfPCell.NO_BORDER); table.addCell(cell1); table.addCell(cell2); table.addCell(cell3); getDocument().add(table); //Write title with top and bottom borders on p1 cb = writer.getDirectContent(); cb.setColorStroke(new Color(0, 0, 0)); cb.setLineWidth(0.5f); cb.moveTo(document.left(), document.top() - (font.getCalculatedLeading(LINESPACING) * 5f)); cb.lineTo(document.right(), document.top() - (font.getCalculatedLeading(LINESPACING) * 5f)); cb.stroke(); }
From source file:org.oscarehr.casemgmt.service.CaseManagementPrintPdf.java
License:Open Source License
public void printDocHeaderFooter() throws IOException, DocumentException { //Create the document we are going to write to document = new Document(); PdfWriter writer = PdfWriter.getInstance(document, os); writer.setPageEvent(new EndPage()); document.setPageSize(PageSize.LETTER); document.open();//from w w w .j av a 2s .co m //Create the font we are going to print to bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED); font = new Font(bf, FONTSIZE, Font.NORMAL); String title = "", gender = "", dob = "", age = "", mrp = ""; if (this.demoDtl != null) { //set up document title and header ResourceBundle propResource = ResourceBundle.getBundle("oscarResources"); title = propResource.getString("oscarEncounter.pdfPrint.title") + " " + (String) demoDtl.get("demoName") + "\n"; gender = propResource.getString("oscarEncounter.pdfPrint.gender") + " " + (String) demoDtl.get("demoSex") + "\n"; dob = propResource.getString("oscarEncounter.pdfPrint.dob") + " " + (String) demoDtl.get("demoDOB") + "\n"; age = propResource.getString("oscarEncounter.pdfPrint.age") + " " + (String) demoDtl.get("demoAge") + "\n"; mrp = propResource.getString("oscarEncounter.pdfPrint.mrp") + " " + (String) demoDtl.get("mrp") + "\n"; } else { //set up document title and header ResourceBundle propResource = ResourceBundle.getBundle("oscarResources"); title = propResource.getString("oscarEncounter.pdfPrint.title") + " " + (String) request.getAttribute("demoName") + "\n"; gender = propResource.getString("oscarEncounter.pdfPrint.gender") + " " + (String) request.getAttribute("demoSex") + "\n"; dob = propResource.getString("oscarEncounter.pdfPrint.dob") + " " + (String) request.getAttribute("demoDOB") + "\n"; age = propResource.getString("oscarEncounter.pdfPrint.age") + " " + (String) request.getAttribute("demoAge") + "\n"; mrp = propResource.getString("oscarEncounter.pdfPrint.mrp") + " " + (String) request.getAttribute("mrp") + "\n"; } String[] info = new String[] { title, gender, dob, age, mrp }; ClinicData clinicData = new ClinicData(); clinicData.refreshClinicData(); String[] clinic = new String[] { clinicData.getClinicName(), clinicData.getClinicAddress(), clinicData.getClinicCity() + ", " + clinicData.getClinicProvince(), clinicData.getClinicPostal(), clinicData.getClinicPhone(), "Fax: " + clinicData.getClinicFax() }; //Header will be printed at top of every page beginning with p2 Phrase headerPhrase = new Phrase(LEADING, title, font); HeaderFooter header = new HeaderFooter(headerPhrase, false); header.setAlignment(HeaderFooter.ALIGN_CENTER); document.setHeader(header); //Write title with top and bottom borders on p1 cb = writer.getDirectContent(); cb.setColorStroke(new Color(0, 0, 0)); cb.setLineWidth(0.5f); cb.moveTo(document.left(), document.top()); cb.lineTo(document.right(), document.top()); cb.stroke(); //cb.setFontAndSize(bf, FONTSIZE); upperYcoord = document.top() - (font.getCalculatedLeading(LINESPACING) * 2f); ColumnText ct = new ColumnText(cb); Paragraph p = new Paragraph(); p.setAlignment(Paragraph.ALIGN_LEFT); Phrase phrase = new Phrase(); Phrase dummy = new Phrase(); for (int idx = 0; idx < clinic.length; ++idx) { phrase.add(clinic[idx] + "\n"); dummy.add("\n"); upperYcoord -= phrase.getLeading(); } dummy.add("\n"); ct.setSimpleColumn(document.left(), upperYcoord, document.right() / 2f, document.top()); ct.addElement(phrase); ct.go(); p.add(dummy); document.add(p); //add patient info phrase = new Phrase(); p = new Paragraph(); p.setAlignment(Paragraph.ALIGN_RIGHT); for (int idx = 0; idx < info.length; ++idx) { phrase.add(info[idx]); } ct.setSimpleColumn(document.right() / 2f, upperYcoord, document.right(), document.top()); p.add(phrase); ct.addElement(p); ct.go(); cb.moveTo(document.left(), upperYcoord); cb.lineTo(document.right(), upperYcoord); cb.stroke(); upperYcoord -= phrase.getLeading(); if (Boolean.parseBoolean(OscarProperties.getInstance().getProperty("ICFHT_CONVERT_TO_PDF", "false"))) { printPersonalInfo(); } }
From source file:org.sakaiproject.evaluation.tool.reporting.EvalPDFReportBuilder.java
License:Educational Community License
public void addFooter(String text) { HeaderFooter footer = new HeaderFooter((new Phrase(text + " - Pag. ", paragraphFont)), true); ;/*from w ww . j a va 2 s . co m*/ footer.setAlignment(HeaderFooter.ALIGN_RIGHT); footer.disableBorderSide(HeaderFooter.BOTTOM); document.setFooter(footer); }
From source file:org.schreibubi.JCombinations.ui.GridChartPanel.java
License:Open Source License
/** * Create PDF/* w w w . ja v a2s . c o m*/ * * @param name * Filename * @param selection * Selected Nodes * @param dm * DataModel * @param pl * ProgressListener */ @SuppressWarnings("unchecked") public static void generatePDF(File name, DataModel dm, ArrayList<TreePath> selection, ProgressListener pl) { com.lowagie.text.Document document = new Document(PageSize.A4.rotate(), 50, 50, 50, 50); try { ArrayList<ExtendedJFreeChart> charts = dm.getCharts(selection); if (charts.size() > 0) { PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(name)); writer.setViewerPreferences(PdfWriter.PageModeUseOutlines); document.addAuthor("Jrg Werner"); document.addSubject("Created by JCombinations"); document.addKeywords("JCombinations"); document.addCreator("JCombinations using iText"); // we define a header and a footer HeaderFooter header = new HeaderFooter(new Phrase("JCombinations by Jrg Werner"), false); HeaderFooter footer = new HeaderFooter(new Phrase("Page "), new Phrase(".")); footer.setAlignment(Element.ALIGN_CENTER); document.setHeader(header); document.setFooter(footer); document.open(); DefaultFontMapper mapper = new DefaultFontMapper(); FontFactory.registerDirectories(); mapper.insertDirectory("c:\\WINNT\\fonts"); PdfContentByte cb = writer.getDirectContent(); pl.progressStarted(new ProgressEvent(GridChartPanel.class, 0, charts.size())); for (int i = 0; i < charts.size(); i++) { ExtendedJFreeChart chart = charts.get(i); PdfTemplate tp = cb.createTemplate(document.right(EXTRA_MARGIN) - document.left(EXTRA_MARGIN), document.top(EXTRA_MARGIN) - document.bottom(EXTRA_MARGIN)); Graphics2D g2d = tp.createGraphics(document.right(EXTRA_MARGIN) - document.left(EXTRA_MARGIN), document.top(EXTRA_MARGIN) - document.bottom(EXTRA_MARGIN), mapper); Rectangle2D r2d = new Rectangle2D.Double(0, 0, document.right(EXTRA_MARGIN) - document.left(EXTRA_MARGIN), document.top(EXTRA_MARGIN) - document.bottom(EXTRA_MARGIN)); chart.draw(g2d, r2d); g2d.dispose(); cb.addTemplate(tp, document.left(EXTRA_MARGIN), document.bottom(EXTRA_MARGIN)); PdfDestination destination = new PdfDestination(PdfDestination.FIT); TreePath treePath = chart.getTreePath(); PdfOutline po = cb.getRootOutline(); for (int j = 0; j < treePath.getPathCount(); j++) { ArrayList<PdfOutline> lpo = po.getKids(); PdfOutline cpo = null; for (PdfOutline outline : lpo) if (outline.getTitle().compareTo(treePath.getPathComponent(j).toString()) == 0) cpo = outline; if (cpo == null) cpo = new PdfOutline(po, destination, treePath.getPathComponent(j).toString()); po = cpo; } document.newPage(); pl.progressIncremented(new ProgressEvent(GridChartPanel.class, i)); } document.close(); pl.progressEnded(new ProgressEvent(GridChartPanel.class)); } } catch (DocumentException de) { System.err.println(de.getMessage()); } catch (IOException ioe) { System.err.println(ioe.getMessage()); } }
From source file:org.silverpeas.components.almanach.control.AlmanachPdfGenerator.java
License:Open Source License
static public void buildPdf(String name, AlmanachSessionController almanach, String mode) throws AlmanachRuntimeException { try {/* w w w.j a v a 2 s .com*/ String fileName = FileRepositoryManager.getTemporaryPath(almanach.getSpaceId(), almanach.getComponentId()) + name; Document document = new Document(PageSize.A4, 50, 50, 50, 50); // we add some meta information to the document document.addAuthor(almanach.getSettings().getString("author", "")); document.addSubject(almanach.getSettings().getString("subject", "")); document.addCreationDate(); PdfWriter.getInstance(document, new FileOutputStream(fileName)); document.open(); try { Calendar currentDay = Calendar.getInstance(); currentDay.setTime(almanach.getCurrentDay()); String sHeader = almanach.getString("events"); if (mode.equals(PDF_MONTH_ALLDAYS) || mode.equals(PDF_MONTH_EVENTSONLY)) { sHeader += " " + almanach.getString("GML.mois" + currentDay.get(Calendar.MONTH)); } sHeader += " " + currentDay.get(Calendar.YEAR); HeaderFooter header = new HeaderFooter(new Phrase(sHeader), false); HeaderFooter footer = new HeaderFooter(new Phrase("Page "), true); footer.setAlignment(Element.ALIGN_CENTER); document.setHeader(header); document.setFooter(footer); createFirstPage(almanach, document); document.newPage(); Font titleFont = new Font(Font.HELVETICA, 24, Font.NORMAL, new Color(255, 255, 255)); Paragraph cTitle = new Paragraph(almanach.getString("Almanach") + " " + almanach.getString("GML.mois" + currentDay.get(Calendar.MONTH)) + " " + currentDay.get(Calendar.YEAR), titleFont); Chapter chapter = new Chapter(cTitle, 1); // Collection<EventDetail> events = // almanach.getListRecurrentEvent(mode.equals(PDF_YEAR_EVENTSONLY)); AlmanachCalendarView almanachView; if (PDF_YEAR_EVENTSONLY.equals(mode)) { almanachView = almanach.getYearlyAlmanachCalendarView(); } else { almanachView = almanach.getMonthlyAlmanachCalendarView(); } List<DisplayableEventOccurrence> occurrences = almanachView.getEvents(); generateAlmanach(chapter, almanach, occurrences, mode); document.add(chapter); } catch (Exception ex) { throw new AlmanachRuntimeException("PdfGenerator.generate", AlmanachRuntimeException.WARNING, "AlmanachRuntimeException.EX_PROBLEM_TO_GENERATE_PDF", ex); } document.close(); } catch (Exception e) { throw new AlmanachRuntimeException("PdfGenerator.generate", AlmanachRuntimeException.WARNING, "AlmanachRuntimeException.EX_PROBLEM_TO_GENERATE_PDF", e); } }
From source file:org.tellervo.desktop.print.ProSheet.java
License:Open Source License
private void generateProSheet(OutputStream output) { Paragraph spacingPara = new Paragraph(); spacingPara.setSpacingBefore(10);/*from ww w .j a v a2 s . com*/ spacingPara.add(new Chunk(" ", bodyFont)); try { PdfWriter writer = PdfWriter.getInstance(document, output); document.setPageSize(PageSize.LETTER); // Set basic metadata document.addAuthor("Peter Brewer"); document.addSubject("Corina Provenience Sheet for " + o.getTitle()); HeaderFooter footer = new HeaderFooter(new Phrase(""), new Phrase("")); footer.setAlignment(Element.ALIGN_RIGHT); footer.setBorder(0); document.setFooter(footer); HeaderFooter header = new HeaderFooter(new Phrase(o.getLabCode() + " - " + o.getTitle(), bodyFont), false); header.setAlignment(Element.ALIGN_RIGHT); header.setBorder(0); document.setHeader(header); document.open(); cb = writer.getDirectContent(); // Title Left ColumnText ct = new ColumnText(cb); ct.setSimpleColumn(document.left(), document.top() - 193, document.right(), document.top() - 20, 20, Element.ALIGN_LEFT); ct.addText(getTitlePDF()); ct.go(); // Timestamp ColumnText ct3 = new ColumnText(cb); ct3.setSimpleColumn(document.left(), document.top() - 223, 283, document.top() - 60, 20, Element.ALIGN_LEFT); ct3.setLeading(0, 1.2f); ct3.addText(getTimestampPDF()); ct3.go(); // Pad text document.add(spacingPara); document.add(getObjectDescription()); document.add(getObjectComments()); document.add(spacingPara); getElementTable(); } catch (DocumentException de) { System.err.println(de.getMessage()); } // Close the document document.close(); }
From source file:oscar.oscarPrevention.pageUtil.PreventionPrintPdf.java
License:Open Source License
public void printPdf(String[] headerIds, HttpServletRequest request, OutputStream outputStream) throws IOException, DocumentException { //make sure we have data to print //String[] headerIds = request.getParameterValues("printHP"); if (headerIds == null) throw new DocumentException(); //Create the document we are going to write to document = new Document(); PdfWriter writer = PdfWriter.getInstance(document, outputStream); document.setPageSize(PageSize.LETTER); document.open();/* w w w . jav a 2 s . com*/ //Create the font we are going to print to BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED); Font font = new Font(bf, FONTSIZE, Font.NORMAL); float leading = font.getCalculatedLeading(LINESPACING); //set up document title and header String title = "Preventions for " + request.getParameter("nameAge"); String hin = "HIN: " + request.getParameter("hin"); String mrp = request.getParameter("mrp"); if (mrp != null) { Properties prop = (Properties) request.getSession().getAttribute("providerBean"); mrp = "MRP: " + prop.getProperty(mrp, "unknown"); } ClinicData clinicData = new ClinicData(); clinicData.refreshClinicData(); String[] clinic = new String[] { clinicData.getClinicName(), clinicData.getClinicAddress(), clinicData.getClinicCity() + ", " + clinicData.getClinicProvince(), clinicData.getClinicPostal(), clinicData.getClinicPhone(), title, hin, mrp }; //Header will be printed at top of every page beginning with p2 Phrase headerPhrase = new Phrase(LEADING, title, font); HeaderFooter header = new HeaderFooter(headerPhrase, false); header.setAlignment(HeaderFooter.ALIGN_CENTER); document.setHeader(header); //Write title with top and bottom borders on p1 cb = writer.getDirectContent(); cb.setColorStroke(new Color(0, 0, 0)); cb.setLineWidth(0.5f); cb.moveTo(document.left(), document.top()); cb.lineTo(document.right(), document.top()); cb.stroke(); cb.setFontAndSize(bf, FONTSIZE); upperYcoord = document.top() - (font.getCalculatedLeading(LINESPACING) * 2f); cb.beginText(); for (int idx = 0; idx < clinic.length; ++idx) { cb.showTextAligned(PdfContentByte.ALIGN_CENTER, clinic[idx], document.right() / 2f, upperYcoord, 0f); upperYcoord -= font.getCalculatedLeading(LINESPACING); } cb.endText(); cb.moveTo(document.left(), upperYcoord); cb.lineTo(document.right(), upperYcoord); cb.stroke(); //get top y-coord for starting to print columns upperYcoord = cb.getYTLM() - font.getCalculatedLeading(LINESPACING * 2f); int subIdx; String preventionHeader, procedureAge, procedureDate; //1 - obtain number of lines of incoming prevention data numLines = 0; for (int idx = 0; idx < headerIds.length; ++idx) { ++numLines; subIdx = 0; while (request.getParameter("preventProcedureAge" + headerIds[idx] + "-" + subIdx) != null) { ++subIdx; numLines += 3; } numLines += 2; } //2 - calculate max num of lines a page can hold and number of pages of data we have pageHeight = upperYcoord - document.bottom(); maxLines = (int) Math.floor(pageHeight / (font.getCalculatedLeading(LINESPACING) + 4d)); numPages = (int) Math.ceil(numLines / ((double) maxLines * NUMCOLS)); //3 - Start the column ct = new ColumnText(cb); ct.setSimpleColumn(document.left(), document.bottom(), document.right() / 2f, upperYcoord); linesToBeWritten = linesWritten = 0; boolean pageBreak = false; curPage = 1; totalLinesWritten = 0; //add promotext to current page addPromoText(); //if we have > 1 element but less than a page of data, shrink maxLines so we can try to balance text in columns if (headerIds.length > 1) { if (curPage == numPages) { maxLines = numLines / NUMCOLS; } } //now we can start to print the prevention data for (int idx = 0; idx < headerIds.length; ++idx) { linesToBeWritten = 4; //minimum lines for header and one prevention item pageBreak = checkColumnFill(ct, "", font, pageBreak); //if necessary break before we print prevention header preventionHeader = request.getParameter("preventionHeader" + headerIds[idx]); Phrase procHeader = new Phrase(LEADING, "Prevention " + preventionHeader + "\n", font); ct.addText(procHeader); subIdx = 0; while ((procedureAge = request .getParameter("preventProcedureAge" + headerIds[idx] + "-" + subIdx)) != null) { procedureDate = request.getParameter("preventProcedureDate" + headerIds[idx] + "-" + subIdx); linesToBeWritten = 3; pageBreak = checkColumnFill(ct, preventionHeader, font, pageBreak); Phrase procedure = new Phrase(LEADING, " " + procedureAge + "\n", font); procedure.add(" " + procedureDate + "\n\n"); ct.addText(procedure); ct.go(); linesWritten += ct.getLinesWritten(); totalLinesWritten += ct.getLinesWritten(); ++subIdx; } } ColumnText.showTextAligned(cb, Phrase.ALIGN_CENTER, new Phrase("-" + curPage + "-"), document.right() / 2f, document.bottom() - (document.bottomMargin() / 2f), 0f); document.close(); }