Example usage for com.lowagie.text HeaderFooter HeaderFooter

List of usage examples for com.lowagie.text HeaderFooter HeaderFooter

Introduction

In this page you can find the example usage for com.lowagie.text HeaderFooter HeaderFooter.

Prototype


public HeaderFooter(Phrase before, boolean numbered) 

Source Link

Document

Constructs a Header-object with a pagenumber at the end.

Usage

From source file:org.drools.verifier.doc.DroolsDocsComponentFactory.java

License:Apache License

public static HeaderFooter createFooter(String packageName) {
    HeaderFooter footer = new HeaderFooter(new Phrase(packageName + "-", HEADER_FOOTER_TEXT), true);
    footer.setBorder(1);//www. jav a  2s .c o  m
    footer.setAlignment(Element.ALIGN_RIGHT);

    return footer;
}

From source file:org.egov.infra.web.displaytag.export.EGovPdfView.java

License:Open Source License

@Override
public void doExport(final OutputStream out) throws JspException {

    try {//  w  ww . j a v  a2 s .c  om
        // Initialize the table with the appropriate number of columns
        initTable();

        // Initialize the Document and register it with PdfWriter listener and the OutputStream
        final Document document = new Document(PageSize.A4.rotate(), 60, 60, 40, 40);
        document.addCreationDate();
        final HeaderFooter footer = new HeaderFooter(new Phrase(TagConstants.TAGNAME_CAPTION, this.smallFont),
                true);
        footer.setBorder(Rectangle.NO_BORDER);
        footer.setAlignment(Element.ALIGN_CENTER);

        // PdfWriter.getInstance(document, out);
        PdfWriter.getInstance(document, out).setPageEvent(new PageNumber());
        // Fill the virtual PDF table with the necessary data
        generatePDFTable();
        document.open();

        // Table table = new Table(this.model.getNumberOfColumns());
        // ItextTableWriter writer = new ItextTableWriter(tablePDF, document);
        // writer.writeTable(this.model, "-1");
        // document.setFooter(footer);
        // document.setHeader(footer);
        document.add(this.tableCaption);
        document.add(this.tablePDF);
        document.close();

    } catch (final Exception e) {

        throw new PdfGenerationException(e);
    }

}

From source file:org.egov.works.web.actions.estimate.EstimatePDFGenerator.java

License:Open Source License

public void generatePDF() {
    try {//from ww w. j  av a2 s .  c o  m
        final Paragraph headerTextPara = new Paragraph(
                new Chunk(headerText, new Font(Font.UNDEFINED, LARGE_FONT, Font.BOLD)));
        String projectCode;
        final String oldEstNo = "";
        HeaderFooter hf;
        headerTextPara.setAlignment(Element.ALIGN_CENTER);
        document.add(headerTextPara);
        document.add(makePara("Executing Department:" + estimate.getExecutingDepartment().getName(),
                Element.ALIGN_LEFT));
        if (estimate.getUserDepartment() != null)
            document.add(
                    makePara("User Department:" + estimate.getUserDepartment().getName(), Element.ALIGN_LEFT));

        final CFinancialYear estimateFinancialYear = estimate.getMultiYearEstimates().get(0).getFinancialYear();
        addZoneYearHeader(estimate, estimateFinancialYear);

        document.add(makePara("Name of Work: " + estimate.getName(), Element.ALIGN_LEFT));
        document.add(makePara("Description: " + estimate.getDescription(), Element.ALIGN_LEFT));

        if (estimate.getProjectCode() != null) {
            projectCode = "Project Code : " + estimate.getProjectCode().getCode();
            document.add(makePara(projectCode, Element.ALIGN_LEFT));
            hf = new HeaderFooter(new Phrase("\t  \t  \t  \t \t \t  \t  \t  \t \t \t  \t  \t  \t \t"
                    + "\t  \t  \t  \t \t\t  \t  \t  \t \t\t  \t  \t  \t \t\t  \t  \t  "
                    + "\t  \t  \t  \t \t\t  \t  \t  \t \t"
                    + headerText.concat("\n")
                            .concat("\t  \t  \t  \t \t \t  \t  \t  \t \t"
                                    + "\t  \t  \t  \t \t\t  \t  \t  \t \t\t  \t  \t  \t \t\t  \t  \t  "
                                    + "\t  \t  \t  \t \t\t  \t  \t  \t \t ABSTRACT ESTIMATE")
                            .concat("\n\n").concat("Name of Work: " + estimate.getName()).concat("\n")
                            .concat("Description: " + estimate.getDescription()).concat("\n")
                            .concat("Estimate Number: " + estimate.getEstimateNumber()).concat(oldEstNo)
                            .concat("\n").concat(projectCode)),
                    false);
        } else
            hf = new HeaderFooter(new Phrase("\t  \t  \t  \t \t \t  \t  \t  \t \t \t  \t  \t  \t \t"
                    + "\t  \t  \t  \t \t\t  \t  \t  \t \t\t  \t  \t  \t \t\t  \t  \t  "
                    + "\t  \t  \t  \t \t\t  \t  \t  \t \t"
                    + headerText.concat("\n")
                            .concat("\t  \t  \t  \t \t \t  \t  \t  \t \t"
                                    + "\t  \t  \t  \t \t\t  \t  \t  \t \t\t  \t  \t  \t \t\t  \t  \t  "
                                    + "\t  \t  \t  \t \t\t  \t  \t  \t \t ABSTRACT ESTIMATE")
                            .concat("\n\n").concat("Name of Work: " + estimate.getName()).concat("\n")
                            .concat("Description: " + estimate.getDescription()).concat("\n")
                            .concat("Estimate Number: " + estimate.getEstimateNumber()).concat(oldEstNo)),
                    false);

        hf.disableBorderSide(Rectangle.TOP);
        hf.disableBorderSide(Rectangle.BOTTOM);
        hf.setLeft(Element.ALIGN_LEFT);
        document.setHeader(hf);
        final PdfPTable overheadsTable = createOverheadsTable(estimate);
        document.add(spacer());
        document.add(overheadsTable);
        document.add(spacer());
        final PdfPTable multiyearTable = createMultiYearTable(estimate);
        document.add(makePara("Year-wise Estimate"));
        document.add(spacer());
        document.add(multiyearTable);
        document.add(spacer());
        document.add(makePara("Estimate Created By: " + estimate.getCreatedBy().getName()));
        document.add(spacer());
        document.add(spacer());
        document.add(makePara("Checked By: "));
        document.newPage();
        addZoneYearHeaderWithOutEstimateNo(estimate, estimateFinancialYear);
        document.add(createActivitiesTable(estimate));
        document.add(spacer());

        final PdfPTable approvaldetailsTable = createApprovalDetailsTable(estimate);
        // TODO:Fixme - commented final out workflow history final details since ordering final of approval is final not
        // getting final listed properly
        /*
         * if (approvaldetailsTable.getRows().size() != 1) { document.add(makePara("Approval Details"));
         * document.add(spacer()); document.add(approvaldetailsTable); }
         */

        final String appropriationNumber = abstractEstimateService
                .getLatestEstimateAppropriationNumber(estimate);

        if (isSkipBudgetCheck()) {
            final PdfPTable depositWorksAppropriationTable = createDepositAppropriationTable(estimate,
                    appropriationNumber);
            if (depositWorksAppropriationTable.getRows().size() != 1)
                if (appropriationNumber != null) {
                    document.newPage();
                    document.add(spacer());
                    document.add(makePara("Deposit Code Appropriation Details"));
                    document.add(spacer());
                    document.add(depositWorksAppropriationTable);
                }
        } else {
            final PdfPTable BudgetaryAppropriationTable = createBudgetaryAppropriationTable(estimate,
                    appropriationNumber);
            final String estimateNumber = estimate.getEstimateNumber();
            if (BudgetaryAppropriationTable.getRows().size() != 1)
                if (!getBudgetDetailUsage(estimateNumber).isEmpty() && appropriationNumber != null) {
                    document.newPage();
                    document.add(spacer());
                    document.add(makePara("Budgetary Appropriation"));
                    document.add(spacer());
                    document.add(BudgetaryAppropriationTable);
                }
        }

        document.newPage();
        document.add(spacer());
        document.add(makePara(
                "EXECUTIVE ENGINEER'S OFFICE,  ZONE.......................................................................",
                Element.ALIGN_LEFT));
        document.add(spacer());
        document.add(makePara(
                "Est No.                                                Unit:                                                 Dept.",
                Element.ALIGN_LEFT));
        document.add(spacer());
        final Paragraph budgetheadTextPara = new Paragraph(
                new Chunk("BUDGET HEAD", new Font(Font.UNDEFINED, LARGE_FONT, Font.BOLD)));
        budgetheadTextPara.setAlignment(Element.ALIGN_CENTER);
        document.add(budgetheadTextPara);
        document.add(spacer());
        document.add(makePara("____________________________________________________________________________",
                Element.ALIGN_LEFT));
        document.add(makePara("Rs.                                            ", Element.ALIGN_LEFT));
        document.add(makePara("____________________________________________________________________________",
                Element.ALIGN_LEFT));
        document.add(makePara("Works:                                          ", Element.ALIGN_LEFT));
        document.add(spacer());
        document.add(spacer());
        final Paragraph memoTextPara = new Paragraph(
                new Chunk("MEMO", new Font(Font.UNDEFINED, LARGE_FONT, Font.BOLD)));
        memoTextPara.setAlignment(Element.ALIGN_CENTER);
        document.add(memoTextPara);
        document.add(makePara("Budget Grant                               ", Element.ALIGN_LEFT));
        document.add(makePara("Amount Appropriated:__________________________________________________________",
                Element.ALIGN_LEFT));
        document.add(makePara("Balance on Hand:                                ", Element.ALIGN_LEFT));
        document.add(
                makePara("Amount of this estimate_________________________________________________________",
                        Element.ALIGN_LEFT));
        document.add(makePara("Balance forward_______________________________________________________________",
                Element.ALIGN_LEFT));
        document.add(
                makePara("Submitted for favour of sanction                           ", Element.ALIGN_LEFT));
        document.add(spacer());
        document.add(spacer());
        document.add(
                makePara("A.E.E.Unit " + space1 + "\t  \t  \t  \t \t \t  \t  \t  \t \t \t \t \t \t \t \t \t \t"
                        + "Exe.Eng.Zone.....................", Element.ALIGN_LEFT));
        document.add(spacer());
        document.add(makePara("Sanctioned", Element.ALIGN_CENTER));
        document.add(spacer());
        document.add(spacer());
        document.add(makePara("DATE:" + space1
                + "\t  \t  \t  \t \t \t  \t  \t  \t \t \t \t\t  \t  \t  \t \t \t  \t  \t  \t \t \t \t"
                + "Asst.Commissioner Zone...............", Element.ALIGN_LEFT));
        document.add(spacer());
        document.add(makePara(
                space1 + "\t  \t  \t  \t \t \t  \t  \t  \t \t \t \t\t  \t  \t  \t \t \t  \t  \t  \t \t \t \t"
                        + "APPROPRIATION No.",
                Element.ALIGN_LEFT));
        document.add(makePara(space1 + "\t  \t  \t  \t \t \t  \t  \t  \t \t \t \t"
                + "\t  \t  \t  \t \t \t  \t  \t  \t \t \t \t \t \t \t" + "Date:", Element.ALIGN_LEFT));

        // WF for signature -----
        if (approvaldetailsTable.getRows().size() != 1)
            if (shouldShowApprovalNumber) {
                document.resetHeader();
                document.newPage();
                document.add(
                        makePara("\t  \t  \t  \t \t \t  \t  \t  \t \t \t  \t  \t  \t \t"
                                + "\t  \t  \t  \t \t\t  \t  \t  \t \t\t  \t  \t  \t \t\t  \t  \t  "
                                + "\t  \t  \t  \t \t\t  \t  \t  \t \t"
                                + headerText.concat("\n").concat("\t  \t  \t  \t \t \t  \t  \t  \t \t"
                                        + "\t  \t  \t  \t \t\t  \t  \t  \t \t\t  \t  \t  \t \t\t  \t  \t  "
                                        + "\t  \t  \t  \t \t\t  \t  \t  \t \t ABSTRACT ESTIMATE")
                                        .concat("\n\n")));
                document.add(
                        makePara(
                                "File Current Number :" + space1
                                        + "\t  \t  \t  \t \t \t  \t  \t  \t \t \t \t \t   " + "Date: \t \t",
                                Element.ALIGN_LEFT));
                document.add(makePara(space1
                        + "\t  \t  \t  \t \t \t  \t  \t  \t \t \t \t\t  \t  \t  \t \t \t \t \t  \t  \t  \t "
                        + "Department : ", Element.ALIGN_LEFT));
                document.add(spacer());
                final Paragraph headingPara1 = new Paragraph(
                        new Chunk("NOTE FOR ADMINISTRATIVE SANCTION AS PER RULE 78 OF ",
                                new Font(Font.UNDEFINED, LARGE_FONT, Font.BOLD)));
                headingPara1.setAlignment(Element.ALIGN_CENTER);
                document.add(headingPara1);
                final Paragraph headingPara2 = new Paragraph(
                        new Chunk("MCMC ACT 1919 ", new Font(Font.UNDEFINED, LARGE_FONT, Font.BOLD)));
                headingPara2.setAlignment(Element.ALIGN_CENTER);
                document.add(headingPara2);

                document.add(spacer());
                final PdfPTable estimateDetailsTable1 = createEstimateDetailsTable1(estimate);
                document.add(estimateDetailsTable1);
                final PdfPTable budgetDetailsTableFourCols = createBudgetDetailsForEstimateTable(estimate);
                document.add(budgetDetailsTableFourCols);
                final PdfPTable estimateDetailsTable2 = createBalanceAmtCalculationTable(estimate);
                document.add(estimateDetailsTable2);
                document.add(spacer());
                final Paragraph endTextPara = new Paragraph(
                        new Chunk("** END **", new Font(Font.UNDEFINED, LARGE_FONT, Font.BOLD)));
                endTextPara.setAlignment(Element.ALIGN_CENTER);
                document.add(endTextPara);
            }

        document.close();
    } catch (final DocumentException e) {
        throw new ApplicationRuntimeException("estimate.pdf.error", e);
    }
}

From source file:org.gtdfree.addons.PDFExportAddOn.java

License:Open Source License

@Override
public void export(GTDModel model, ActionsCollection collection, OutputStream out,
        ExportAddOn.ExportOrder order, FileFilter ff, boolean compact) throws Exception {

    fontSelector = new FontSelector();
    fontSelectorB = new FontSelector();
    fontSelectorB2 = new FontSelector();
    fontSelectorB4 = new FontSelector();

    baseFont = fontModel.getBaseFont();// ww  w .ja  v a 2s .  co m

    for (BaseFont bf : fontModel.getFonts()) {
        fontSelector.addFont(new Font(bf, baseFontSize));
        fontSelectorB.addFont(new Font(bf, baseFontSize, Font.BOLD));
        fontSelectorB2.addFont(new Font(bf, baseFontSize + 2, Font.BOLD));
        fontSelectorB4.addFont(new Font(bf, baseFontSize + 4, Font.BOLD));
    }

    boolean emptyH2 = false;
    boolean emptyH3 = false;

    PdfPTable actionTable = null;

    Document doc = new Document();

    if (sizeSet) {
        doc.setPageSize(pageSize);
    }
    if (marginSet) {
        doc.setMargins(marginLeft, marginRight, marginTop, marginBottom);
    }

    //System.out.println("PDF size "+doc.getPageSize().toString());
    //System.out.println("PDF m "+marginLeft+" "+marginRight+" "+marginTop+" "+marginBottom);

    @SuppressWarnings("unused")
    PdfWriter pw = PdfWriter.getInstance(doc, out);

    doc.addCreationDate();
    doc.addTitle("GTD-Free PDF");
    doc.addSubject("GTD-Free data exported as PDF");

    HeaderFooter footer = new HeaderFooter(newParagraph(), true);
    footer.setAlignment(HeaderFooter.ALIGN_CENTER);
    footer.setBorder(HeaderFooter.TOP);
    doc.setFooter(footer);

    doc.open();

    Phrase ch = newTitle("GTD-Free Data");
    Paragraph p = new Paragraph(ch);
    p.setAlignment(Paragraph.ALIGN_CENTER);

    PdfPTable t = new PdfPTable(1);
    t.setWidthPercentage(100f);
    PdfPCell c = newCell(p);
    c.setBorder(Table.BOTTOM);
    c.setBorderWidth(2.5f);
    c.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
    c.setPadding(5f);
    t.addCell(c);
    doc.add(t);

    Iterator<Object> it = collection.iterator(order);

    while (it.hasNext()) {
        Object o = it.next();

        if (o == ActionsCollection.ACTIONS_WITHOUT_PROJECT) {

            if (order == ExportAddOn.ExportOrder.FoldersProjectsActions) {

                doc.add(newSubSection(ActionsCollection.ACTIONS_WITHOUT_PROJECT));

                emptyH2 = false;
                emptyH3 = true;
            } else {

                doc.add(newSection(ActionsCollection.ACTIONS_WITHOUT_PROJECT));

                emptyH2 = true;
                emptyH3 = false;
            }

            continue;
        }

        if (o instanceof Folder) {

            Folder f = (Folder) o;

            if (actionTable != null) {
                doc.add(actionTable);
                actionTable = null;
            }

            if (f.isProject()) {

                if (order == ExportAddOn.ExportOrder.ProjectsActions
                        || order == ExportAddOn.ExportOrder.ProjectsFoldersActions) {

                    if (emptyH2 || emptyH3) {
                        p = newParagraph(NONE_DOT);
                        doc.add(p);
                    }

                    doc.add(newSection(f.getName()));

                    if (compact) {
                        if (f.getDescription() != null && f.getDescription().length() > 0) {
                            p = newParagraph(f.getDescription());
                            p.setIndentationLeft(10f);
                            p.setIndentationRight(10f);
                            doc.add(p);
                        }
                    } else {
                        t = new PdfPTable(2);
                        t.setKeepTogether(true);
                        t.setSpacingBefore(5f);
                        t.setWidthPercentage(66f);
                        t.setWidths(new float[] { 0.33f, 0.66f });

                        c = newCell("ID");
                        t.addCell(c);
                        c = newCell(newStrongParagraph(String.valueOf(f.getId())));
                        t.addCell(c);
                        c = newCell("Type");
                        t.addCell(c);
                        c = newCell(newStrongParagraph("Project"));
                        t.addCell(c);
                        c = newCell("Open");
                        t.addCell(c);
                        c = newCell(newStrongParagraph(String.valueOf(f.getOpenCount())));
                        t.addCell(c);
                        c = newCell("All");
                        t.addCell(c);
                        c = newCell(newStrongParagraph(String.valueOf(f.size())));
                        t.addCell(c);
                        c = newCell("Description");
                        t.addCell(c);
                        c = newDescriptionCell(f.getDescription());
                        t.addCell(c);

                        doc.add(t);
                    }

                    emptyH2 = true;
                    emptyH3 = false;

                } else {

                    if (emptyH3) {
                        p = newParagraph(NONE_DOT);
                        doc.add(p);
                    }

                    doc.add(newSubSection("Project:" + " " + f.getName()));

                    emptyH2 = false;
                    emptyH3 = true;
                }

                continue;

            }
            if (order == ExportAddOn.ExportOrder.FoldersActions
                    || order == ExportAddOn.ExportOrder.FoldersProjectsActions) {

                if (emptyH2 || emptyH3) {
                    p = newParagraph(NONE_DOT);
                    doc.add(p);
                }

                doc.add(newSection(f.getName()));

                if (compact) {
                    if (f.getDescription() != null && f.getDescription().length() > 0) {
                        p = newParagraph(f.getDescription());
                        p.setIndentationLeft(10f);
                        p.setIndentationRight(10f);
                        doc.add(p);
                    }
                } else {

                    t = new PdfPTable(2);
                    t.setKeepTogether(true);
                    t.setSpacingBefore(5f);
                    t.setWidthPercentage(66f);
                    t.setWidths(new float[] { 0.33f, 0.66f });

                    c = newCell("ID");
                    t.addCell(c);
                    c = newCell(newStrongParagraph(String.valueOf(f.getId())));
                    t.addCell(c);

                    String type = "";
                    if (f.isAction()) {
                        type = "Action list";
                    } else if (f.isInBucket()) {
                        type = "In-Bucket";
                    } else if (f.isQueue()) {
                        type = "Next action queue";
                    } else if (f.isReference()) {
                        type = "Reference list";
                    } else if (f.isSomeday()) {
                        type = "Someday/Maybe list";
                    } else if (f.isBuildIn()) {
                        type = "Default list";
                    }

                    c = newCell("Type");
                    t.addCell(c);
                    c = newCell(newStrongParagraph(type));
                    t.addCell(c);
                    c = newCell("Open");
                    t.addCell(c);
                    c = newCell(newStrongParagraph(String.valueOf(f.getOpenCount())));
                    t.addCell(c);
                    c = newCell("All");
                    t.addCell(c);
                    c = newCell(newStrongParagraph(String.valueOf(f.size())));
                    t.addCell(c);
                    c = newCell("Description");
                    t.addCell(c);
                    c = newDescriptionCell(f.getDescription());
                    t.addCell(c);

                    doc.add(t);
                }

                emptyH2 = true;
                emptyH3 = false;

            } else {

                if (emptyH3) {
                    p = newParagraph(NONE_DOT);
                    doc.add(p);
                }

                doc.add(newSubSection("List:" + " " + f.getName()));

                emptyH2 = false;
                emptyH3 = true;

            }

            continue;

        }

        if (o instanceof Action) {
            emptyH2 = false;
            emptyH3 = false;

            Action a = (Action) o;

            if (compact) {

                if (actionTable == null) {
                    actionTable = new PdfPTable(5);
                    actionTable.setWidthPercentage(100f);
                    actionTable.setHeaderRows(1);
                    actionTable.setSpacingBefore(5f);
                    c = newHeaderCell("ID");
                    actionTable.addCell(c);
                    c = newHeaderCell("Pri.");
                    actionTable.addCell(c);
                    c = newHeaderCell("Description");
                    actionTable.addCell(c);
                    c = newHeaderCell("Reminder");
                    actionTable.addCell(c);
                    c = newHeaderCell(CHECK_RESOLVED);
                    actionTable.addCell(c);

                    float width = doc.getPageSize().getWidth() - doc.getPageSize().getBorderWidthLeft()
                            - doc.getPageSize().getBorderWidthRight();
                    int i = model.getLastActionID();
                    float step = baseFontSize - 1;
                    int steps = (int) Math.floor(Math.log10(i)) + 1;
                    // ID column
                    float col1 = 8 + steps * step;
                    // Priority column
                    float col2 = 4 + 3 * (baseFontSize + 4);
                    // Reminder column
                    float col4 = 10 + step * 11;
                    // Resolved column
                    float col5 = 8 + baseFontSize;
                    // Description column
                    float col3 = width - col1 - col2 - col4 - col5;
                    actionTable.setWidths(new float[] { col1, col2, col3, col4, col5 });

                }

                addSingleActionRow(a, actionTable);

            } else {
                addSingleActionTable(model, doc, a);
            }
        }

    }

    if (actionTable != null) {
        doc.add(actionTable);
        actionTable = null;
    }
    if (emptyH2 || emptyH3) {

        p = newParagraph(NONE_DOT);
        doc.add(p);
    }

    //w.writeCharacters("Exported: "+ApplicationHelper.toISODateTimeString(new Date()));

    doc.close();
}

From source file:org.jboss.as.quickstarts.ejbinwar.ejb.GreeterEJB.java

License:Apache License

public ByteArrayOutputStream generatePDFDocumentBytes(String selectedTariff) throws DocumentException {
    java.util.Set<String> users = getRestUsers(selectedTariff);

    Document doc = new Document();

    ByteArrayOutputStream baosPDF = new ByteArrayOutputStream();
    PdfWriter docWriter = null;//w ww .  j  ava2  s  . c  o m

    try {
        docWriter = PdfWriter.getInstance(doc, baosPDF);

        doc.addAuthor(this.getClass().getName());
        doc.addCreationDate();
        doc.addProducer();
        doc.addCreator(this.getClass().getName());
        doc.addTitle(selectedTariff + " clients");
        doc.addKeywords("pdf, itext, Java, ecare, http");

        doc.setPageSize(PageSize.LETTER);

        HeaderFooter footer = new HeaderFooter(new Phrase("E-Care report"), false);

        doc.setFooter(footer);

        doc.open();

        doc.add(new Paragraph(selectedTariff + " clients"));
        doc.add(new Paragraph("\n"));
        doc.add(new Paragraph("\n"));

        PdfPTable table = new PdfPTable(4); // 3 columns.

        PdfPCell cell1 = new PdfPCell(new Paragraph("Name"));
        PdfPCell cell2 = new PdfPCell(new Paragraph("Surname"));
        PdfPCell cell3 = new PdfPCell(new Paragraph("Address"));
        PdfPCell cell4 = new PdfPCell(new Paragraph("Email"));

        table.addCell(cell1);
        table.addCell(cell2);
        table.addCell(cell3);
        table.addCell(cell4);

        for (Iterator<String> it = users.iterator(); it.hasNext();) {
            String user = it.next();

            table.addCell(new PdfPCell(new Paragraph(user.split(" ")[0])));
            table.addCell(new PdfPCell(new Paragraph(user.split(" ")[1])));
            table.addCell(new PdfPCell(new Paragraph(user.split(" ")[2])));
            table.addCell(new PdfPCell(new Paragraph(user.split(" ")[3])));
        }

        doc.add(table);

    } catch (DocumentException dex) {
        baosPDF.reset();
        throw dex;
    } finally {
        if (doc != null) {
            doc.close();
        }
        if (docWriter != null) {
            docWriter.close();
        }
    }

    if (baosPDF.size() < 1) {
        throw new DocumentException("document has " + baosPDF.size() + " bytes");
    }
    return baosPDF;

}

From source file:org.jsondoc.springmvc.pdf.PdfExportView.java

License:Open Source License

public File getPdfFile(String filename) {
    try {/*from ww  w  . j a  v  a2 s .  c o m*/
        File file = new File(filename + "-v" + jsonDoc.getVersion() + FILE_EXTENSION);
        FileOutputStream fileout = new FileOutputStream(file);
        Document document = new Document();
        PdfWriter.getInstance(document, fileout);

        // Header
        HeaderFooter header = new HeaderFooter(new Phrase("Copyright "
                + Calendar.getInstance().get(Calendar.YEAR) + " Paybay Networks - All rights reserved"), false);
        header.setBorder(Rectangle.NO_BORDER);
        header.setAlignment(Element.ALIGN_LEFT);
        document.setHeader(header);

        // Footer
        HeaderFooter footer = new HeaderFooter(new Phrase("Page "), true);
        footer.setBorder(Rectangle.NO_BORDER);
        footer.setAlignment(Element.ALIGN_CENTER);
        document.setFooter(footer);

        document.open();

        //init documentation
        apiDocs = buildApiDocList();
        apiMethodDocs = buildApiMethodDocList(apiDocs);

        Phrase baseUrl = new Phrase("Base url: " + jsonDoc.getBasePath());
        document.add(baseUrl);
        document.add(Chunk.NEWLINE);
        document.add(Chunk.NEWLINE);

        int pos = 1;
        for (ApiMethodDoc apiMethodDoc : apiMethodDocs) {
            Phrase phrase = new Phrase(/*"Description: " + */apiMethodDoc.getDescription());
            document.add(phrase);
            document.add(Chunk.NEWLINE);

            PdfPTable table = new PdfPTable(2);
            table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_LEFT);
            table.getDefaultCell().setBorder(Rectangle.NO_BORDER);
            table.setWidthPercentage(100);

            table.setWidths(new int[] { 50, 200 });

            // HEADER CELL START TABLE
            table.addCell(ITextUtils.getHeaderCell("URL"));
            table.addCell(ITextUtils.getHeaderCell("<baseUrl> " + apiMethodDoc.getPath()));
            table.completeRow();

            // FIRST CELL
            table.addCell(ITextUtils.getCell("Http Method", 0));
            table.addCell(ITextUtils.getCell(apiMethodDoc.getVerb().name(), pos));
            pos++;
            table.completeRow();

            // PRODUCES
            if (!apiMethodDoc.getProduces().isEmpty()) {
                table.addCell(ITextUtils.getCell("Produces", 0));
                table.addCell(ITextUtils.getCell(buildApiMethodProduces(apiMethodDoc), pos));
                pos++;
                table.completeRow();
            }

            // CONSUMES
            if (!apiMethodDoc.getConsumes().isEmpty()) {
                table.addCell(ITextUtils.getCell("Consumes", 0));
                table.addCell(ITextUtils.getCell(buildApiMethodConsumes(apiMethodDoc), pos));
                pos++;
                table.completeRow();
            }

            // HEADERS
            if (!apiMethodDoc.getHeaders().isEmpty()) {
                table.addCell(ITextUtils.getCell("Request headers", 0));

                PdfPTable pathParamsTable = new PdfPTable(3);
                pathParamsTable.setWidths(new int[] { 30, 20, 40 });

                pathParamsTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_LEFT);
                pathParamsTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);

                for (ApiHeaderDoc apiHeaderDoc : apiMethodDoc.getHeaders()) {
                    PdfPCell boldCell = new PdfPCell();
                    Font fontbold = FontFactory.getFont("Times-Roman", 12, Font.BOLD);
                    boldCell.setPhrase(new Phrase(apiHeaderDoc.getName(), fontbold));
                    boldCell.getPhrase().setFont(new Font(Font.BOLD));
                    boldCell.setBorder(Rectangle.NO_BORDER);
                    pathParamsTable.addCell(boldCell);

                    PdfPCell paramCell = new PdfPCell();

                    StringBuilder builder = new StringBuilder();

                    for (String value : apiHeaderDoc.getAllowedvalues())
                        builder.append(value).append(", ");

                    paramCell.setPhrase(new Phrase("Allowed values: " + builder.toString()));
                    paramCell.setBorder(Rectangle.NO_BORDER);

                    pathParamsTable.addCell(paramCell);

                    paramCell.setPhrase(new Phrase(apiHeaderDoc.getDescription()));

                    pathParamsTable.addCell(paramCell);
                    pathParamsTable.completeRow();
                }

                PdfPCell bluBorderCell = new PdfPCell(pathParamsTable);
                bluBorderCell.setBorder(Rectangle.NO_BORDER);
                bluBorderCell.setBorderWidthRight(1f);
                bluBorderCell.setBorderColorRight(Colors.CELL_BORDER_COLOR);

                table.addCell(ITextUtils.setOddEvenStyle(bluBorderCell, pos));
                pos++;
                table.completeRow();
            }

            // PATH PARAMS
            if (!apiMethodDoc.getPathparameters().isEmpty()) {
                table.addCell(ITextUtils.getCell("Path params", 0));

                PdfPTable pathParamsTable = new PdfPTable(3);
                pathParamsTable.setWidths(new int[] { 30, 15, 40 });

                pathParamsTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_LEFT);
                pathParamsTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);

                for (ApiParamDoc apiParamDoc : apiMethodDoc.getPathparameters()) {
                    PdfPCell boldCell = new PdfPCell();
                    Font fontbold = FontFactory.getFont("Times-Roman", 12, Font.BOLD);
                    boldCell.setPhrase(new Phrase(apiParamDoc.getName(), fontbold));
                    boldCell.getPhrase().setFont(new Font(Font.BOLD));
                    boldCell.setBorder(Rectangle.NO_BORDER);
                    pathParamsTable.addCell(boldCell);

                    PdfPCell paramCell = new PdfPCell();
                    paramCell.setPhrase(new Phrase(apiParamDoc.getJsondocType().getOneLineText()));
                    paramCell.setBorder(Rectangle.NO_BORDER);

                    pathParamsTable.addCell(paramCell);

                    paramCell.setPhrase(new Phrase(apiParamDoc.getDescription()));

                    pathParamsTable.addCell(paramCell);
                    pathParamsTable.completeRow();
                }

                PdfPCell bluBorderCell = new PdfPCell(pathParamsTable);
                bluBorderCell.setBorder(Rectangle.NO_BORDER);
                bluBorderCell.setBorderWidthRight(1f);
                bluBorderCell.setBorderColorRight(Colors.CELL_BORDER_COLOR);

                table.addCell(ITextUtils.setOddEvenStyle(bluBorderCell, pos));
                pos++;
                table.completeRow();
            }

            // QUERY PARAMS
            if (!apiMethodDoc.getQueryparameters().isEmpty()) {
                table.addCell(ITextUtils.getCell("Query params", 0));

                PdfPTable queryParamsTable = new PdfPTable(3);
                queryParamsTable.setWidths(new int[] { 30, 15, 40 });

                queryParamsTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_LEFT);
                queryParamsTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);

                for (ApiParamDoc apiParamDoc : apiMethodDoc.getQueryparameters()) {
                    PdfPCell boldCell = new PdfPCell();
                    Font fontbold = FontFactory.getFont("Times-Roman", 12, Font.BOLD);
                    boldCell.setPhrase(new Phrase(apiParamDoc.getName(), fontbold));
                    boldCell.getPhrase().setFont(new Font(Font.BOLD));
                    boldCell.setBorder(Rectangle.NO_BORDER);
                    queryParamsTable.addCell(boldCell);

                    PdfPCell paramCell = new PdfPCell();
                    paramCell.setPhrase(new Phrase(apiParamDoc.getJsondocType().getOneLineText()));
                    paramCell.setBorder(Rectangle.NO_BORDER);

                    queryParamsTable.addCell(paramCell);

                    paramCell.setPhrase(new Phrase(
                            apiParamDoc.getDescription() + ", mandatory: " + apiParamDoc.getRequired()));

                    queryParamsTable.addCell(paramCell);
                    queryParamsTable.completeRow();
                }

                PdfPCell bluBorderCell = new PdfPCell(queryParamsTable);
                bluBorderCell.setBorder(Rectangle.NO_BORDER);
                bluBorderCell.setBorderWidthRight(1f);
                bluBorderCell.setBorderColorRight(Colors.CELL_BORDER_COLOR);

                table.addCell(ITextUtils.setOddEvenStyle(bluBorderCell, pos));
                pos++;
                table.completeRow();
            }

            // BODY OBJECT
            if (null != apiMethodDoc.getBodyobject()) {
                table.addCell(ITextUtils.getCell("Body object:", 0));
                String jsonObject = buildJsonFromTemplate(apiMethodDoc.getBodyobject().getJsondocTemplate());
                table.addCell(ITextUtils.getCell(jsonObject, pos));
                pos++;
                table.completeRow();
            }

            // RESPONSE OBJECT
            table.addCell(ITextUtils.getCell("Json response:", 0));
            table.addCell(
                    ITextUtils.getCell(apiMethodDoc.getResponse().getJsondocType().getOneLineText(), pos));
            pos++;
            table.completeRow();

            // RESPONSE STATUS CODE
            table.addCell(ITextUtils.getCell("Status code:", 0));
            table.addCell(ITextUtils.getCell(apiMethodDoc.getResponsestatuscode(), pos));
            pos++;
            table.completeRow();

            table.setSpacingAfter(10f);
            table.setSpacingBefore(5f);
            document.add(table);
        }

        document.close();
        return file;
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (DocumentException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:org.kuali.coeus.common.impl.print.PrintingServiceImpl.java

License:Open Source License

/**
 * @param pdfBytesList List containing the PDF data bytes
 * @param bookmarksList List of bookmarks corresponding to the PDF bytes.
 * @return/*w  ww .j a v a2  s.  c om*/
 * @throws PrintingException
 */

protected byte[] mergePdfBytes(List<byte[]> pdfBytesList, List<String> bookmarksList,
        boolean headerFooterRequired) throws PrintingException {
    Document document = null;
    PdfWriter writer = null;
    ByteArrayOutputStream mergedPdfReport = new ByteArrayOutputStream();
    int totalNumOfPages = 0;
    PdfReader[] pdfReaderArr = new PdfReader[pdfBytesList.size()];
    int pdfReaderCount = 0;
    for (byte[] fileBytes : pdfBytesList) {
        LOG.debug("File Size " + fileBytes.length + " For " + bookmarksList.get(pdfReaderCount));
        PdfReader reader = null;
        try {
            reader = new PdfReader(fileBytes);
            pdfReaderArr[pdfReaderCount] = reader;
            pdfReaderCount = pdfReaderCount + 1;
            totalNumOfPages += reader.getNumberOfPages();
        } catch (IOException e) {
            LOG.error(e.getMessage(), e);
        }
    }
    HeaderFooter footer = null;
    if (headerFooterRequired) {
        Calendar calendar = dateTimeService.getCurrentCalendar();
        String dateString = formateCalendar(calendar);
        StringBuilder footerPhStr = new StringBuilder();
        footerPhStr.append(" of ");
        footerPhStr.append(totalNumOfPages);
        footerPhStr.append(getWhitespaceString(WHITESPACE_LENGTH_76));
        footerPhStr.append(getWhitespaceString(WHITESPACE_LENGTH_76));
        footerPhStr.append(getWhitespaceString(WHITESPACE_LENGTH_60));
        footerPhStr.append(dateString);
        Font font = FontFactory.getFont(FontFactory.TIMES, 8, Font.NORMAL, Color.BLACK);
        Phrase beforePhrase = new Phrase("Page ", font);
        Phrase afterPhrase = new Phrase(footerPhStr.toString(), font);
        footer = new HeaderFooter(beforePhrase, afterPhrase);
        footer.setAlignment(Element.ALIGN_BASELINE);
        footer.setBorderWidth(0f);
    }
    for (int count = 0; count < pdfReaderArr.length; count++) {
        PdfReader reader = pdfReaderArr[count];
        int nop;
        if (reader == null) {
            LOG.debug("Empty PDF byetes found for " + bookmarksList.get(count));
            continue;
        } else {
            nop = reader.getNumberOfPages();
        }

        if (count == 0) {
            document = nop > 0 ? new com.lowagie.text.Document(reader.getPageSizeWithRotation(1))
                    : new com.lowagie.text.Document();
            try {
                writer = PdfWriter.getInstance(document, mergedPdfReport);
            } catch (DocumentException e) {
                LOG.error(e.getMessage(), e);
                throw new PrintingException(e.getMessage(), e);
            }
            if (footer != null) {
                document.setFooter(footer);
            }
            // writer.setPageEvent(new Watermark()); // add watermark object here
            document.open();
        }

        PdfContentByte cb = writer.getDirectContent();
        int pageCount = 0;
        while (pageCount < nop) {
            document.setPageSize(reader.getPageSize(++pageCount));
            document.newPage();
            if (footer != null) {
                document.setFooter(footer);
            }
            PdfImportedPage page = writer.getImportedPage(reader, pageCount);

            cb.addTemplate(page, 1, 0, 0, 1, 0, 0);

            PdfOutline root = cb.getRootOutline();
            if (pageCount == 1) {
                String pageName = bookmarksList.get(count);
                cb.addOutline(new PdfOutline(root, new PdfDestination(PdfDestination.FITH), pageName),
                        pageName);
            }
        }
    }
    if (document != null) {
        try {
            document.close();
            return mergedPdfReport.toByteArray();
        } catch (Exception e) {
            LOG.error("Exception occured because the generated PDF document has no pages", e);
        }
    }
    return null;
}

From source file:org.kuali.coeus.s2sgen.impl.print.S2SPrintingServiceImpl.java

License:Educational Community License

/**
 * @param pdfBytesList List containing the PDF data bytes
 * @param bookmarksList List of bookmarks corresponding to the PDF bytes.
 *///from  w w  w.  ja va  2 s . co  m
protected byte[] mergePdfBytes(List<byte[]> pdfBytesList, List<String> bookmarksList,
        boolean headerFooterRequired) {
    Document document = null;
    PdfWriter writer = null;
    ByteArrayOutputStream mergedPdfReport = new ByteArrayOutputStream();
    int totalNumOfPages = 0;
    PdfReader[] pdfReaderArr = new PdfReader[pdfBytesList.size()];
    int pdfReaderCount = 0;
    for (byte[] fileBytes : pdfBytesList) {
        LOG.debug("File Size " + fileBytes.length + " For " + bookmarksList.get(pdfReaderCount));
        PdfReader reader = null;
        try {
            reader = new PdfReader(fileBytes);
            pdfReaderArr[pdfReaderCount] = reader;
            pdfReaderCount = pdfReaderCount + 1;
            totalNumOfPages += reader.getNumberOfPages();
        } catch (IOException e) {
            LOG.error(e.getMessage(), e);
        }
    }
    HeaderFooter footer = null;
    if (headerFooterRequired) {
        Calendar calendar = Calendar.getInstance();
        String dateString = formateCalendar(calendar);
        StringBuilder footerPhStr = new StringBuilder();
        footerPhStr.append(" of ");
        footerPhStr.append(totalNumOfPages);
        footerPhStr.append(getWhitespaceString(WHITESPACE_LENGTH_76));
        footerPhStr.append(getWhitespaceString(WHITESPACE_LENGTH_76));
        footerPhStr.append(getWhitespaceString(WHITESPACE_LENGTH_60));
        footerPhStr.append(dateString);
        Font font = FontFactory.getFont(FontFactory.TIMES, 8, Font.NORMAL, Color.BLACK);
        Phrase beforePhrase = new Phrase("Page ", font);
        Phrase afterPhrase = new Phrase(footerPhStr.toString(), font);
        footer = new HeaderFooter(beforePhrase, afterPhrase);
        footer.setAlignment(Element.ALIGN_BASELINE);
        footer.setBorderWidth(0f);
    }
    for (int count = 0; count < pdfReaderArr.length; count++) {
        PdfReader reader = pdfReaderArr[count];
        int nop;
        if (reader == null) {
            LOG.debug("Empty PDF byetes found for " + bookmarksList.get(count));
            continue;
        } else {
            nop = reader.getNumberOfPages();
        }

        if (count == 0) {
            document = nop > 0 ? new Document(reader.getPageSizeWithRotation(1)) : new Document();
            try {
                writer = PdfWriter.getInstance(document, mergedPdfReport);
            } catch (DocumentException e) {
                LOG.error(e.getMessage(), e);
                throw new S2SException(e.getMessage(), e);
            }
            if (footer != null) {
                document.setFooter(footer);
            }
            document.open();
        }

        PdfContentByte cb = writer.getDirectContent();
        int pageCount = 0;
        while (pageCount < nop) {
            document.setPageSize(reader.getPageSize(++pageCount));
            document.newPage();
            if (footer != null) {
                document.setFooter(footer);
            }
            PdfImportedPage page = writer.getImportedPage(reader, pageCount);

            cb.addTemplate(page, 1, 0, 0, 1, 0, 0);

            PdfOutline root = cb.getRootOutline();
            if (pageCount == 1) {
                String pageName = bookmarksList.get(count);
                cb.addOutline(new PdfOutline(root, new PdfDestination(PdfDestination.FITH), pageName),
                        pageName);
            }
        }
    }
    if (document != null) {
        try {
            document.close();
            return mergedPdfReport.toByteArray();
        } catch (Exception e) {
            LOG.error("Exception occured because the generated PDF document has no pages", e);
        }
    }
    return null;
}

From source file:org.kuali.kfs.module.endow.report.util.TransactionSummaryReportPrint.java

License:Educational Community License

/**
 * Generates the report in PDF using iText
 * /*  w w w. ja  v a2 s .  c om*/
 * @param reportRequestHeaderDataHolder
 * @param transactionStatementDataReportHolders
 * @return pdfStream
 */
public ByteArrayOutputStream printTransactionSummaryReport(
        EndowmentReportHeaderDataHolder reportRequestHeaderDataHolder,
        List<TransactionSummaryReportDataHolder> transactionSummaryDataReportHolders, String listKemidsInHeader,
        String reportOption, String summaryTotalsOnly) {
    Document document = new Document();
    document.setPageSize(LETTER_PORTRAIT);
    document.addTitle("Endowment Transaction Summary");

    ByteArrayOutputStream pdfStream = new ByteArrayOutputStream();

    try {
        PdfWriter.getInstance(document, pdfStream);
        document.open();

        // page
        HeaderFooter header = new HeaderFooter(new Phrase(new Date().toString() + "     Page: ", headerFont),
                true);
        header.setBorder(Rectangle.NO_BORDER);
        header.setAlignment(Element.ALIGN_RIGHT);
        header.setPageNumber(0);
        document.setHeader(header);

        // print the report header
        if (printReportHeaderPage(reportRequestHeaderDataHolder, document, listKemidsInHeader)) {
            if (transactionSummaryDataReportHolders != null && transactionSummaryDataReportHolders.size() > 0) {
                if ("Y".equalsIgnoreCase(summaryTotalsOnly)) {
                    printReportBodyBySummaryTotals(transactionSummaryDataReportHolders, document, reportOption);
                } else {
                    printReportBodyByAllTotals(transactionSummaryDataReportHolders, document, reportOption);
                }
            }
        } else {
            LOG.error("Transaction Summary Report Header Error");
        }

        document.close();

    } catch (Exception e) {
        LOG.error("PDF Error: " + e.getMessage());
        return null;
    }

    return pdfStream;
}

From source file:org.kuali.kfs.module.endow.report.util.TrialBalanceReportPrint.java

License:Educational Community License

/**
 * Generates the report in PDF using iText
 * /*w  w  w . j av a2 s  .  co  m*/
 * @param reportRequestHeaderDataHolder
 * @param trialBalanceDataReportHolders
 * @return ByteArrayOutputStream
 */
public ByteArrayOutputStream printTrialBalanceReport(
        EndowmentReportHeaderDataHolder reportRequestHeaderDataHolder,
        List<TrialBalanceReportDataHolder> trialBalanceDataReportHolders, String listKemidsInHeader) {

    final org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(TrialBalanceReportPrint.class);

    Document document = new Document();
    document.setPageSize(LETTER_PORTRAIT);
    document.addTitle("Endowment Trial Balance");

    // get the stream for PDF
    ByteArrayOutputStream pdfStream = new ByteArrayOutputStream();

    try {
        PdfWriter.getInstance(document, pdfStream);
        document.open();

        // page
        HeaderFooter header = new HeaderFooter(new Phrase(new Date().toString() + "     Page: ", headerFont),
                true);
        header.setBorder(Rectangle.NO_BORDER);
        header.setAlignment(Element.ALIGN_RIGHT);
        header.setPageNumber(0);
        document.setHeader(header);

        // print the report header
        if (printReportHeaderPage(reportRequestHeaderDataHolder, document, listKemidsInHeader)) {

            if (trialBalanceDataReportHolders != null && trialBalanceDataReportHolders.size() > 0) {
                document.setPageSize(LETTER_LANDSCAPE);
                document.resetPageCount();
                header.setPageNumber(1);
                document.newPage();
                printTrialBalanceReportBody(trialBalanceDataReportHolders, document);
            } else {
                LOG.error("Trial Balance Report Header Error");
            }
        }

        document.close();

    } catch (Exception e) {
        LOG.error("PDF Error: " + e.getMessage());
        return null;
    }

    return pdfStream;
}