Example usage for com.lowagie.text.pdf PdfContentByte createTemplate

List of usage examples for com.lowagie.text.pdf PdfContentByte createTemplate

Introduction

In this page you can find the example usage for com.lowagie.text.pdf PdfContentByte createTemplate.

Prototype

public PdfTemplate createTemplate(float width, float height) 

Source Link

Document

Creates a new template.

Usage

From source file:jmbench.plots.UtilPlotPdf.java

License:Open Source License

public static void saveAsPdf(LegendTitle legend, String FILENAME, int width, int height) {
    Document document = new Document(new Rectangle(width, height));
    try {/* w  w w .  ja  va  2  s.  c  o m*/
        FileOutputStream file = new FileOutputStream(FILENAME);
        PdfWriter writer = PdfWriter.getInstance(document, file);
        document.open();
        PdfContentByte cb = writer.getDirectContent();
        PdfTemplate tp = cb.createTemplate(width, height);
        Graphics2D g2d = tp.createGraphics(width, height, new DefaultFontMapper());
        Rectangle2D r2d = new Rectangle2D.Double(0, 0, width, height);
        legend.draw(g2d, r2d);
        g2d.dispose();
        cb.addTemplate(tp, 0, 0);
        document.close();
        g2d.dispose();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

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  ww w.  ja  v a  2 s  .c om*/
 * @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:keel.GraphInterKeel.datacf.visualizeData.VisualizePanelCharts2D.java

License:Open Source License

private void topdfjButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_topdfjButtonActionPerformed
    // Save chart as a PDF file
    JFileChooser chooser = new JFileChooser();
    chooser.setDialogTitle("Save chart");
    KeelFileFilter fileFilter = new KeelFileFilter();
    fileFilter.addExtension("pdf");
    fileFilter.setFilterName("PDF images (.pdf)");
    chooser.setFileFilter(fileFilter);//from   ww  w . j  ava 2 s. co  m
    chooser.setCurrentDirectory(Path.getFilePath());
    int opcion = chooser.showSaveDialog(this);
    Path.setFilePath(chooser.getCurrentDirectory());
    if (opcion == JFileChooser.APPROVE_OPTION) {
        String nombre = chooser.getSelectedFile().getAbsolutePath();
        if (!nombre.toLowerCase().endsWith(".pdf")) {
            // Add correct extension
            nombre += ".pdf";
        }
        File tmp = new File(nombre);
        if (!tmp.exists() || JOptionPane.showConfirmDialog(this,
                "File " + nombre + " already exists. Do you want to replace it?", "Confirm",
                JOptionPane.YES_NO_OPTION, 3) == JOptionPane.YES_OPTION) {
            try {
                Document document = new Document();
                PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(nombre));
                document.addAuthor("KEEL");
                document.addSubject("Attribute comparison");
                document.open();
                PdfContentByte cb = writer.getDirectContent();
                PdfTemplate tp = cb.createTemplate(550, 412);
                Graphics2D g2 = tp.createGraphics(550, 412, new DefaultFontMapper());
                Rectangle2D r2D = new Rectangle2D.Double(0, 0, 550, 412);
                chart2.setBackgroundPaint(Color.white);
                chart2.draw(g2, r2D);
                g2.dispose();
                cb.addTemplate(tp, 20, 350);
                document.close();
            } catch (Exception exc) {
            }
        }
    }
}

From source file:org.adempiere.pdf.Document.java

License:Open Source License

private static void writePDF(Pageable pageable, OutputStream output) {
    try {//  w  ww .  j  a  v  a  2s .c  om
        final PageFormat pf = pageable.getPageFormat(0);

        final com.lowagie.text.Document document = new com.lowagie.text.Document(
                new Rectangle((int) pf.getWidth(), (int) pf.getHeight()));
        final PdfWriter writer = PdfWriter.getInstance(document, output);
        writer.setPdfVersion(PdfWriter.VERSION_1_2);
        document.open();
        final DefaultFontMapper mapper = new DefaultFontMapper();

        //Elaine 2009/02/17 - load additional font from directory set in PDF_FONT_DIR of System Configurator 
        String pdfFontDir = MSysConfig.getValue(PDF_FONT_DIR, "");
        if (pdfFontDir != null && pdfFontDir.trim().length() > 0) {
            pdfFontDir = pdfFontDir.trim();
            File dir = new File(pdfFontDir);
            if (dir.exists() && dir.isDirectory())
                mapper.insertDirectory(pdfFontDir);
        }
        //

        final float w = (float) pf.getWidth();
        final float h = (float) pf.getHeight();
        final PdfContentByte cb = writer.getDirectContent();
        for (int page = 0; page < pageable.getNumberOfPages(); page++) {
            if (page != 0) {
                document.newPage();
            }

            final PdfTemplate tp = cb.createTemplate(w, h);
            final Graphics2D g2 = tp.createGraphics(w, h, mapper);
            tp.setWidth(w);
            tp.setHeight(h);
            pageable.getPrintable(page).print(g2, pf, page);
            g2.dispose();
            cb.addTemplate(tp, 0, 0);
        }
        document.close();

    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:org.adempiere.util.Document.java

private static void writePDF(Pageable pageable, OutputStream output) {
    try {/*from   ww  w  .  jav  a2s  . c  o  m*/
        final PageFormat pf = pageable.getPageFormat(0);

        Rectangle pageSize = new Rectangle((int) pf.getWidth(), (int) pf.getHeight());
        final com.lowagie.text.Document document = new com.lowagie.text.Document(pageSize);
        final PdfWriter writer = PdfWriter.getInstance(document, output);
        writer.setPdfVersion(PdfWriter.VERSION_1_2);
        document.open();
        final DefaultFontMapper mapper = new DefaultFontMapper();

        String pdfFontDir = /* MSysConfig.getValue( */PDF_FONT_DIR/* , "") */;
        if (pdfFontDir != null && pdfFontDir.trim().length() > 0) {
            pdfFontDir = pdfFontDir.trim();
            File dir = new File(pdfFontDir);
            if (dir.exists() && dir.isDirectory())
                mapper.insertDirectory(pdfFontDir);
        }
        final float w = (float) pf.getWidth();
        final float h = (float) pf.getHeight();
        final PdfContentByte cb = writer.getDirectContent();
        for (int page = 0; page < pageable.getNumberOfPages(); page++) {
            if (page != 0) {
                document.newPage();
            }

            final PdfTemplate tp = cb.createTemplate(w, h);
            final Graphics2D g2 = tp.createGraphics(w, h, mapper);
            tp.setWidth(w);
            tp.setHeight(h);
            pageable.getPrintable(page).print(g2, pf, page);
            g2.dispose();
            cb.addTemplate(tp, 0, 0);
        }
        document.close();

    } catch (Exception e) {
        e.printStackTrace();
    }
}

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

License:Open Source License

/** Save the canvas to a single paged PDF file
 * /*from w ww  .j  av  a 2s .c o m*/
 * @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  a2  s  . 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.  ja va 2 s  .c  om*/
    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.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 {//from  w  ww .java 2s  .  c  o m
        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  a v  a 2s  .  co m*/
 * <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");
    }
}