List of usage examples for com.lowagie.text Document close
boolean close
To view the source code for com.lowagie.text Document close.
Click Source Link
From source file:com.senacor.wbs.web.project.ProjectListPanel.java
License:Apache License
public ProjectListPanel(final String id, final List<Project> projects) { super(id);//from w ww.ja v a 2s . c o m this.locale = getLocale(); SortableListDataProvider<Project> projectProvider = new SortableListDataProvider<Project>(projects) { @Override protected Locale getLocale() { return ProjectListPanel.this.getLocale(); } public IModel model(final Object object) { return new CompoundPropertyModel(object); } }; projectProvider.setSort("name", true); dataView = new DataView("projects", projectProvider, 4) { @Override protected void populateItem(final Item item) { Project project = (Project) item.getModelObject(); PageParameters pageParameters = new PageParameters(); pageParameters.put("projectId", project.getId()); item.add(new BookmarkablePageLink("tasks", ProjectDetailsPage.class, pageParameters) .add(new Label("id"))); item.add(new Label("kuerzel")); item.add(new Label("titel", project.getName())); item.add(new Label("budget")); item.add(new Label("costPerHour")); item.add(new Label("start")); item.add(new Label("ende")); item.add(new Label("state")); // Alternieren der Farbe zwischen geraden und // ungeraden Zeilen item.add(new AttributeModifier("class", true, new AbstractReadOnlyModel() { @Override public Object getObject() { return (item.getIndex() % 2 == 1) ? "even" : "odd"; } })); } }; add(dataView); Form localeForm = new Form("localeForm"); ImageButton deButton = new ImageButton("langde", new ResourceReference(BaseWBSPage.class, "de.png")) { @Override public void onSubmit() { ProjectListPanel.this.locale = Locale.GERMANY; } }; localeForm.add(deButton); ImageButton usButton = new ImageButton("langus", new ResourceReference(BaseWBSPage.class, "us.png")) { @Override public void onSubmit() { ProjectListPanel.this.locale = Locale.US; } }; localeForm.add(usButton); add(localeForm); final IResourceStream pdfResourceStream = new AbstractResourceStreamWriter() { public void write(final OutputStream output) { Document document = new Document(); try { PdfWriter.getInstance(document, output); document.open(); // document.add(new // Paragraph("WBS-Projektliste")); // document.add(new Paragraph("")); PdfPTable table = new PdfPTable(new float[] { 1f, 1f, 2f, 1f }); PdfPCell cell = new PdfPCell(new Paragraph("WBS-Projektliste")); cell.setColspan(4); cell.setGrayFill(0.8f); table.addCell(cell); table.addCell("ID"); table.addCell("Krzel"); table.addCell("Titel"); table.addCell("Budget in PT"); for (Project project : projects) { table.addCell("" + project.getId()); table.addCell(project.getKuerzel()); table.addCell(project.getName()); table.addCell("" + project.getBudget()); } document.add(table); document.close(); } catch (DocumentException e) { throw new RuntimeException(e); } } public String getContentType() { return "application/pdf"; } }; WebResource projectsResource = new WebResource() { { setCacheable(false); } @Override public IResourceStream getResourceStream() { return pdfResourceStream; } @Override protected void setHeaders(final WebResponse response) { super.setHeaders(response); // response.setAttachmentHeader("projekte.pdf"); } }; WebResource projectsResourceDL = new WebResource() { { setCacheable(false); } @Override public IResourceStream getResourceStream() { return pdfResourceStream; } @Override protected void setHeaders(final WebResponse response) { super.setHeaders(response); response.setAttachmentHeader("projekte.pdf"); } }; ResourceLink pdfDownload = new ResourceLink("pdfDownload", projectsResourceDL); ResourceLink pdfPopup = new ResourceLink("pdfPopup", projectsResource); PopupSettings popupSettings = new PopupSettings(PopupSettings.STATUS_BAR); popupSettings.setWidth(500); popupSettings.setHeight(700); pdfPopup.setPopupSettings(popupSettings); Link pdfReqTarget = new Link("pdfReqTarget") { @Override public void onClick() { RequestCycle.get() .setRequestTarget(new ResourceStreamRequestTarget(pdfResourceStream, "projekte.pdf")); } }; add(pdfReqTarget); add(pdfDownload); add(pdfPopup); add(new OrderByBorder("orderByKuerzel", "kuerzel", projectProvider)); add(new OrderByBorder("orderByName", "name", projectProvider)); add(new OrderByBorder("orderByBudget", "budget", projectProvider)); add(new OrderByBorder("orderByCostPerHour", "costPerHour", projectProvider)); add(new OrderByBorder("orderByStart", "start", projectProvider)); add(new OrderByBorder("orderByEnde", "ende", projectProvider)); add(new OrderByBorder("orderByState", "state", projectProvider)); add(new PagingNavigator("projectsNavigator", dataView)); }
From source file:com.servoy.extensions.plugins.pdf_output.PDFProvider.java
License:Open Source License
/** * Combine multiple protected PDF docs into one. * Note: this function may fail when creating large PDF files due to lack of available heap memory. To compensate, please configure the application server with more heap memory via -Xmx parameter. * * @sample//from w ww . j a v a 2s.c o m * pdf_blob_column = combineProtectedPDFDocuments(new Array(pdf_blob1,pdf_blob2,pdf_blob3), new Array(pdf_blob1_pass,pdf_blob2_pass,pdf_blob3_pass)); * * @param pdf_docs_bytearrays the array of documents to combine * @param pdf_docs_passwords an array of passwords to use */ public byte[] js_combineProtectedPDFDocuments(Object[] pdf_docs_bytearrays, Object[] pdf_docs_passwords) { if (pdf_docs_bytearrays == null || pdf_docs_bytearrays.length == 0) return null; ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { int pageOffset = 0; List master = new ArrayList(); Document document = null; PdfCopy writer = null; for (int f = 0; f < pdf_docs_bytearrays.length; f++) { if (!(pdf_docs_bytearrays[f] instanceof byte[])) continue; byte[] pdf_file = (byte[]) pdf_docs_bytearrays[f]; // we create a reader for a certain document byte[] password = null; if (pdf_docs_passwords != null && pdf_docs_passwords.length > f && pdf_docs_passwords[f] != null) { if (pdf_docs_passwords[f] instanceof String) password = pdf_docs_passwords[f].toString().getBytes(); } PdfReader reader = new PdfReader(pdf_file, password); 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 (writer == null) { // 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); } PRAcroForm form = reader.getAcroForm(); if (form != null) writer.copyAcroForm(reader); } if (writer != null && document != null) { if (master.size() > 0) writer.setOutlines(master); // step 5: we close the document document.close(); } return baos.toByteArray(); } catch (Throwable e) { Debug.error(e); throw new RuntimeException("Error combinding pdf documents: " + e.getMessage(), e); //$NON-NLS-1$ } }
From source file:com.shmsoft.dmass.print.Html2Pdf.java
License:Apache License
/** * Bad rendering, perhaps used only for Windows *///w w w . j av a2s. co m @SuppressWarnings({ "rawtypes", "unchecked" }) private static void convertHtml2Pdf(Reader htmlReader, String outputFile) throws Exception { Document pdfDocument = new Document(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); PdfWriter.getInstance(pdfDocument, baos); pdfDocument.open(); StyleSheet styles = new StyleSheet(); styles.loadTagStyle("body", "font", "Times New Roman"); ImageProvider imageProvider = new ImageProvider() { @Override public Image getImage(String src, HashMap arg1, ChainedProperties arg2, DocListener arg3) { try { Image image = Image.getInstance(IOUtils.toByteArray( getClass().getClassLoader().getResourceAsStream(ParameterProcessing.NO_IMAGE_FILE))); return image; } catch (Exception e) { System.out.println("Problem with html->pdf imaging, image provider fault"); } return null; } }; HashMap interfaceProps = new HashMap(); interfaceProps.put("img_provider", imageProvider); ArrayList arrayElementList = HTMLWorker.parseToList(htmlReader, styles, interfaceProps); for (int i = 0; i < arrayElementList.size(); ++i) { Element e = (Element) arrayElementList.get(i); pdfDocument.add(e); } pdfDocument.close(); byte[] bs = baos.toByteArray(); File pdfFile = new File(outputFile); FileOutputStream out = new FileOutputStream(pdfFile); out.write(bs); out.close(); }
From source file:com.silverpeas.importExport.control.ImportExport.java
License:Open Source License
/** * @param userDetail/*from w w w . j a va2 s .c o m*/ * @param itemsToExport * @return * @throws ImportExportException */ public ExportPDFReport processExportPDF(UserDetail userDetail, List<WAAttributeValuePair> itemsToExport, NodePK rootPK) throws ImportExportException { ExportPDFReport report = new ExportPDFReport(); report.setDateDebut(new Date()); PublicationsTypeManager pubTypeManager = new PublicationsTypeManager(); String fileExportName = generateExportDirName(userDetail, "fusion"); String tempDir = FileRepositoryManager.getTemporaryPath(); File fileExportDir = new File(tempDir + fileExportName); if (!fileExportDir.exists()) { try { FileFolderManager.createFolder(fileExportDir); } catch (UtilException ex) { throw new ImportExportException("ImportExport", "importExport.EX_CANT_CREATE_FOLDER", ex); } } File pdfFileName = new File(tempDir + fileExportName + ".pdf"); try { // cration des rpertoires avec le nom des thmes et des publications List<AttachmentDetail> pdfList = pubTypeManager.processPDFExport(report, userDetail, itemsToExport, fileExportDir.getPath(), true, rootPK); try { int pageOffset = 0; List master = new ArrayList(); Document document = null; PdfCopy writer = null; if (!pdfList.isEmpty()) { boolean firstPage = true; for (AttachmentDetail attDetail : pdfList) { PdfReader reader = null; try { reader = new PdfReader( fileExportDir.getPath() + File.separatorChar + attDetail.getLogicalName()); } catch (IOException ioe) { // Attached file is not physically present on disk, ignore it and log event SilverTrace.error("importExport", "PublicationTypeManager.processExportPDF", "CANT_FIND_PDF_FILE", "PDF file '" + attDetail.getLogicalName() + "' is not present on disk", ioe); } if (reader != null) { reader.consolidateNamedDestinations(); int nbPages = reader.getNumberOfPages(); List bookmarks = SimpleBookmark.getBookmark(reader); if (bookmarks != null) { if (pageOffset != 0) { SimpleBookmark.shiftPageNumbers(bookmarks, pageOffset, null); } master.addAll(bookmarks); } pageOffset += nbPages; if (firstPage) { document = new Document(reader.getPageSizeWithRotation(1)); writer = new PdfCopy(document, new FileOutputStream(pdfFileName)); document.open(); firstPage = false; } for (int i = 1; i <= nbPages; i++) { try { PdfImportedPage page = writer.getImportedPage(reader, i); writer.addPage(page); } catch (Exception e) { // Can't import PDF file, ignore it and log event SilverTrace.error("importExport", "PublicationTypeManager.processExportPDF", "CANT_MERGE_PDF_FILE", "PDF file is " + attDetail.getLogicalName(), e); } } PRAcroForm form = reader.getAcroForm(); if (form != null) { writer.copyAcroForm(reader); } } } if (!master.isEmpty()) { writer.setOutlines(master); } writer.flush(); document.close(); } else { return null; } } catch (BadPdfFormatException e) { // Erreur lors de la copie throw new ImportExportException("ImportExport", "root.EX_CANT_WRITE_FILE", e); } catch (DocumentException e) { // Impossible de copier le document throw new ImportExportException("ImportExport", "root.EX_CANT_WRITE_FILE", e); } } catch (IOException e) { // Pb avec le rpertoire de destination throw new ImportExportException("ImportExport", "root.EX_CANT_WRITE_FILE", e); } report.setPdfFileName(pdfFileName.getName()); report.setPdfFileSize(pdfFileName.length()); report.setPdfFilePath(FileServerUtils.getUrlToTempDir(pdfFileName.getName())); report.setDateFin(new Date()); return report; }
From source file:com.slamd.report.PDFReportGenerator.java
License:Open Source License
/** * Generates the report and sends it to the user over the provided servlet * response./*from w ww. j a v a2 s . c om*/ * * @param requestInfo State information about the request being processed. */ public void generateReport(RequestInfo requestInfo) { // Determine exactly what to include in the report. We will want to strip // out any individual jobs that are part of an optimizing job that is also // to be included in the report. reportOptimizingJobs = new OptimizingJob[optimizingJobList.size()]; optimizingJobList.toArray(reportOptimizingJobs); ArrayList<Job> tmpList = new ArrayList<Job>(jobList.size()); for (int i = 0; i < jobList.size(); i++) { Job job = jobList.get(i); String optimizingJobID = job.getOptimizingJobID(); if ((optimizingJobID != null) && (optimizingJobID.length() > 0)) { boolean matchFound = false; for (int j = 0; j < reportOptimizingJobs.length; j++) { if (optimizingJobID.equalsIgnoreCase(reportOptimizingJobs[j].getOptimizingJobID())) { matchFound = true; break; } } if (matchFound) { continue; } } tmpList.add(job); } reportJobs = new Job[tmpList.size()]; tmpList.toArray(reportJobs); // Prepare to actually generate the report and send it to the user. HttpServletResponse response = requestInfo.getResponse(); if (viewInBrowser) { response.setContentType("application/pdf"); } else { response.setContentType("application/x-slamd-report-pdf"); } response.addHeader("Content-Disposition", "filename=\"slamd_data_report.pdf\""); try { // Create the PDF document and associate it with the response to send to // the client. Document document = new Document(PageSize.LETTER); PdfWriter writer = PdfWriter.getInstance(document, response.getOutputStream()); document.addTitle("SLAMD Generated Report"); document.addCreationDate(); document.addCreator("SLAMD Distributed Load Generator"); writer.setPageEvent(this); // Open the document and add the table of contents. document.open(); boolean needNewPage = writeContents(document); // Write the regular job information. for (int i = 0; i < reportJobs.length; i++) { if (needNewPage) { document.newPage(); } writeJob(document, reportJobs[i]); needNewPage = true; } // Write the optimizing job information. for (int i = 0; i < reportOptimizingJobs.length; i++) { if (needNewPage) { document.newPage(); } writeOptimizingJob(document, reportOptimizingJobs[i]); needNewPage = true; } // Close the document. document.close(); } catch (Exception e) { // Not much we can do about this. e.printStackTrace(); return; } }
From source file:com.songbook.pc.exporter.PdfExporter.java
License:Open Source License
private PageStats generatePDF(List<SongNode> songList, File outputFile) throws IOException, DocumentException { logger.info("Starting export to PDF file {}.", outputFile.getAbsolutePath()); // Initialize Writer Document document = new Document(); PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(outputFile)); PageStats pageStats = new PageStats(); writer.setPageEvent(pageStats);/*from w w w . j a v a2s .c o m*/ // Initialize document document.setPageSize(PageSize.A4); document.setMargins(35 * POINTS_PER_MM, 10 * POINTS_PER_MM, 7 * POINTS_PER_MM, 7 * POINTS_PER_MM); document.setMarginMirroring(true); document.open(); // Add QR codes Element qrCodeSection = buildQrCodeSection(); document.add(qrCodeSection); // Line separator document.add(verseSpacing); document.add(new LineSeparator()); document.add(verseSpacing); // Build TOC Chunk tocTitle = new Chunk("SONG BOOK - TABLE OF CONTENTS", songTitleFont); tocTitle.setLocalDestination("TOC"); document.add(new Paragraph(tocTitle)); for (int i = 0; i < songList.size(); i++) { SongNode songNode = songList.get(i); int chapterNumber = i + 1; Chunk tocEntry = new Chunk(chapterNumber + ". " + songNode.getTitle(), textFont); tocEntry.setLocalGoto("SONG::" + chapterNumber); document.add(new Paragraph(tocEntry)); } document.newPage(); pageStats.setSectionLength("TOC", pageStats.getCurrentPage() - 1); // Build document for (int i = 0; i < songList.size(); i++) { // Get song node SongNode songNode = songList.get(i); // Mark song start int songStartPage = pageStats.getCurrentPage(); // Write song document.add(buildChapter(songNode, i + 1)); document.newPage(); // Record song length pageStats.setSectionLength(songNode.getTitle(), pageStats.getCurrentPage() - songStartPage); } // Close document document.close(); logger.info("COMPLETED export to PDF file {}.", outputFile.getAbsolutePath()); return pageStats; }
From source file:com.stratelia.webactiv.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 av a 2 s. c om*/ SilverTrace.info("almanach", "AlmanachPdfGenerator.buildPdf()", "root.MSG_GEN_ENTER_METHOD"); 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(); SilverTrace.info("almanach", "AlmanachPdfGenerator.buildPdf()", "root.MSG_GEN_EXIT_METHOD"); } catch (Exception e) { throw new AlmanachRuntimeException("PdfGenerator.generate", AlmanachRuntimeException.WARNING, "AlmanachRuntimeException.EX_PROBLEM_TO_GENERATE_PDF", e); } }
From source file:com.stratelia.webactiv.newsEdito.control.PdfGenerator.java
License:Open Source License
/** * Method declaration//from www . j a v a 2 s.c om * @param name * @param completePubList * @param langue * @throws NewsEditoException * @see */ public static void generatePubList(String name, Collection<CompletePublication> completePubList, String langue) throws NewsEditoException { SilverTrace.info("NewsEdito", "PdfGenerator.generatePubList", "NewsEdito.MSG_ENTRY_METHOD", "Pdf name = " + name); try { CompletePublication first = completePubList.iterator().next(); String fileName = FileRepositoryManager.getTemporaryPath( first.getPublicationDetail().getPK().getSpace(), first.getPublicationDetail().getPK().getComponentName()) + name; ResourceLocator message = new ResourceLocator( "com.stratelia.webactiv.newsEdito.multilang.newsEditoBundle", langue); // creation of the document with a certain size and certain margins Document document = new Document(PageSize.A4, 50, 50, 50, 50); // we add some meta information to the document document.addAuthor("Generateur de PDF Silverpeas"); document.addSubject("Compilation de publications Silverpeas"); document.addCreationDate(); PdfWriter.getInstance(document, new FileOutputStream(fileName)); document.open(); createFirstPage(document, langue); HeaderFooter header = new HeaderFooter(new Phrase(message.getString("publicationCompilation")), false); HeaderFooter footer = new HeaderFooter(new Phrase("Page "), new Phrase(".")); footer.setAlignment(Element.ALIGN_CENTER); document.setHeader(header); document.setFooter(footer); document.newPage(); Font titleFont = new Font(Font.HELVETICA, 24, Font.NORMAL, new Color(255, 255, 255)); Paragraph cTitle = new Paragraph(message.getString("listPublication"), titleFont); Chapter chapter = new Chapter(cTitle, 1); Iterator<CompletePublication> i = completePubList.iterator(); CompletePublication complete = null; while (i.hasNext()) { complete = i.next(); addPublication(chapter, complete); } document.add(chapter); document.close(); } catch (Exception e) { throw new NewsEditoException("PdfGenerator.generatePubList", NewsEditoException.WARNING, "NewsEdito.EX_PROBLEM_TO_GENERATE_PUBLI_LIST", e); } }
From source file:com.stratelia.webactiv.newsEdito.control.PdfGenerator.java
License:Open Source License
/** * Method declaration//from w w w.j a v a2s. c om * @param name * @param archiveDetail * @param publicationBm * @param langue * @throws NewsEditoException * @see */ public static void generateArchive(String name, NodeDetail archiveDetail, PublicationBm publicationBm, String langue) throws NewsEditoException { SilverTrace.info("NewsEdito", "PdfGenerator.generateArchive", "NewsEdito.MSG_ENTRY_METHOD", "Pdf name = " + name); try { String fileName = FileRepositoryManager.getTemporaryPath(archiveDetail.getNodePK().getSpace(), archiveDetail.getNodePK().getComponentName()) + name; // creation of the document with a certain size and certain margins Document document = new Document(PageSize.A4, 50, 50, 50, 50); // we add some meta information to the document document.addAuthor("Generateur de PDF Silverpeas"); document.addSubject("Journal Silverpeas : " + archiveDetail.getName()); document.addCreationDate(); PdfWriter.getInstance(document, new FileOutputStream(fileName)); document.open(); createFirstPage(document, langue); // we define a header and a footer String descriptionArchive = archiveDetail.getDescription(); if (descriptionArchive == null) descriptionArchive = " "; HeaderFooter header = new HeaderFooter(new Phrase(archiveDetail.getName() + " : " + descriptionArchive), false); HeaderFooter footer = new HeaderFooter(new Phrase("Page "), new Phrase(".")); footer.setAlignment(Element.ALIGN_CENTER); document.setHeader(header); document.setFooter(footer); document.newPage(); PdfGenerator.addEditorial(document, archiveDetail, publicationBm, langue); PdfGenerator.addMasterTable(document, archiveDetail, publicationBm); document.close(); } catch (Exception e) { throw new NewsEditoException("PdfGenerator.generateArchive", NewsEditoException.WARNING, "NewsEdito.EX_PROBLEM_TO_GENERATE_ARCHIVE", e); } }
From source file:com.t2.compassionMeditation.ViewSessionsActivity.java
License:Open Source License
/** * Create a PDF file based on the contents of the graph *///from w w w. j a v a2s .c o m void CreatePdf() { // Run the export on a separate thread. new Thread(new Runnable() { @Override public void run() { Document document = new Document(); try { Date calendar = Calendar.getInstance().getTime(); mResultsFileName = "BioZenResults_"; mResultsFileName += (calendar.getYear() + 1900) + "-" + (calendar.getMonth() + 1) + "-" + calendar.getDate() + "_"; mResultsFileName += calendar.getHours() + "-" + calendar.getMinutes() + "-" + calendar.getSeconds() + ".pdf"; PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(android.os.Environment.getExternalStorageDirectory() + java.io.File.separator + mResultsFileName)); document.open(); PdfContentByte contentByte = writer.getDirectContent(); BaseFont baseFont = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED); // Note top of PDF = 900 float chartWidth = 332; float chartHeight = 45; float spaceHeight = chartHeight + 30; int horizontalPos = 180; float verticalPos = 780; // Write document header contentByte.beginText(); contentByte.setFontAndSize(baseFont, 20); contentByte.showTextAligned(PdfContentByte.ALIGN_CENTER, "T2 BioZen Report", 300, 800, 0); contentByte.showTextAligned(PdfContentByte.ALIGN_CENTER, "Generated on: " + calendar.toLocaleString(), 300, 770, 0); contentByte.endText(); contentByte.setLineWidth(1f); verticalPos -= spaceHeight; long startTime = startCal.getTimeInMillis(); long endTime = endCal.getTimeInMillis(); float maxChartValue = 0; float chartYAvg; BioSession tmpSession = sessionItems.get(0); int maxKeys = tmpSession.keyItemNames.length; // Loop through all of the the keys for (int key = 0; key < maxKeys; key++) { //Draw a border rect contentByte.setRGBColorStrokeF(0, 0, 0); contentByte.setLineWidth(1f); contentByte.rectangle(horizontalPos, verticalPos, chartWidth, chartHeight); contentByte.stroke(); // Write band name contentByte.beginText(); contentByte.setFontAndSize(baseFont, 12); BioSession tmpSession1 = sessionItems.get(0); contentByte.showTextAligned(PdfContentByte.ALIGN_RIGHT, tmpSession1.keyItemNames[key], 170, (verticalPos + (chartHeight / 2)) - 5, 0); contentByte.endText(); maxChartValue = 0; // First find the max Y for (BioSession session : sessionItems) { if (session.time >= startTime && session.time <= endTime) { chartYAvg = session.avgFilteredValue[key]; if (chartYAvg > maxChartValue) maxChartValue = chartYAvg; } } float lastY = -1; float xIncrement = 0; if (sessionItems.size() > 0) { xIncrement = chartWidth / sessionItems.size(); } float yIncrement = 0; if (maxChartValue > 0) { yIncrement = chartHeight / maxChartValue; } float highValue = 0; int highTime = 0; float highY = 0; float highX = 0; int lowTime = 0; float lowY = 100; float lowX = chartWidth; float lowValue = maxChartValue; int lCount = 0; String keyName = ""; ArrayList<RegressionItem> ritems = new ArrayList<RegressionItem>(); // Loop through the session points of this key String rawYValues = ""; for (BioSession session : sessionItems) { keyName = session.keyItemNames[key]; if (session.time >= startTime && session.time <= endTime) { chartYAvg = session.avgFilteredValue[key]; rawYValues += chartYAvg + ", "; if (lastY < 0) lastY = (float) chartYAvg; contentByte.setLineWidth(3f); contentByte.setRGBColorStrokeF(255, 0, 0); float graphXFrom = horizontalPos + (lCount * xIncrement); float graphYFrom = verticalPos + (lastY * yIncrement); float graphXTo = (horizontalPos + ((lCount + 1) * xIncrement)); float graphYTo = verticalPos + (chartYAvg * yIncrement); // Log.e(TAG, "[" + graphXFrom + ", " + graphYFrom + "] to [" + graphXTo + ", " + graphYTo + "]"); // Draw the actual graph contentByte.moveTo(graphXFrom, graphYFrom); contentByte.lineTo(graphXTo, graphYTo); contentByte.stroke(); //Add regression Item ritems.add(new RegressionItem(lCount, (chartYAvg * yIncrement))); if (chartYAvg > highValue) { highValue = chartYAvg; highY = graphYTo; highX = graphXTo; highTime = (int) (session.time / 1000); } if (chartYAvg < lowValue) { lowValue = chartYAvg; lowY = graphYTo; lowX = graphXTo; lowTime = (int) (session.time / 1000); } lCount++; lastY = (float) chartYAvg; } // End if (session.time >= startTime && session.time <= endTime ) } // End for (BioSession session : sessionItems) //Draw high low dates if (highY != 0 && lowY != 0) { SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yy"); String hDate = dateFormat.format(new Date((long) highTime * 1000L)); String lDate = dateFormat.format(new Date((long) lowTime * 1000L)); contentByte.beginText(); contentByte.setFontAndSize(baseFont, 8); contentByte.showTextAligned(PdfContentByte.ALIGN_CENTER, hDate, highX, highY, 0); contentByte.showTextAligned(PdfContentByte.ALIGN_CENTER, lDate, lowX, lowY, 0); contentByte.endText(); } //Draw Regression Line RegressionResult regression = calculateRegression(ritems); contentByte.saveState(); contentByte.setRGBColorStrokeF(0, 0, 250); contentByte.setLineDash(3, 3, 0); contentByte.moveTo(horizontalPos, verticalPos + (float) regression.intercept); contentByte.lineTo(horizontalPos + chartWidth, (float) ((verticalPos + regression.intercept) + (float) (regression.slope * (chartWidth / xIncrement)))); contentByte.stroke(); contentByte.restoreState(); contentByte.setRGBColorStrokeF(0, 0, 0); // Log.e(TAG, keyName + ": [" + rawYValues + "]"); // Get ready for the next key (and series of database points ) verticalPos -= spaceHeight; if (verticalPos < 30) { document.newPage(); verticalPos = 780 - spaceHeight; } } // End for (int key = 0; key < maxKeys; key++) //document.add(new Paragraph("You can also write stuff directly tot he document like this!")); } catch (DocumentException de) { System.err.println(de.getMessage()); Log.e(TAG, de.toString()); } catch (IOException ioe) { System.err.println(ioe.getMessage()); Log.e(TAG, ioe.toString()); } catch (Exception e) { System.err.println(e.getMessage()); Log.e(TAG, e.toString()); } // step 5: we close the document document.close(); fileExportCompleteHandler.sendEmptyMessage(EXPORT_SUCCESS); } }).start(); }