List of usage examples for com.lowagie.text.pdf PdfContentByte addTemplate
public void addTemplate(PdfTemplate template, float x, float y)
From source file:org.cyberoam.iview.charts.Chart.java
License:Open Source License
/** * Function to write a given ChartID to pdf file * @param pdfFileName specifies the pdf where chart is written.Please specify full path with the filename. * @param reportGroup id specifies the chart to be generated * @param startdate specifies start date * @param enddate specifies end date/*from w w w . j av a 2 s . c o m*/ * @param limit specifies number of records per record to be written in report */ public static void generatePDFReportGroup(OutputStream out, int reportGroupID, String applianceID, String startDate, String endDate, String limit, int[] deviceIDs, HttpServletRequest request, LinkedHashMap paramMap) throws Exception { float width = 768; float height = 1024; float rec_hieght = 470; Rectangle pagesize = new Rectangle(768, 1024); Document document = new Document(pagesize, 30, 30, 30, 30); JFreeChart chart = null; SqlReader sqlReader = new SqlReader(false); //CyberoamLogger.sysLog.debug("pdf:"+pdfFileName); CyberoamLogger.sysLog.debug("reportGroupID:" + reportGroupID); CyberoamLogger.sysLog.debug("applianceID:" + applianceID); CyberoamLogger.sysLog.debug("startDate:" + startDate); CyberoamLogger.sysLog.debug("endDate:" + endDate); CyberoamLogger.sysLog.debug("limit:" + limit); try { //PdfWriter writer = PdfWriter.getInstance(document, response!=null ? response.getOutputStream():new FileOutputStream(pdfFileName)); PdfWriter writer = PdfWriter.getInstance(document, out); writer.setPageEvent(new Chart()); document.addAuthor("iView"); document.addSubject("iView Report"); document.open(); PdfContentByte contentByte = writer.getDirectContent(); ReportGroupBean reportGroupBean = ReportGroupBean.getRecordbyPrimarykey(reportGroupID); ArrayList reportList = reportGroupBean.getReportIdByReportGroupId(reportGroupID); ReportBean reportBean; ResultSetWrapper rsw = null; String seperator = System.getProperty("file.separator"); //String path=System.getProperty("catalina.home") +seperator+"webapps" +seperator+"ROOT" + seperator + "images" + seperator + "iViewPDF.jpg"; String path = InitServlet.contextPath + seperator + "images" + seperator + "iViewPDF.jpg"; Image iViewImage = Image.getInstance(path); iViewImage.scaleAbsolute(750, 900); //iViewImage.scaleAbsolute(600,820); iViewImage.setAbsolutePosition(10, 10); document.add(iViewImage); document.add(new Paragraph("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n")); /* * Generating Table on the First Page of Report providing summary of Content */ PdfPTable frontPageTable = new PdfPTable(2); PdfPCell dataCell; ReportGroupRelationBean reportGroupRelationBean; String reportName = ""; Color tableHeadBackColor = new Color(150, 174, 190); Color tableContentBackColor = new Color(229, 232, 237); Color tableBorderColor = new Color(229, 232, 237); dataCell = new PdfPCell(new Phrase(new Chunk("Report Profile", FontFactory.getFont(FontFactory.HELVETICA_BOLD, 16, Font.PLAIN, new Color(255, 255, 255))))); dataCell.setBackgroundColor(tableHeadBackColor); dataCell.setBorderColor(tableBorderColor); frontPageTable.addCell(dataCell); /** * Getting dynamic title. */ String title = ""; if (paramMap != null) { title = paramMap.get("title").toString(); paramMap.remove("title"); } if (request != null) title = getFormattedTitle(request, reportGroupBean, true); dataCell = new PdfPCell(new Phrase(new Chunk(title, FontFactory.getFont(FontFactory.HELVETICA_BOLD, 16, Font.PLAIN, new Color(255, 255, 255))))); dataCell.setBackgroundColor(tableHeadBackColor); dataCell.setBorderColor(tableBorderColor); frontPageTable.addCell(dataCell); dataCell = new PdfPCell(new Phrase(new Chunk("Start Date", FontFactory.getFont(FontFactory.HELVETICA_BOLD, 12, Font.PLAIN, new Color(0, 0, 0))))); dataCell.setBackgroundColor(tableContentBackColor); dataCell.setBorderColor(tableBorderColor); frontPageTable.addCell(dataCell); dataCell = new PdfPCell(new Phrase(startDate)); dataCell.setBackgroundColor(tableContentBackColor); dataCell.setBorderColor(tableBorderColor); frontPageTable.addCell(dataCell); dataCell = new PdfPCell(new Phrase(new Chunk("End Date", FontFactory.getFont(FontFactory.HELVETICA_BOLD, 12, Font.PLAIN, new Color(0, 0, 0))))); dataCell.setBackgroundColor(tableContentBackColor); dataCell.setBorderColor(tableBorderColor); frontPageTable.addCell(dataCell); dataCell = new PdfPCell(new Phrase(endDate)); dataCell.setBackgroundColor(tableContentBackColor); dataCell.setBorderColor(tableBorderColor); frontPageTable.addCell(dataCell); dataCell = new PdfPCell(new Phrase(new Chunk("iView Server Time", FontFactory.getFont(FontFactory.HELVETICA_BOLD, 12, Font.PLAIN, new Color(0, 0, 0))))); dataCell.setBackgroundColor(tableContentBackColor); dataCell.setBorderColor(tableBorderColor); frontPageTable.addCell(dataCell); java.util.Date currentDate = new java.util.Date(); dataCell = new PdfPCell(new Phrase(currentDate.toString())); dataCell.setBackgroundColor(tableContentBackColor); dataCell.setBorderColor(tableBorderColor); frontPageTable.addCell(dataCell); dataCell = new PdfPCell(new Phrase(new Chunk("Reports", FontFactory.getFont(FontFactory.HELVETICA_BOLD, 12, Font.PLAIN, new Color(0, 0, 0))))); dataCell.setBackgroundColor(tableContentBackColor); dataCell.setBorderColor(tableBorderColor); frontPageTable.addCell(dataCell); int len = reportList.size(); for (int k = 0; k < len; k++) { reportGroupRelationBean = (ReportGroupRelationBean) reportList.get(k); reportName += " " + (k + 1) + ". " + ReportBean.getRecordbyPrimarykey(reportGroupRelationBean.getReportId()).getTitle() + "\n"; } dataCell = new PdfPCell(new Phrase("\n" + reportName + "\n")); dataCell.setBackgroundColor(tableContentBackColor); dataCell.setBorderColor(tableBorderColor); frontPageTable.addCell(dataCell); dataCell = new PdfPCell(new Phrase(new Chunk("Device Names (IP Address)", FontFactory.getFont(FontFactory.HELVETICA_BOLD, 12, Font.PLAIN, new Color(0, 0, 0))))); dataCell.setBackgroundColor(tableContentBackColor); dataCell.setBorderColor(tableBorderColor); frontPageTable.addCell(dataCell); DeviceBean deviceBean = null; String deviceNameWithIP = ""; if (deviceIDs != null) { for (int i = 0; i < deviceIDs.length; i++) { deviceBean = DeviceBean.getRecordbyPrimarykey(deviceIDs[i]); if (deviceBean != null) { deviceNameWithIP += " " + (i + 1) + ". " + deviceBean.getName() + " (" + deviceBean.getIp() + ")\n"; } } } dataCell = new PdfPCell(new Phrase("\n" + deviceNameWithIP + "\n")); dataCell.setBackgroundColor(tableContentBackColor); dataCell.setBorderColor(tableBorderColor); frontPageTable.addCell(dataCell); /* * Adding Table to PDF */ document.add(frontPageTable); /* * Adding Charts and Table to PDF */ for (int i = 0; i < reportList.size(); i++) { document.newPage(); reportBean = ReportBean .getRecordbyPrimarykey(((ReportGroupRelationBean) reportList.get(i)).getReportId()); String query = null; if (request == null) { query = PrepareQuery.getQuery(reportBean, startDate, endDate, applianceID, null, null, "0", limit, paramMap); } else { PrepareQuery prepareQuery = new PrepareQuery(); query = prepareQuery.getQuery(reportBean, request); } CyberoamLogger.sysLog.debug("PDF:ReportID:" + reportBean.getReportId() + "Query->" + query); try { rsw = sqlReader.getInstanceResultSetWrapper(query); } catch (org.postgresql.util.PSQLException e) { if (query.indexOf("5min_ts_20") > -1) { query = query.substring(0, query.indexOf("5min_ts_20")) + "4hr" + query.substring(query.indexOf("5min_ts_20") + 16, query.length()); CyberoamLogger.appLog.debug("New query : " + query); rsw = sqlReader.getInstanceResultSetWrapper(query); } else { CyberoamLogger.appLog.error("Exeption in AjaxController.java " + e, e); } } catch (Exception e) { CyberoamLogger.appLog.error("Exeption in AjaxController.java " + e, e); rsw.close(); } /* * PDF Rendering work starts here */ for (int j = 0; j < (int) (rec_hieght / 16) + 1; j++) { document.add(new Paragraph("\n")); } // This fix is to resolve the problems associated with reports which don't have graphs. // If there is no graph associated with the report than no need to generate //a chart for it. GraphBean graphBean = GraphBean.getRecordbyPrimarykey(reportBean.getReportId()); //if(graphBean!=null) if (reportBean.getReportFormatId() != 2) { chart = Chart.getChart(reportBean.getReportId(), rsw, null); PdfTemplate pdfTemplate = contentByte.createTemplate(width, height); Graphics2D graphics2D = pdfTemplate.createGraphics(width, height); Rectangle2D rectangle = new Rectangle2D.Double(100, 85, 540, rec_hieght); chart.draw(graphics2D, rectangle); graphics2D.dispose(); contentByte.addTemplate(pdfTemplate, 0, 0); } else { Paragraph p = new Paragraph(reportBean.getTitle() + "\n\n", FontFactory.getFont(FontFactory.HELVETICA, 18, Font.BOLD)); p.setAlignment("center"); document.add(p); } // Retrieving PdfPTable PdfPTable pdfTable = getPdfPTable(reportBean, rsw); rsw.close(); /* * Adding Table to PDF */ document.add(pdfTable); } CyberoamLogger.appLog.info("*************Finishing Chart****************"); } catch (Exception e) { CyberoamLogger.sysLog.debug("Chart.writeChartToPDF.e" + e.getMessage(), e); } finally { sqlReader.close(); } document.close(); }
From source file:org.cyberoam.iview.charts.Chart.java
License:Open Source License
public static void generatePDFReport(OutputStream out, int reportID, String applianceID, String startDate, String endDate, String limit, int[] deviceIDs, HttpServletRequest request, int reportGroupID, LinkedHashMap paramMap) throws Exception { float width = 768; float height = 1024; float rec_hieght = 470; Rectangle pagesize = new Rectangle(768, 1024); Document document = new Document(pagesize, 30, 30, 30, 30); IndexManager indexManager = null;//from w ww . j a v a 2 s.com JFreeChart chart = null; SqlReader sqlReader = new SqlReader(false); CyberoamLogger.sysLog.debug("reportID:" + reportID); CyberoamLogger.sysLog.debug("applianceID:" + applianceID); CyberoamLogger.sysLog.debug("startDate:" + startDate); CyberoamLogger.sysLog.debug("endDate:" + endDate); CyberoamLogger.sysLog.debug("limit:" + limit); try { //PdfWriter writer = PdfWriter.getInstance(document, response!=null ? response.getOutputStream():new FileOutputStream(pdfFileName)); PdfWriter writer = PdfWriter.getInstance(document, out); writer.setPageEvent(new Chart()); document.addAuthor("iView"); document.addSubject("iView Report"); document.open(); PdfContentByte contentByte = writer.getDirectContent(); //ReportGroupBean reportGroupBean=ReportGroupBean.getRecordbyPrimarykey(reportGroupID); //ArrayList reportList=reportGroupBean.getReportIdByReportGroupId(reportGroupID); ReportBean reportBean; ResultSetWrapper rsw = null; String seperator = System.getProperty("file.separator"); // String path=System.getProperty("catalina.home") +seperator+"webapps" +seperator+"ROOT" + seperator + "images" + seperator; String path = InitServlet.contextPath + seperator + "images" + seperator + "iViewPDF.jpg"; /* * Loading Image to add into PDF */ Image iViewImage = Image.getInstance(path); iViewImage.scaleAbsolute(750, 900); //iViewImage.scaleAbsolute(600,820); iViewImage.setAbsolutePosition(10, 10); /*Image headerImage= Image.getInstance(path+ "iViewPDFHeader.jpg"); PdfPTable headerTable = new PdfPTable(2); PdfPCell cell = new PdfPCell(headerImage); headerTable.addCell(cell); HeaderFooter docHeader=null; //document.setHeader(new HeaderFooter(new Phrase(new Chunk())), true); */ document.add(iViewImage); document.add(new Paragraph("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n")); /* * Generating Table on the First Page of Report providing summary of Content */ PdfPTable frontPageTable = new PdfPTable(2); PdfPCell dataCell; String reportName = ""; Color tableHeadBackColor = new Color(150, 174, 190); Color tableContentBackColor = new Color(229, 232, 237); Color tableBorderColor = new Color(229, 232, 237); dataCell = new PdfPCell(new Phrase(new Chunk("Report Profile", FontFactory.getFont(FontFactory.HELVETICA_BOLD, 16, Font.PLAIN, new Color(255, 255, 255))))); dataCell.setBackgroundColor(tableHeadBackColor); dataCell.setBorderColor(tableBorderColor); frontPageTable.addCell(dataCell); if (paramMap != null) { reportName = paramMap.get("title").toString(); paramMap.remove("title"); } if (request != null) { ReportGroupBean reportGroupBean = ReportGroupBean.getRecordbyPrimarykey(reportGroupID); reportName = getFormattedTitle(request, reportGroupBean, true); } dataCell = new PdfPCell(); dataCell.addElement(new Phrase(new Chunk(reportName, FontFactory.getFont(FontFactory.HELVETICA_BOLD, 12, Font.PLAIN, new Color(255, 255, 255))))); //dataCell.addElement(new Phrase(new Chunk(ReportBean.getRecordbyPrimarykey(reportID).getTitle(), FontFactory.getFont(FontFactory.HELVETICA_BOLD, 11, Font.PLAIN, new Color(10,10,10))))); if (request != null) { dataCell.addElement(new Phrase(new Chunk(reportName + " >> ", FontFactory .getFont(FontFactory.HELVETICA_BOLD, 12, Font.PLAIN, new Color(255, 255, 255))))); dataCell.addElement( new Phrase(new Chunk(ReportBean.getRecordbyPrimarykey(reportID).getTitle(), FontFactory .getFont(FontFactory.HELVETICA_BOLD, 12, Font.PLAIN, new Color(255, 255, 255))))); } dataCell.setBackgroundColor(tableHeadBackColor); dataCell.setBorderColor(tableBorderColor); frontPageTable.addCell(dataCell); dataCell = new PdfPCell(new Phrase(new Chunk("Start Date", FontFactory.getFont(FontFactory.HELVETICA_BOLD, 12, Font.PLAIN, new Color(0, 0, 0))))); dataCell.setBackgroundColor(tableContentBackColor); dataCell.setBorderColor(tableBorderColor); frontPageTable.addCell(dataCell); dataCell = new PdfPCell(new Phrase(startDate)); dataCell.setBackgroundColor(tableContentBackColor); dataCell.setBorderColor(tableBorderColor); frontPageTable.addCell(dataCell); dataCell = new PdfPCell(new Phrase(new Chunk("End Date", FontFactory.getFont(FontFactory.HELVETICA_BOLD, 12, Font.PLAIN, new Color(0, 0, 0))))); dataCell.setBackgroundColor(tableContentBackColor); dataCell.setBorderColor(tableBorderColor); frontPageTable.addCell(dataCell); dataCell = new PdfPCell(new Phrase(endDate)); dataCell.setBackgroundColor(tableContentBackColor); dataCell.setBorderColor(tableBorderColor); frontPageTable.addCell(dataCell); dataCell = new PdfPCell(new Phrase(new Chunk("iView Server Time", FontFactory.getFont(FontFactory.HELVETICA_BOLD, 12, Font.PLAIN, new Color(0, 0, 0))))); dataCell.setBackgroundColor(tableContentBackColor); dataCell.setBorderColor(tableBorderColor); frontPageTable.addCell(dataCell); java.util.Date currentDate = new java.util.Date(); dataCell = new PdfPCell(new Phrase(currentDate.toString())); dataCell.setBackgroundColor(tableContentBackColor); dataCell.setBorderColor(tableBorderColor); frontPageTable.addCell(dataCell); dataCell = new PdfPCell(new Phrase(new Chunk("Device Names (IP Address)", FontFactory.getFont(FontFactory.HELVETICA_BOLD, 12, Font.PLAIN, new Color(0, 0, 0))))); dataCell.setBackgroundColor(tableContentBackColor); dataCell.setBorderColor(tableBorderColor); frontPageTable.addCell(dataCell); DeviceBean deviceBean = null; String deviceNameWithIP = ""; if (deviceIDs != null) { for (int i = 0; i < deviceIDs.length; i++) { deviceBean = DeviceBean.getRecordbyPrimarykey(deviceIDs[i]); if (deviceBean != null) { deviceNameWithIP += " " + (i + 1) + ". " + deviceBean.getName() + " (" + deviceBean.getIp() + ")\n"; } } } dataCell = new PdfPCell(new Phrase("\n" + deviceNameWithIP + "\n")); dataCell.setBackgroundColor(tableContentBackColor); dataCell.setBorderColor(tableBorderColor); frontPageTable.addCell(dataCell); /* * Adding Table to PDF */ document.add(frontPageTable); /* * Adding Charts and Table to PDF */ document.newPage(); reportBean = ReportBean.getRecordbyPrimarykey(reportID); String query = null; if (request == null) { query = PrepareQuery.getQuery(reportBean, startDate, endDate, applianceID, null, null, "0", limit, paramMap); } else { PrepareQuery prepareQuery = new PrepareQuery(); query = prepareQuery.getQuery(reportBean, request); } String searchQuery = ""; if (request == null) { searchQuery = null; } else { searchQuery = request.getParameter("searchquery"); } if (searchQuery != null && !"".equalsIgnoreCase(searchQuery)) { query = query.replaceFirst("where", "where " + searchQuery + " and"); } CyberoamLogger.sysLog.debug("PDF:ReportID:" + reportBean.getReportId() + "Query->" + query); try { if (query.indexOf("select") == -1 && query.indexOf("SELECT") == -1) { indexManager = new IndexManager(); rsw = indexManager.getSearch(query); //rsw=indexManager.getResutSetFromArrayList(searchRecord); } else { rsw = sqlReader.getInstanceResultSetWrapper(query); } } catch (org.postgresql.util.PSQLException e) { if (query.indexOf("5min_ts_20") > -1) { query = query.substring(0, query.indexOf("5min_ts_20")) + "4hr" + query.substring(query.indexOf("5min_ts_20") + 16, query.length()); CyberoamLogger.appLog.debug("New query : " + query); rsw = sqlReader.getInstanceResultSetWrapper(query); } else { CyberoamLogger.appLog.error("Exeption in AjaxController.java " + e, e); } } catch (Exception e) { CyberoamLogger.appLog.error("Exeption in AjaxController.java " + e, e); rsw.close(); } /* * PDF Rendering work starts here */ //if(Integer.parseInt(limit)<=10 && query.indexOf("where")>-1){ if (reportBean.getReportFormatId() != 2) { chart = Chart.getChart(reportBean.getReportId(), rsw, null); PdfTemplate pdfTemplate = contentByte.createTemplate(width, height); Graphics2D graphics2D = pdfTemplate.createGraphics(width, height); Rectangle2D rectangle = new Rectangle2D.Double(100, 85, 540, rec_hieght); chart.draw(graphics2D, rectangle); graphics2D.dispose(); contentByte.addTemplate(pdfTemplate, 0, 0); for (int j = 0; j < (int) (rec_hieght / 16) + 1; j++) { document.add(new Paragraph("\n")); } } else document.add(new Paragraph("\n")); // Retrieving PdfPTable PdfPTable pdfTable = getPdfPTable(reportBean, rsw); rsw.close(); document.add(pdfTable); CyberoamLogger.appLog.info("*************Finishing PDF Work****************"); } catch (Exception e) { CyberoamLogger.sysLog.debug("Chart.writeChartToPDF.e" + e.getMessage(), e); } finally { sqlReader.close(); } document.close(); }
From source file:org.egov.ptis.actions.reports.SearchNoticesAction.java
License:Open Source License
/** * @param streamOfPDFFiles/*from w ww. j ava 2 s . co m*/ * @param outputStream * @return */ private byte[] concatPDFs(final List<InputStream> streamOfPDFFiles, final ByteArrayOutputStream outputStream) { if (LOGGER.isDebugEnabled()) LOGGER.debug("Entered into concatPDFs method"); Document document = null; try { final List<InputStream> pdfs = streamOfPDFFiles; final List<PdfReader> readers = new ArrayList<>(); final Iterator<InputStream> iteratorPDFs = pdfs.iterator(); // Create Readers for the pdfs. while (iteratorPDFs.hasNext()) { final InputStream pdf = iteratorPDFs.next(); final PdfReader pdfReader = new PdfReader(pdf); readers.add(pdfReader); if (null == document) document = new Document(pdfReader.getPageSize(1)); } // Create a writer for the outputstream final PdfWriter writer = PdfWriter.getInstance(document, outputStream); document.open(); final PdfContentByte cb = writer.getDirectContent(); // Holds the // PDF // data PdfImportedPage page; int pageOfCurrentReaderPDF = 0; final Iterator<PdfReader> iteratorPDFReader = readers.iterator(); // Loop through the PDF files and add to the output. while (iteratorPDFReader.hasNext()) { final PdfReader pdfReader = iteratorPDFReader.next(); // Create a new page in the target for each source page. while (pageOfCurrentReaderPDF < pdfReader.getNumberOfPages()) { document.newPage(); pageOfCurrentReaderPDF++; page = writer.getImportedPage(pdfReader, pageOfCurrentReaderPDF); cb.addTemplate(page, 0, 0); } pageOfCurrentReaderPDF = 0; } outputStream.flush(); document.close(); outputStream.close(); } catch (final Exception e) { LOGGER.error("Exception in concat PDFs : ", e); } finally { if (document.isOpen()) document.close(); try { if (outputStream != null) outputStream.close(); } catch (final IOException ioe) { LOGGER.error("Exception in concat PDFs : ", ioe); } } if (LOGGER.isDebugEnabled()) LOGGER.debug("Exit from concatPDFs method"); return outputStream.toByteArray(); }
From source file:org.egov.wtms.web.controller.reports.GenerateBillForConsumerCodeController.java
License:Open Source License
private byte[] concatPDFs(final List<InputStream> streamOfPDFFiles, final ByteArrayOutputStream outputStream) { Document document = null;//w ww.jav a2s . c om try { final List<InputStream> pdfs = streamOfPDFFiles; final List<PdfReader> readers = new ArrayList<>(); final Iterator<InputStream> iteratorPDFs = pdfs.iterator(); // Create Readers for the pdfs. while (iteratorPDFs.hasNext()) { final InputStream pdf = iteratorPDFs.next(); final PdfReader pdfReader = new PdfReader(pdf); readers.add(pdfReader); if (null == document) document = new Document(pdfReader.getPageSize(1)); } // Create a writer for the outputstream final PdfWriter writer = PdfWriter.getInstance(document, outputStream); document.open(); final PdfContentByte cb = writer.getDirectContent(); // Holds the // PDF // data PdfImportedPage page; int pageOfCurrentReaderPDF = 0; final Iterator<PdfReader> iteratorPDFReader = readers.iterator(); // Loop through the PDF files and add to the output. while (iteratorPDFReader.hasNext()) { final PdfReader pdfReader = iteratorPDFReader.next(); // Create a new page in the target for each source page. while (pageOfCurrentReaderPDF < pdfReader.getNumberOfPages()) { document.newPage(); pageOfCurrentReaderPDF++; page = writer.getImportedPage(pdfReader, pageOfCurrentReaderPDF); cb.addTemplate(page, 0, 0); } pageOfCurrentReaderPDF = 0; } outputStream.flush(); document.close(); outputStream.close(); } catch (final Exception e) { LOGGER.error("Exception in concat PDFs : ", e); } finally { if (document.isOpen()) document.close(); try { if (outputStream != null) outputStream.close(); } catch (final IOException ioe) { LOGGER.error("Exception in concat PDFs : ", ioe); } } return outputStream.toByteArray(); }
From source file:org.egov.wtms.web.controller.reports.GenerateConnectionBillController.java
License:Open Source License
private byte[] concatPDFs(final List<InputStream> streamOfPDFFiles, final ByteArrayOutputStream outputStream) { Document document = null;//from ww w . j a v a 2 s .c o m try { final List<InputStream> pdfs = streamOfPDFFiles; final List<PdfReader> readers = new ArrayList<PdfReader>(); final Iterator<InputStream> iteratorPDFs = pdfs.iterator(); // Create Readers for the pdfs. while (iteratorPDFs.hasNext()) { final InputStream pdf = iteratorPDFs.next(); final PdfReader pdfReader = new PdfReader(pdf); readers.add(pdfReader); if (null == document) document = new Document(pdfReader.getPageSize(1)); } // Create a writer for the outputstream final PdfWriter writer = PdfWriter.getInstance(document, outputStream); document.open(); final PdfContentByte cb = writer.getDirectContent(); // Holds the // PDF // data PdfImportedPage page; int pageOfCurrentReaderPDF = 0; final Iterator<PdfReader> iteratorPDFReader = readers.iterator(); // Loop through the PDF files and add to the output. while (iteratorPDFReader.hasNext()) { final PdfReader pdfReader = iteratorPDFReader.next(); // Create a new page in the target for each source page. while (pageOfCurrentReaderPDF < pdfReader.getNumberOfPages()) { document.newPage(); pageOfCurrentReaderPDF++; page = writer.getImportedPage(pdfReader, pageOfCurrentReaderPDF); cb.addTemplate(page, 0, 0); } pageOfCurrentReaderPDF = 0; } outputStream.flush(); document.close(); outputStream.close(); } catch (final Exception e) { LOGGER.error("Exception in concat PDFs : ", e); } finally { if (document.isOpen()) document.close(); try { if (outputStream != null) outputStream.close(); } catch (final IOException ioe) { LOGGER.error("Exception in concat PDFs : ", ioe); } } return outputStream.toByteArray(); }
From source file:org.egov.wtms.web.controller.reports.SearchNoticeController.java
License:Open Source License
private byte[] concatPDFs(final List<InputStream> streamOfPDFFiles, final ByteArrayOutputStream outputStream) { Document document = null;/*from w ww . ja v a2 s .c om*/ try { final List<InputStream> pdfs = streamOfPDFFiles; final List<PdfReader> readers = new ArrayList<>(); final Iterator<InputStream> iteratorPDFs = pdfs.iterator(); // Create Readers for the pdfs. while (iteratorPDFs.hasNext()) { final InputStream pdf = iteratorPDFs.next(); final PdfReader pdfReader = new PdfReader(pdf); readers.add(pdfReader); if (null == document) document = new Document(pdfReader.getPageSize(1)); } // Create a writer for the outputstream final PdfWriter writer = PdfWriter.getInstance(document, outputStream); document.open(); final PdfContentByte cb = writer.getDirectContent(); // Holds the // PDF // data PdfImportedPage page; int pageOfCurrentReaderPDF = 0; final Iterator<PdfReader> iteratorPDFReader = readers.iterator(); // Loop through the PDF files and add to the output. while (iteratorPDFReader.hasNext()) { final PdfReader pdfReader = iteratorPDFReader.next(); // Create a new page in the target for each source page. while (pageOfCurrentReaderPDF < pdfReader.getNumberOfPages()) { document.newPage(); pageOfCurrentReaderPDF++; page = writer.getImportedPage(pdfReader, pageOfCurrentReaderPDF); cb.addTemplate(page, 0, 0); } pageOfCurrentReaderPDF = 0; } outputStream.flush(); document.close(); outputStream.close(); } catch (final Exception e) { LOGGER.error("Exception in concat PDFs : ", e); } finally { if (document.isOpen()) document.close(); try { if (outputStream != null) outputStream.close(); } catch (final IOException ioe) { LOGGER.error("Exception in concat PDFs : ", ioe); } } return outputStream != null ? outputStream.toByteArray() : null; }
From source file:org.encog.workbench.util.graph.DocumentPDF.java
License:Apache License
public static void writeChartAsPDF(OutputStream out, JFreeChart chart, int width, int height, FontMapper mapper) throws IOException { Rectangle pagesize = new Rectangle(width, height); Document document = new Document(pagesize, 50, 50, 50, 50); try {// w w w. j av a 2 s.com PdfWriter writer = PdfWriter.getInstance(document, out); document.addAuthor("JFreeChart"); document.addSubject("Demonstration"); document.open(); PdfContentByte cb = writer.getDirectContent(); PdfTemplate tp = cb.createTemplate(width, height); Graphics2D g2 = tp.createGraphics(width, height, mapper); Rectangle2D r2D = new Rectangle2D.Double(0, 0, width, height); chart.draw(g2, r2D); g2.dispose(); cb.addTemplate(tp, 0, 0); } catch (DocumentException de) { System.err.println(de.getMessage()); } }
From source file:org.geoserver.wms.map.PDFMapResponse.java
License:Open Source License
/** * Writes the PDF./*from www .j ava 2 s .com*/ * <p> * NOTE: the document seems to actually be created in memory, and being written down to * {@code output} once we call {@link Document#close()}. If there's no other way to do so, it'd * be better to actually split out the process into produceMap/write? * </p> * * @see org.geoserver.ows.Response#write(java.lang.Object, java.io.OutputStream, * org.geoserver.platform.Operation) */ @Override public void write(Object value, OutputStream output, Operation operation) throws IOException, ServiceException { Assert.isInstanceOf(PDFMap.class, value); WMSMapContent mapContent = ((PDFMap) value).getContext(); final int width = mapContent.getMapWidth(); final int height = mapContent.getMapHeight(); if (LOGGER.isLoggable(Level.FINE)) { LOGGER.fine("setting up " + width + "x" + height + " image"); } try { // step 1: creation of a document-object // width of document-object is width*72 inches // height of document-object is height*72 inches com.lowagie.text.Rectangle pageSize = new com.lowagie.text.Rectangle(width, height); Document document = new Document(pageSize); document.setMargins(0, 0, 0, 0); // step 2: creation of the writer PdfWriter writer = PdfWriter.getInstance(document, output); // step 3: we open the document document.open(); // step 4: we grab the ContentByte and do some stuff with it // we create a fontMapper and read all the fonts in the font // directory DefaultFontMapper mapper = new DefaultFontMapper(); FontFactory.registerDirectories(); // we create a template and a Graphics2D object that corresponds // with it PdfContentByte cb = writer.getDirectContent(); PdfTemplate tp = cb.createTemplate(width, height); PdfGraphics2D graphic = (PdfGraphics2D) tp.createGraphics(width, height, mapper); // we set graphics options if (!mapContent.isTransparent()) { graphic.setColor(mapContent.getBgColor()); graphic.fillRect(0, 0, width, height); } else { if (LOGGER.isLoggable(Level.FINE)) { LOGGER.fine("setting to transparent"); } int type = AlphaComposite.SRC; graphic.setComposite(AlphaComposite.getInstance(type)); Color c = new Color(mapContent.getBgColor().getRed(), mapContent.getBgColor().getGreen(), mapContent.getBgColor().getBlue(), 0); graphic.setBackground(mapContent.getBgColor()); graphic.setColor(c); graphic.fillRect(0, 0, width, height); type = AlphaComposite.SRC_OVER; graphic.setComposite(AlphaComposite.getInstance(type)); } Rectangle paintArea = new Rectangle(width, height); StreamingRenderer renderer = new StreamingRenderer(); renderer.setMapContent(mapContent); // TODO: expose the generalization distance as a param // ((StreamingRenderer) renderer).setGeneralizationDistance(0); RenderingHints hints = new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); renderer.setJava2DHints(hints); // we already do everything that the optimized data loading does... // if we set it to true then it does it all twice... java.util.Map rendererParams = new HashMap(); rendererParams.put("optimizedDataLoadingEnabled", new Boolean(true)); rendererParams.put("renderingBuffer", new Integer(mapContent.getBuffer())); // we need the renderer to draw everything on the batik provided graphics object rendererParams.put(StreamingRenderer.OPTIMIZE_FTS_RENDERING_KEY, Boolean.FALSE); // render everything in vector form if possible rendererParams.put(StreamingRenderer.VECTOR_RENDERING_KEY, Boolean.TRUE); if (DefaultWebMapService.isLineWidthOptimizationEnabled()) { rendererParams.put(StreamingRenderer.LINE_WIDTH_OPTIMIZATION_KEY, true); } rendererParams.put(StreamingRenderer.SCALE_COMPUTATION_METHOD_KEY, mapContent.getRendererScaleMethod()); renderer.setRendererHints(rendererParams); Envelope dataArea = mapContent.getRenderingArea(); // enforce no more than x rendering errors int maxErrors = wms.getMaxRenderingErrors(); MaxErrorEnforcer errorChecker = new MaxErrorEnforcer(renderer, maxErrors); // Add a render listener that ignores well known rendering exceptions and reports back // non // ignorable ones final RenderExceptionStrategy nonIgnorableExceptionListener; nonIgnorableExceptionListener = new RenderExceptionStrategy(renderer); renderer.addRenderListener(nonIgnorableExceptionListener); // enforce max memory usage int maxMemory = wms.getMaxRequestMemory() * KB; PDFMaxSizeEnforcer memoryChecker = new PDFMaxSizeEnforcer(renderer, graphic, maxMemory); // render the map renderer.paint(graphic, paintArea, mapContent.getRenderingArea(), mapContent.getRenderingTransform()); // render the watermark MapDecorationLayout.Block watermark = RenderedImageMapOutputFormat.getWatermark(wms.getServiceInfo()); if (watermark != null) { MapDecorationLayout layout = new MapDecorationLayout(); layout.paint(graphic, paintArea, mapContent); } // check if a non ignorable error occurred if (nonIgnorableExceptionListener.exceptionOccurred()) { Exception renderError = nonIgnorableExceptionListener.getException(); throw new ServiceException("Rendering process failed", renderError, "internalError"); } // check if too many errors occurred if (errorChecker.exceedsMaxErrors()) { throw new ServiceException("More than " + maxErrors + " rendering errors occurred, bailing out", errorChecker.getLastException(), "internalError"); } // check we did not use too much memory if (memoryChecker.exceedsMaxSize()) { long kbMax = maxMemory / KB; throw new ServiceException( "Rendering request used more memory than the maximum allowed:" + kbMax + "KB"); } graphic.dispose(); cb.addTemplate(tp, 0, 0); // step 5: we close the document document.close(); writer.flush(); writer.close(); } catch (DocumentException t) { throw new ServiceException("Error setting up the PDF", t, "internalError"); } }
From source file:org.ghost4j.document.PDFDocument.java
License:LGPL
public Document extract(int begin, int end) throws DocumentException { this.assertValidPageRange(begin, end); PDFDocument result = new PDFDocument(); ByteArrayInputStream bais = null; ByteArrayOutputStream baos = null; if (content != null) { com.lowagie.text.Document document = new com.lowagie.text.Document(); try {//from w w w . j a v a2 s .co m bais = new ByteArrayInputStream(content); baos = new ByteArrayOutputStream(); PdfReader inputPDF = new PdfReader(bais); // create a writer for the outputstream PdfWriter writer = PdfWriter.getInstance(document, baos); document.open(); PdfContentByte cb = writer.getDirectContent(); PdfImportedPage page; while (begin <= end) { document.newPage(); page = writer.getImportedPage(inputPDF, begin); cb.addTemplate(page, 0, 0); begin++; } document.close(); result.load(new ByteArrayInputStream(baos.toByteArray())); } catch (Exception e) { throw new DocumentException(e); } finally { if (document.isOpen()) document.close(); IOUtils.closeQuietly(bais); IOUtils.closeQuietly(baos); } } return result; }
From source file:org.jivesoftware.openfire.reporting.graph.GraphServlet.java
License:Open Source License
private void writePDFContent(HttpServletRequest request, HttpServletResponse response, JFreeChart charts[], Statistic[] stats, long starttime, long endtime, int width, int height) throws IOException { try {/* w ww .j a va2 s. c om*/ Document document = new Document(PageSize.A4, 50, 50, 50, 50); ByteArrayOutputStream baos = new ByteArrayOutputStream(); PdfWriter writer = PdfWriter.getInstance(document, baos); writer.setPageEvent(new PDFEventListener(request)); document.open(); int index = 0; int chapIndex = 0; for (Statistic stat : stats) { String serverName = XMPPServer.getInstance().getServerInfo().getXMPPDomain(); String dateName = JiveGlobals.formatDate(new Date(starttime)) + " - " + JiveGlobals.formatDate(new Date(endtime)); Paragraph paragraph = new Paragraph(serverName, FontFactory.getFont(FontFactory.HELVETICA, 18, Font.BOLD)); document.add(paragraph); paragraph = new Paragraph(dateName, FontFactory.getFont(FontFactory.HELVETICA, 14, Font.PLAIN)); document.add(paragraph); document.add(Chunk.NEWLINE); document.add(Chunk.NEWLINE); Paragraph chapterTitle = new Paragraph(++chapIndex + ". " + stat.getName(), FontFactory.getFont(FontFactory.HELVETICA, 16, Font.BOLD)); document.add(chapterTitle); // total hack: no idea what tags people are going to use in the description // possibly recommend that we only use a <p> tag? String[] paragraphs = stat.getDescription().split("<p>"); for (String s : paragraphs) { Paragraph p = new Paragraph(s); document.add(p); } document.add(Chunk.NEWLINE); PdfContentByte contentByte = writer.getDirectContent(); PdfTemplate template = contentByte.createTemplate(width, height); Graphics2D graphs2D = template.createGraphics(width, height, new DefaultFontMapper()); Rectangle2D rectangle2D = new Rectangle2D.Double(0, 0, width, height); charts[index++].draw(graphs2D, rectangle2D); graphs2D.dispose(); float x = (document.getPageSize().width() / 2) - (width / 2); contentByte.addTemplate(template, x, writer.getVerticalPosition(true) - height); document.newPage(); } document.close(); // setting some response headers response.setHeader("Expires", "0"); response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0"); response.setHeader("Pragma", "public"); // setting the content type response.setContentType("application/pdf"); // the contentlength is needed for MSIE!!! response.setContentLength(baos.size()); // write ByteArrayOutputStream to the ServletOutputStream ServletOutputStream out = response.getOutputStream(); baos.writeTo(out); out.flush(); } catch (DocumentException e) { Log.error("error creating PDF document: " + e.getMessage()); } }