Example usage for com.lowagie.text.pdf PdfTemplate createGraphics

List of usage examples for com.lowagie.text.pdf PdfTemplate createGraphics

Introduction

In this page you can find the example usage for com.lowagie.text.pdf PdfTemplate createGraphics.

Prototype

public java.awt.Graphics2D createGraphics(float width, float height) 

Source Link

Document

Gets a Graphics2D to write on.

Usage

From source file:com.anevis.jfreechartsamplespring.chart.ChartServiceImpl.java

private byte[] writeChartsToDocument(JFreeChart... charts) {
    try {/*from  ww  w . j  a va  2s.c o m*/
        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        float width = PageSize.A4.getWidth();
        float height = PageSize.A4.getHeight() / 2;
        int index = 0;

        Document document = new Document();
        PdfWriter writer = PdfWriter.getInstance(document, baos);
        document.open();
        PdfContentByte contentByte = writer.getDirectContent();

        for (JFreeChart chart : charts) {

            PdfTemplate template = contentByte.createTemplate(width, height);
            Graphics2D graphics2D = template.createGraphics(width, height);
            Rectangle2D rectangle2D = new Rectangle2D.Double(0, 0, width, height);

            chart.draw(graphics2D, rectangle2D);

            graphics2D.dispose();
            contentByte.addTemplate(template, 0, height - (height * index));
            index++;
        }

        writer.flush();
        document.close();

        return baos.toByteArray();
    } catch (DocumentException ex) {
        Logger.getLogger(ChartService.class.getName()).log(Level.SEVERE, null, ex);
    }
    return null;
}

From source file:com.byterefinery.rmbench.export.diagram.PDFDiagramExporter.java

License:Open Source License

protected void doExport(OutputStream out, IFigure figure) {

    Rectangle bounds = getBounds(figure);
    Document document = new Document(new com.lowagie.text.Rectangle(bounds.width, bounds.height));

    PdfWriter pdf;/* w  w  w.j a  v a  2  s.  c om*/
    try {
        pdf = PdfWriter.getInstance(document, out);
        document.open();
        document.add(new Chunk(" "));
    } catch (DocumentException e) {
        ExportPlugin.logError(e);
        return;
    }
    PdfContentByte contentbytes = pdf.getDirectContent();
    PdfTemplate template = contentbytes.createTemplate(bounds.width, bounds.height);
    Graphics2D graphics2d = template.createGraphics(bounds.width, bounds.height);
    try {
        GraphicsToGraphics2DAdaptor graphics = new GraphicsToGraphics2DAdaptor(graphics2d,
                bounds.getTranslated(bounds.getLocation().negate()));
        graphics.translate(bounds.getLocation().negate());
        figure.paint(graphics);
    } finally {
        graphics2d.dispose();
        contentbytes.addTemplate(template, 0, 0);
        document.close();
    }
}

From source file:de.chott.jfreechartsample.service.ChartService.java

/**
 * Schreibt mehrere JFreeCharts in ein PDF. Fr jedes Chart wird hierbei eine halbe PDF-Seite verwendet.
 * /*from www . ja va  2 s  .  c  o  m*/
 * @param charts
 * @return Das PDF als ByteArray
 */
private byte[] writeChartsToDocument(JFreeChart... charts) {
    try {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        float width = PageSize.A4.getWidth();
        float height = PageSize.A4.getHeight() / 2;
        int index = 0;

        Document document = new Document();
        PdfWriter writer = PdfWriter.getInstance(document, baos);
        document.open();
        PdfContentByte contentByte = writer.getDirectContent();

        for (JFreeChart chart : charts) {

            PdfTemplate template = contentByte.createTemplate(width, height);
            Graphics2D graphics2D = template.createGraphics(width, height);
            Rectangle2D rectangle2D = new Rectangle2D.Double(0, 0, width, height);

            chart.draw(graphics2D, rectangle2D);

            graphics2D.dispose();
            contentByte.addTemplate(template, 0, height - (height * index));
            index++;
        }

        writer.flush();
        document.close();

        return baos.toByteArray();
    } catch (Exception ex) {
        Logger.getLogger(ChartService.class.getName()).log(Level.SEVERE, null, ex);
    }
    return null;
}

From source file:de.d3web.empiricaltesting.casevisualization.jung.JUNGCaseVisualizer.java

License:Open Source License

/**
 * Streams the graph to an OutputStream (useful for web requests!)
 * /* www  . ja  va  2s  .  co  m*/
 * @param cases List<SequentialTestCase> cases
 * @param outStream OutputStream
 */
@Override
public void writeToStream(java.util.List<SequentialTestCase> cases, java.io.OutputStream outStream)
        throws IOException {

    init(cases);

    int w = vv.getGraphLayout().getSize().width;
    int h = vv.getGraphLayout().getSize().height;

    Document document = new Document();

    try {

        PdfWriter writer = PdfWriter.getInstance(document, outStream);
        document.setPageSize(new Rectangle(w, h));
        document.open();

        PdfContentByte cb = writer.getDirectContent();
        PdfTemplate tp = cb.createTemplate(w, h);
        Graphics2D g2 = tp.createGraphics(w, h);
        paintGraph(g2);

        g2.dispose();
        tp.sanityCheck();
        cb.addTemplate(tp, 0, 0);
        cb.sanityCheck();

        document.close();

    } catch (DocumentException e) {
        throw new IOException("Error while writing to file. The file was not created. ", e);
    }
}

From source file:gov.noaa.pfel.coastwatch.sgt.SgtUtil.java

License:Open Source License

/**
 * This creates a file to capture the pdf output generated by calls to 
 * graphics2D (e.g., use makeMap).// www. j  a v  a 2s.  co m
 * This will overwrite an existing file.
 * 
 * @param pageSize e.g, PageSize.LETTER or PageSize.LETTER.rotate() (or A4, or, ...)
 * @param width the bounding box width, in 1/144ths of an inch
 * @param height the bounding box height, in 1/144ths of an inch
 * @param outputStream
 * @return an object[] with 0=g2D, 1=document, 2=pdfContentByte, 3=pdfTemplate
 * @throws Exception if trouble
 */
public static Object[] createPdf(com.lowagie.text.Rectangle pageSize, int bbWidth, int bbHeight,
        OutputStream outputStream) throws Exception {
    //currently, this uses itext
    //see the sample program:
    //  file://localhost/C:/programs/iText/examples/com/lowagie/examples/directcontent/graphics2D/G2D.java
    //Document.compress = false; //for test purposes only
    Document document = new Document(pageSize);
    document.addCreationDate();
    document.addCreator("gov.noaa.pfel.coastwatch.SgtUtil.createPdf");

    document.setPageSize(pageSize);
    PdfWriter writer = PdfWriter.getInstance(document, outputStream);
    document.open();

    //create contentByte and template and Graphics2D objects
    PdfContentByte pdfContentByte = writer.getDirectContent();
    PdfTemplate pdfTemplate = pdfContentByte.createTemplate(bbWidth, bbHeight);
    Graphics2D g2D = pdfTemplate.createGraphics(bbWidth, bbHeight);

    return new Object[] { g2D, document, pdfContentByte, pdfTemplate };
}

From source file:javaaxp.xps2pdf.service.impl.PDFConverterImpl.java

License:Open Source License

@Override
public void covertToPDF(OutputStream ouput) throws XPSError {
    try {//ww w  . j  a  v  a2 s .  co  m
        int firstPage = fPageController.getXPSAccess().getPageAccess(0).getFirstPageNum();
        int lastPage = fPageController.getXPSAccess().getPageAccess(0).getLastPageNum();

        Document document = new Document();
        document.setPageCount(lastPage - firstPage + 1);
        document.setPageSize(PageSize.LETTER);
        PdfWriter writer = PdfWriter.getInstance(document, ouput);
        document.open();
        PdfContentByte cb = writer.getDirectContent();
        for (int i = firstPage; i < 1; i++) {
            System.out.println("Converting page " + i);
            fPageController.setPage(i);
            PdfTemplate tp = cb.createTemplate((float) fPageController.getPage().getWidth(),
                    (float) fPageController.getPage().getHeight());
            Graphics g = tp.createGraphics((float) fPageController.getPage().getWidth(),
                    (float) fPageController.getPage().getHeight());
            JComponent toReturn = fPageViewer.getPageRenderer().getRendererComponent();
            toReturn.paint(g);
            cb.addTemplate(tp, 0, 0);
            document.newPage();
        }
        document.close();
    } catch (DocumentException e) {
        //rethrow
    }
}

From source file:joelib2.io.types.PDF.java

License:Open Source License

/**
 *  Writes a molecule with his <tt>PairData</tt> .
 *
 * @param  mol              the molecule with additional data
 * @param  title            the molecule title or <tt>null</tt> if the title
 *      from the molecule should be used
 * @param  writePairData    if <tt>true</tt> then the additional molecule data
 *      is written//from  w ww . j  av a 2s .  com
 * @param  attribs2write    Description of the Parameter
 * @return                  <tt>true</tt> if the molecule and the data has
 *      been succesfully written.
 * @exception  IOException  Description of the Exception
 */
public boolean write(Molecule mol, String title, boolean writePairData, List attribs2write,
        SMARTSPatternMatcher smarts) throws IOException {
    if (firstMoleculeWritten == false) {
        document.open();
        firstMoleculeWritten = true;
    }

    Dimension d = new Dimension(Mol2Image.instance().getDefaultWidth(),
            Mol2Image.instance().getDefaultHeight());
    RenderingAtoms container = new RenderingAtoms();
    container.add(mol);

    RenderHelper.translateAllPositive(container);
    RenderHelper.scaleMolecule(container, d, 0.8);
    RenderHelper.center(container, d);

    Renderer2D renderer = new Renderer2D();

    //BaseFont helvetica = null;
    try {
        BaseFont.createFont("Helvetica", BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
    } catch (DocumentException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    int w = d.width;
    int h = d.height;
    PdfContentByte cb = writer.getDirectContent();
    PdfTemplate tp = cb.createTemplate(w, h);
    Graphics2D g2 = tp.createGraphics(w, h);
    g2.setStroke(new BasicStroke(0.1f));
    tp.setWidth(w);
    tp.setHeight(h);

    g2.setColor(renderer.getRenderer2DModel().getBackColor());
    g2.fillRect(0, 0, d.width, d.height);

    if (smarts != null) {
        renderer.selectSMARTSPatterns(container, smarts);
    }

    renderer.paintMolecule(container, g2);

    g2.dispose();

    ////cb.addTemplate(tp, 72, 720 - h);
    //cb.addTemplate(tp, 12, 720 - h);
    cb.addTemplate(tp, 0, document.getPageSize().height() - h);

    //     Mol2Image.instance().mol2image(mol);
    BaseFont bf = null;

    try {
        bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
    } catch (DocumentException e2) {
        // TODO Auto-generated catch block
        e2.printStackTrace();
    }

    String string = "";

    //float myBorder = DEFAULT_BORDER;
    //float fontSize = 10;
    //float fontSizeDelta = DEFAULT_FONT_OFFSET;
    float hpos;

    if (writePairData) {
        PairData pairData;
        PairDataIterator gdit = mol.genericDataIterator();
        int index = 0;
        boolean firstPageWritten = false;

        List attributesV;

        if (attribs2write == null) {
            // write all descriptors
            attributesV = new Vector();

            //DescResult tmpPropResult;
            while (gdit.hasNext()) {
                pairData = gdit.nextPairData();

                attributesV.add(pairData.getKey());
            }
        } else {
            attributesV = attribs2write;
        }

        // sort descriptors by attribute name
        String[] attributes = new String[attributesV.size()];

        for (int i = 0; i < attributesV.size(); i++) {
            attributes[i] = (String) attributesV.get(i);
        }

        Arrays.sort(attributes);

        // write them
        for (int i = 0; i < attributes.length; i++) {
            pairData = mol.getData(attributes[i]);
            string = pairData.getKey() + " = " + pairData.toString();

            // reduce too complex data
            string = string.replace('\n', ' ');
            string = string.substring(0, Math.min(string.length(), WRITE_MAX_CHARACTERS));

            tp = cb.createTemplate(document.getPageSize().width() - pageBorder, fontSize + fontSizeDelta);
            tp.setFontAndSize(bf, fontSize);
            tp.beginText();
            tp.setTextMatrix(0, fontSizeDelta);
            tp.showText(string);
            tp.endText();
            cb.setLineWidth(1f);
            tp.moveTo(0, 0);
            tp.lineTo(document.getPageSize().width() - (2 * pageBorder), 0);
            tp.stroke();

            if (firstPageWritten) {
                hpos = document.getPageSize().height() - ((fontSize + fontSizeDelta) * (index + 1));
            } else {
                hpos = document.getPageSize().height() - h - ((fontSize + fontSizeDelta) * (index + 1));
            }

            if (hpos < pageBorder) {
                index = 1;
                firstPageWritten = true;
                hpos = document.getPageSize().height() - ((fontSize + fontSizeDelta) * (index + 1));

                try {
                    document.newPage();
                } catch (DocumentException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }

            cb.addTemplate(tp, pageBorder, hpos);

            index++;
        }
    }

    try {
        document.newPage();
    } catch (DocumentException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return (true);
}

From source file:org.alchemy.core.AlcSession.java

License:Open Source License

/** Save the canvas to a single paged PDF file
 * //w w  w  . ja v  a 2 s.  c om
 * @param file  The file object to save the pdf to
 * @return      True if save worked, otherwise false
 */
boolean saveSinglePdf(File file) {
    // Get the current 'real' size of the canvas without margins/borders
    java.awt.Rectangle bounds = Alchemy.canvas.getVisibleRect();
    //int singlePdfWidth = Alchemy.window.getWindowSize().width;
    //int singlePdfHeight = Alchemy.window.getWindowSize().height;
    com.lowagie.text.Document document = new com.lowagie.text.Document(
            new com.lowagie.text.Rectangle(bounds.width, bounds.height), 0, 0, 0, 0);
    System.out.println("Save Single Pdf Called: " + file.toString());
    boolean noError = true;

    try {

        PdfWriter singleWriter = PdfWriter.getInstance(document, new FileOutputStream(file));
        document.addTitle("Alchemy Session");
        document.addAuthor(USER_NAME);
        document.addCreator("Alchemy <http://al.chemy.org>");

        // Add metadata and open the document
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        XmpWriter xmp = new XmpWriter(os);
        PdfSchema pdf = new PdfSchema();
        pdf.setProperty(PdfSchema.KEYWORDS, "Alchemy <http://al.chemy.org>");
        //pdf.setProperty(PdfSchema.VERSION, "1.4");
        xmp.addRdfDescription(pdf);
        xmp.close();
        singleWriter.setXmpMetadata(os.toByteArray());

        // To avoid transparent colurs being converted from RGB>CMYK>RGB
        // We have to add everything to a transparency group
        PdfTransparencyGroup transGroup = new PdfTransparencyGroup();
        transGroup.put(PdfName.CS, PdfName.DEVICERGB);

        document.open();

        PdfContentByte cb = singleWriter.getDirectContent();
        PdfTemplate tp = cb.createTemplate(bounds.width, bounds.height);

        document.newPage();

        cb.getPdfWriter().setGroup(transGroup);
        // Make sure the color space is Device RGB
        cb.setDefaultColorspace(PdfName.CS, PdfName.DEVICERGB);

        // Draw into the template and add it to the PDF 
        Graphics2D g2pdf = tp.createGraphics(bounds.width, bounds.height);
        Alchemy.canvas.setGuide(false);
        Alchemy.canvas.vectorCanvas.paintComponent(g2pdf);
        Alchemy.canvas.setGuide(true);
        g2pdf.dispose();
        cb.addTemplate(tp, 0, 0);

    } catch (DocumentException ex) {
        System.err.println(ex);
        noError = false;
    } catch (IOException ex) {
        System.err.println(ex);
        noError = false;
    }

    document.close();

    return noError;
}

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/* w w  w.j a  v a2s.  co 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 w w .  j  a v a 2s  .  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();
}