Example usage for com.lowagie.text.pdf PdfWriter setPageEvent

List of usage examples for com.lowagie.text.pdf PdfWriter setPageEvent

Introduction

In this page you can find the example usage for com.lowagie.text.pdf PdfWriter setPageEvent.

Prototype


public void setPageEvent(PdfPageEvent event) 

Source Link

Document

Sets the PdfPageEvent for this document.

Usage

From source file:jm.Reporte.java

License:GNU General Public License

public void correos(HttpServletResponse response, ResultSet registros) {
    /* inicio PDF */
    Rectangle orientacion = (this.vertical) ? PageSize.A4 : PageSize.A4.rotate();
    Document document = new Document(orientacion);// paso 1
    document.setMargins(0, 0, 50, 80); /*Izquierda, derecha, tope, pie */
    try {//  w w w  .  j  ava  2 s  .co m
        PdfWriter writer = PdfWriter.getInstance(document, response.getOutputStream()); // paso 2
        writer.setPageEvent(new Reporte(this.vertical, this.logo, this.titulo, this.ruc, this.subtitulo,
                this.direccion, this.sucursal, this.rep_pie));
        document.open(); // paso 3

        /* todo el cuerpo del doc es el paso 4 */

        document.add(Addons.setCabecera(this.logo, this.titulo, this.ruc, this.subtitulo, this.direccion,
                this.sucursal));

        PdfPTable tbl_det = new PdfPTable(new float[] { 20, 80 });
        String aux = "";
        String columna1 = "";
        String columna2 = "";
        boolean uno = true;
        try {
            tbl_det.addCell(
                    Addons.setCeldaPDF("SECTOR", Font.TIMES_ROMAN, 8, Font.BOLD, Element.ALIGN_CENTER, 1));
            tbl_det.addCell(Addons.setCeldaPDF("CORREOS ELECTRONICOS", Font.TIMES_ROMAN, 8, Font.BOLD,
                    Element.ALIGN_CENTER, 1));
            while (registros.next()) {
                columna1 = (registros.getString(1) != null) ? registros.getString(1) : "";
                columna2 += ((registros.getString(2) != null) ? registros.getString(2) : "") + ", ";
                if (aux.compareTo(columna1) != 0 && !uno) {
                    tbl_det.addCell(Addons.setCeldaPDF(columna1, Font.TIMES_ROMAN, 8, Font.NORMAL,
                            Element.ALIGN_LEFT, 1));
                    tbl_det.addCell(Addons.setCeldaPDF(columna2.substring(0, columna2.length() - 2),
                            Font.TIMES_ROMAN, 8, Font.NORMAL, Element.ALIGN_LEFT, 1));
                    aux = columna1;
                    columna2 = "";
                }
                uno = false;
            }
            registros.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        document.add(tbl_det);

    } catch (IllegalStateException ie) {
        ie.printStackTrace();
    } catch (DocumentException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }

    document.close(); // paso 5
    /* fin PDF */
}

From source file:jm.Reporte.java

License:GNU General Public License

public void activosPersonalizadosClientes(HttpServletResponse response, String[] cabTabla, float[] anchoTabla,
        ResultSet registros, DataBase objDB) {
    /* inicio PDF */
    Rectangle orientacion = (this.vertical) ? PageSize.A4 : PageSize.A4.rotate();
    Document document = new Document(orientacion);// paso 1
    document.setMargins(0, 0, 50, 80); /*Izquierda, derecha, tope, pie */
    try {//ww  w  .j  a v a2s  .  c om
        PdfWriter writer = PdfWriter.getInstance(document, response.getOutputStream()); // paso 2
        writer.setPageEvent(new Reporte(this.vertical, this.logo, this.titulo, this.ruc, this.subtitulo,
                this.direccion, this.sucursal, this.rep_pie));

        document.open(); // paso 3

        /* todo el cuerpo del doc es el paso 4 */

        document.add(Addons.setCabecera(this.logo, this.titulo, this.ruc, this.subtitulo, this.direccion,
                this.sucursal));

        document.add(Addons.setCabeceraTabla(cabTabla, anchoTabla));

        PdfPTable tbl_det = new PdfPTable(anchoTabla);
        try {
            while (registros.next()) {
                String persona_recibe = "";
                String num_personalizacion = (registros.getString("num_personalizacion") != null)
                        ? registros.getString("num_personalizacion")
                        : "";
                try {
                    ResultSet rs = objDB
                            .consulta("select * from tbl_activo_personalizacion where num_documento="
                                    + num_personalizacion);
                    if (rs.next()) {
                        persona_recibe = (rs.getString("persona_recibe") != null)
                                ? rs.getString("persona_recibe")
                                : "";
                        rs.close();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                tbl_det.addCell(Addons.setCeldaPDF(String.valueOf(persona_recibe), Font.TIMES_ROMAN, 8,
                        Font.NORMAL, Element.ALIGN_LEFT, 1));

                String mac = (registros.getString("codigo_activo") != null)
                        ? registros.getString("codigo_activo")
                        : "";
                tbl_det.addCell(Addons.setCeldaPDF(String.valueOf(mac), Font.TIMES_ROMAN, 8, Font.NORMAL,
                        Element.ALIGN_LEFT, 1));
            }

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

        document.add(tbl_det);

    } catch (IllegalStateException ie) {
        ie.printStackTrace();
    } catch (DocumentException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }

    document.close(); // paso 5
    /* fin PDF */
}

From source file:net.bull.javamelody.internal.web.pdf.PdfDocumentFactory.java

License:Apache License

private void createWriter(Document document, String title) throws DocumentException, IOException {
    final PdfWriter writer = PdfWriter.getInstance(document, output);
    //writer.setViewerPreferences(PdfWriter.PageLayoutTwoColumnLeft);

    // title// w  ww . ja  v  a 2s  .c  om
    final HeaderFooter header = new HeaderFooter(new Phrase(title), false);
    header.setAlignment(Element.ALIGN_LEFT);
    header.setBorder(Rectangle.NO_BORDER);
    document.setHeader(header);

    // simple page numbers : x
    //HeaderFooter footer = new HeaderFooter(new Phrase(), true);
    //footer.setAlignment(Element.ALIGN_RIGHT);
    //footer.setBorder(Rectangle.TOP);
    //document.setFooter(footer);

    // add the event handler for advanced page numbers : x/y
    writer.setPageEvent(new PdfAdvancedPageNumberEvents());
}

From source file:net.bull.javamelody.swing.print.MPdfWriter.java

License:Apache License

/**
 * We create a writer that listens to the document and directs a PDF-stream to out
 *
 * @param table//ww  w  .j  a  v a 2s .  c  o m
 *           MBasicTable
 * @param document
 *           Document
 * @param out
 *           OutputStream
 * @return DocWriter
 * @throws DocumentException
 *            e
 */
protected DocWriter createWriter(final MBasicTable table, final Document document, final OutputStream out)
        throws DocumentException {
    final PdfWriter writer = PdfWriter.getInstance(document, out);
    // writer.setViewerPreferences(PdfWriter.PageLayoutTwoColumnLeft);

    // title
    if (table.getName() != null) {
        final HeaderFooter header = new HeaderFooter(new Phrase(table.getName()), false);
        header.setAlignment(Element.ALIGN_LEFT);
        header.setBorder(Rectangle.NO_BORDER);
        document.setHeader(header);
        document.addTitle(table.getName());
    }

    // simple page numbers : x
    // HeaderFooter footer = new HeaderFooter(new Phrase(), true);
    // footer.setAlignment(Element.ALIGN_RIGHT);
    // footer.setBorder(Rectangle.TOP);
    // document.setFooter(footer);

    // add the event handler for advanced page numbers : x/y
    writer.setPageEvent(new AdvancedPageNumberEvents());

    return writer;
}

From source file:net.mitnet.tools.pdf.book.pdf.builder.PdfBookBuilder.java

License:Open Source License

public void buildBook(List<File> inputFileList, File outputFile) {

    try {/*w  w w. j  av  a 2s .  co m*/

        float pageWidth = getConfig().getPageWidth();
        float pageHeight = getConfig().getPageHeight();

        // Create new Document

        /*
        float marginLeft = 36;
        float marginRight = 36;
        float marginTop = 36;
        float marginBottom = 36;
        */

        if (isVerboseEnabled()) {
            verbose("Building output PDF file " + outputFile);
        }

        // TableOfContents toc = new TableOfContents();

        ProgressMonitor progressMonitor = getConfig().getProgressMonitor();
        TocRowChangeListener tocRowChangeListener = getConfig().getTocRowChangeListener();

        Document outputDocument = new Document(getConfig().getPageSize());
        // Document outputDocument = new Document( getPageSize(), marginLeft, marginRight, marginTop, marginBottom );

        PdfWriter pdfWriter = PdfWriter.getInstance(outputDocument, new FileOutputStream(outputFile));

        // TODO - review PDF page event forwarder
        PdfPageEventLogger pdfPageEventLogger = new PdfPageEventLogger();
        pdfWriter.setPageEvent(pdfPageEventLogger);

        outputDocument.open();

        String metaTitle = getConfig().getMetaTitle();
        if (!StringUtils.isEmpty(metaTitle)) {
            outputDocument.addTitle(metaTitle);
        }
        String metaAuthor = getConfig().getMetaAuthor();
        if (!StringUtils.isEmpty(metaAuthor)) {
            outputDocument.addAuthor(metaAuthor);
        }

        PdfContentByte pdfContent = pdfWriter.getDirectContent();

        // Loop through and pull pages
        int outputPageCount = 0;
        int currentSourceFileIndex = 0;
        int maxSourceFileIndex = inputFileList.size();

        // BaseFont pageLabelFont = BaseFont.createFont( PdfBookBuilderConfig.DEFAULT_FONT, BaseFont.CP1250, BaseFont.EMBEDDED );
        BaseFont pageLabelFont = BaseFont.createFont(PdfBookBuilderConfig.DEFAULT_FONT_PATH, BaseFont.CP1250,
                BaseFont.EMBEDDED);
        if (isVerboseEnabled()) {
            verbose("Using page label font " + pageLabelFont);
        }

        if (isVerboseEnabled()) {
            verbose("Assembling pages using n-up " + getConfig().getNup());
        }

        for (File sourceFile : inputFileList) {

            currentSourceFileIndex++;

            // TODO - refactor current file PDF page processing to another method
            // TODO - handle failover to ensure processing continues ???

            if (sourceFile.isFile()) {

                if (isVerboseEnabled()) {
                    verbose("Reading source PDF file " + sourceFile);
                }

                int sourcePageIndex = 0;

                PdfReader sourcePdfReader = new PdfReader(sourceFile.getCanonicalPath());
                PdfReaderHelper sourcePdfReaderHelper = new PdfReaderHelper(sourcePdfReader);
                if (isVerboseEnabled()) {
                    verbose("PDF reader is " + sourcePdfReader);
                    verbose("PDF reader helper is " + sourcePdfReaderHelper);
                }

                String currentSourcePdfTitle = FilenameUtils.getBaseName(sourceFile.getName());
                String currentSourcePdfAuthor = getSystemUserName();
                if (isVerboseEnabled()) {
                    verbose("PDF title is " + currentSourcePdfTitle);
                    verbose("PDF author is " + currentSourcePdfAuthor);
                }

                currentSourcePdfTitle = sourcePdfReaderHelper.getDocumentTitle(currentSourcePdfTitle);
                currentSourcePdfAuthor = sourcePdfReaderHelper.getDocumentTitle(currentSourcePdfAuthor);
                if (isVerboseEnabled()) {
                    verbose("PDF info title is " + currentSourcePdfTitle);
                    verbose("PDF info author is " + currentSourcePdfAuthor);
                }

                boolean firstPageOfCurrentSource = true;

                int maxSourcePages = sourcePdfReader.getNumberOfPages();
                if (isVerboseEnabled()) {
                    verbose("There are " + maxSourcePages + " page(s) in source PDF file " + sourceFile);
                }

                // process all pages from source doc
                while (sourcePageIndex < maxSourcePages) {

                    // add new page to current document
                    outputDocument.newPage();

                    outputPageCount++;
                    if (isVerboseEnabled()) {
                        verbose("Building output PDF page " + outputPageCount + " ...");
                    }

                    // add first page of current source to TOC listener
                    if (firstPageOfCurrentSource) {
                        int currentPageIndex = outputPageCount;
                        if (tocRowChangeListener != null) {
                            TocRow tocEntry = new TocRow(currentSourcePdfTitle, currentPageIndex);
                            tocRowChangeListener.addTocRow(tocEntry);
                            if (isVerboseEnabled()) {
                                verbose("Added TOC entry " + tocEntry + " to listener");
                            }
                        }
                        firstPageOfCurrentSource = false;
                    }

                    // extract first page from source document
                    sourcePageIndex++;
                    if (isVerboseEnabled()) {
                        verbose("Adding page " + sourcePageIndex + " of " + maxSourcePages
                                + " from source to output");
                    }
                    PdfImportedPage page1 = pdfWriter.getImportedPage(sourcePdfReader, sourcePageIndex);

                    // n-up is 1
                    if (config.getNup() == 1) {
                        // add first page to top half of current page
                        // TODO - review magic transformation matrix numbers and offsets
                        // TODO - calculate scaling/transform based on page rect and template rect
                        float p1a = 0.65f;
                        float p1b = 0;
                        float p1c = 0;
                        float p1d = 0.65f;
                        float p1e = 20;
                        float p1f = 160;
                        pdfContent.addTemplate(page1, p1a, p1b, p1c, p1d, p1e, p1f);

                        // n-up is 2 (default)
                    } else {

                        // add first page to top half of current page
                        // TODO - review magic transformation matrix numbers and offsets
                        float p1a = 0.5f;
                        float p1b = 0;
                        float p1c = 0;
                        float p1d = 0.5f;
                        float p1e = (125);
                        float p1f = ((pageWidth / 2) + 120 + 20);
                        pdfContent.addTemplate(page1, p1a, p1b, p1c, p1d, p1e, p1f);

                        // extract second page from source document ?
                        PdfImportedPage page2 = null;
                        if (sourcePageIndex < maxSourcePages) {
                            sourcePageIndex++;
                            if (isVerboseEnabled()) {
                                verbose("Adding page " + sourcePageIndex + " of " + maxSourcePages
                                        + " from source to output");
                            }
                            page2 = pdfWriter.getImportedPage(sourcePdfReader, sourcePageIndex);
                        }

                        // add second page to bottom half of current page
                        if (page2 != null) {
                            // TODO - review magic transformation matrix numbers and offsets
                            float p2a = 0.5f;
                            float p2b = 0;
                            float p2c = 0;
                            float p2d = 0.5f;
                            float p2e = 125;
                            float p2f = 120;
                            pdfContent.addTemplate(page2, p2a, p2b, p2c, p2d, p2e, p2f);
                        }
                    }

                    /*
                    // add first page to top half of current page
                    // TODO - review magic transformation matrix numbers and offsets
                    float p1a = 0.5f;
                    float p1b = 0;
                    float p1c = 0;
                    float p1d = 0.5f;
                    float p1e = (125);
                    float p1f = ((pageWidth / 2) + 120 + 20);
                    pdfContent.addTemplate( page1, p1a, p1b, p1c, p1d, p1e, p1f );
                            
                    // add second page to bottom half of current page
                    if (page2 != null) {
                       // TODO - review magic transformation matrix numbers and offsets
                       float p2a = 0.5f; 
                       float p2b = 0;
                       float p2c = 0;
                       float p2d = 0.5f;
                       float p2e = 125;
                       float p2f = 120;
                       pdfContent.addTemplate( page2, p2a, p2b, p2c, p2d, p2e, p2f );
                    }
                    */

                    // Add current page number to page footer
                    String pageCountLabel = "Page " + outputPageCount;
                    pdfContent.beginText();
                    pdfContent.setFontAndSize(pageLabelFont, PdfBookBuilderConfig.DEFAULT_FONT_SIZE);
                    pdfContent.showTextAligned(PdfContentByte.ALIGN_CENTER, pageCountLabel, (pageWidth / 2), 40,
                            0);
                    pdfContent.endText();
                }

                if (isVerboseEnabled()) {
                    verbose("Finished reading " + maxSourcePages + " page(s) from source PDF file "
                            + sourceFile);
                }

                // update progress
                if (isVerboseEnabled()) {
                    if (progressMonitor != null) {
                        int fileProgressPercentage = MathHelper.calculatePercentage(currentSourceFileIndex,
                                maxSourceFileIndex);
                        progressMonitor.setProgressPercentage(fileProgressPercentage);
                    }
                }
            }
        }

        // close document
        outputDocument.close();

        if (isVerboseEnabled()) {
            verbose("Output PDF file " + outputFile + " contains " + outputPageCount + " page(s)");
        }

        // TODO - output ODT page stats summary

    } catch (Exception e) {

        String msg = "Error building PDF book: " + e.getMessage();
        e.printStackTrace(System.err);
        System.err.println(msg);

    }

}

From source file:org.cgiar.ccafs.ap.summaries.projects.pdf.ProjectSummaryPDF.java

License:Open Source License

/**
 * This method is used for generating the PDF File.
 * /*from  ww  w. jav a  2  s.c om*/
 * @param project project prepared before with the information
 * @param currentPlanningYear current year of planning
 * @param midOutcomeYear year 2019
 */
public void generatePdf(Project project, int currentPlanningYear, int currentReportingYear,
        int midOutcomeYear) {

    this.prepareFormatter();
    this.allMOGs = elementManager.getIPElementList();
    statuses = new HashMap<>();
    List<ProjectStatusEnum> list = Arrays.asList(ProjectStatusEnum.values());
    for (ProjectStatusEnum projectStatusEnum : list) {
        statuses.put(projectStatusEnum.getStatusId(), projectStatusEnum.getStatus());
    }

    this.mapPartnerPersons = projectPartnerManager.getAllProjectPartnersPersonsWithTheirInstitution();

    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    this.document = new Document(PageSize.A4, 57, 57, 60, 57);
    this.project = project;
    this.midOutcomeYear = midOutcomeYear;
    this.currentPlanningYear = currentPlanningYear;
    this.currentReportingYear = currentReportingYear;
    this.setSummaryTitle(project.getStandardIdentifier(Project.PDF_IDENTIFIER_REPORT));

    PdfWriter writer = this.initializePdf(document, outputStream, PORTRAIT);

    // Adding the event to include header and footer on each page

    HeaderFooterPDF event;

    if (project.isReporting()) {
        event = new HeaderFooterPDF(summaryTitle, PORTRAIT,
                project.isSubmitted(currentReportingYear, APConstants.REPORTING_SECTION),
                APConstants.REPORTING_SECTION, String.valueOf(currentReportingYear));
    } else {
        event = new HeaderFooterPDF(summaryTitle, PORTRAIT,
                project.isSubmitted(currentPlanningYear, APConstants.PLANNING_SECTION),
                APConstants.PLANNING_SECTION, String.valueOf(this.currentPlanningYear));
    }

    writer.setPageEvent(event);

    // Open document
    document.open();

    // Summary content
    this.addProjectTitle();
    this.addMainInformationTable();
    this.addProjectContributions();
    this.addSummary();
    this.addProjectPartners();
    this.addProjectLocations();
    this.addProjectOutcomes("4");
    this.addProjectOutputs("5");
    this.addActivities();
    if (project.isReporting()) {
        this.addBudgetReporting("7");
    } else {
        this.addProjectBudgets();
    }

    // Close document
    document.close();

    // Setting result file attributes
    contentLength = outputStream.size();
    inputStream = new ByteArrayInputStream(outputStream.toByteArray());
}

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  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 2s . c  o m
    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.flightgear.clgen.backend.PdfVisitor.java

License:Open Source License

/**
 * Constructs a PDF visitor with the path to the output directory.
 *
 * @param outputDir the output directory
 *//*from  w ww  .jav a 2  s .  co m*/
public PdfVisitor(final Path outputDir) {
    try {
        document.setMargins(MARGIN, MARGIN, MARGIN, MARGIN);
        filename = outputDir.resolve("checklists.pdf");
        FileOutputStream out = new FileOutputStream(filename.toFile());
        PdfWriter writer = PdfWriter.getInstance(document, out);
        writer.setPageEvent(new Footer());
        document.open();
    } catch (FileNotFoundException | DocumentException e) {
        document.close();
        throw new GeneratorException(e);
    }
}

From source file:org.jivesoftware.openfire.archive.ConversationUtils.java

License:Open Source License

private ByteArrayOutputStream buildPDFContent(Conversation conversation, Map<String, Font> colorMap) {
    Font roomEvent = FontFactory.getFont(FontFactory.HELVETICA, 12f, Font.ITALIC, new Color(0xFF, 0x00, 0xFF));

    try {/*from   w  w  w  .  j  a v a  2 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());
        document.open();

        Paragraph p = new Paragraph(
                LocaleUtils.getLocalizedString("archive.search.pdf.title", MonitoringConstants.NAME),
                FontFactory.getFont(FontFactory.HELVETICA, 18, Font.BOLD));
        document.add(p);
        document.add(Chunk.NEWLINE);

        ConversationInfo coninfo = new ConversationUtils().getConversationInfo(conversation.getConversationID(),
                false);

        String participantsDetail;
        if (coninfo.getAllParticipants() == null) {
            participantsDetail = coninfo.getParticipant1() + ", " + coninfo.getParticipant2();
        } else {
            participantsDetail = String.valueOf(coninfo.getAllParticipants().length);
        }

        Paragraph chapterTitle = new Paragraph(
                LocaleUtils.getLocalizedString("archive.search.pdf.participants", MonitoringConstants.NAME)
                        + " " + participantsDetail,
                FontFactory.getFont(FontFactory.HELVETICA, 12, Font.BOLD));

        document.add(chapterTitle);

        Paragraph startDate = new Paragraph(
                LocaleUtils.getLocalizedString("archive.search.pdf.startdate", MonitoringConstants.NAME) + " "
                        + coninfo.getDate(),
                FontFactory.getFont(FontFactory.HELVETICA, 12, Font.BOLD));
        document.add(startDate);

        Paragraph duration = new Paragraph(
                LocaleUtils.getLocalizedString("archive.search.pdf.duration", MonitoringConstants.NAME) + " "
                        + coninfo.getDuration(),
                FontFactory.getFont(FontFactory.HELVETICA, 12, Font.BOLD));
        document.add(duration);

        Paragraph messageCount = new Paragraph(
                LocaleUtils.getLocalizedString("archive.search.pdf.messagecount", MonitoringConstants.NAME)
                        + " " + conversation.getMessageCount(),
                FontFactory.getFont(FontFactory.HELVETICA, 12, Font.BOLD));
        document.add(messageCount);
        document.add(Chunk.NEWLINE);

        Paragraph messageParagraph;

        for (ArchivedMessage message : conversation.getMessages()) {
            String time = JiveGlobals.formatTime(message.getSentDate());
            String from = message.getFromJID().getNode();
            if (conversation.getRoom() != null) {
                from = message.getToJID().getResource();
            }
            String body = message.getBody();
            String prefix;
            if (!message.isRoomEvent()) {
                prefix = "[" + time + "] " + from + ":  ";
                Font font = colorMap.get(message.getFromJID().toString());
                if (font == null) {
                    font = colorMap.get(message.getFromJID().toBareJID());
                }
                if (font == null) {
                    font = FontFactory.getFont(FontFactory.HELVETICA, 12f, Font.BOLD, Color.BLACK);
                }
                messageParagraph = new Paragraph(new Chunk(prefix, font));
            } else {
                prefix = "[" + time + "] ";
                messageParagraph = new Paragraph(new Chunk(prefix, roomEvent));
            }
            messageParagraph.add(body);
            messageParagraph.add(" ");
            document.add(messageParagraph);
        }

        document.close();
        return baos;
    } catch (DocumentException e) {
        Log.error("error creating PDF document: " + e.getMessage(), e);
        return null;
    }
}