Example usage for com.lowagie.text Document setHeader

List of usage examples for com.lowagie.text Document setHeader

Introduction

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

Prototype


public void setHeader(HeaderFooter header) 

Source Link

Document

Changes the header of this document.

Usage

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

License:Apache License

/**
 * We create a writer that listens to the document and directs a RTF-stream to out
 *
 * @param table// w ww.  java  2 s.  co m
 *           MBasicTable
 * @param document
 *           Document
 * @param out
 *           OutputStream
 * @return DocWriter
 */
@Override
protected DocWriter createWriter(final MBasicTable table, final Document document, final OutputStream out) {
    final RtfWriter2 writer = RtfWriter2.getInstance(document, out);

    // title
    final String title = buildTitle(table);
    if (title != null) {
        final HeaderFooter header = new RtfHeaderFooter(new Paragraph(title));
        header.setAlignment(Element.ALIGN_LEFT);
        header.setBorder(Rectangle.NO_BORDER);
        document.setHeader(header);
        document.addTitle(title);
    }

    // advanced page numbers : x/y
    final Paragraph footerParagraph = new Paragraph();
    final Font font = FontFactory.getFont(FontFactory.TIMES_ROMAN, 12, Font.NORMAL);
    footerParagraph.add(new RtfPageNumber(font));
    footerParagraph.add(new Phrase(" / ", font));
    footerParagraph.add(new RtfTotalPageNumber(font));
    footerParagraph.setAlignment(Element.ALIGN_CENTER);
    final HeaderFooter footer = new RtfHeaderFooter(footerParagraph);
    footer.setBorder(Rectangle.TOP);
    document.setFooter(footer);

    return writer;
}

From source file:net.sf.eclipsecs.ui.stats.export.internal.RTFStatsExporter.java

License:Open Source License

private void createHeaderAndFooter(Document doc) {
    Paragraph p = new Paragraph("Checkstyle statistics", pageHeaderAndFooterFont);
    p.setAlignment(Element.ALIGN_CENTER);
    HeaderFooter header = new RtfHeaderFooter(p);
    doc.setHeader(header);

    SimpleDateFormat simpleDateFormat = new SimpleDateFormat();
    p = new Paragraph("Gnr le : " + simpleDateFormat.format(new Date()), pageHeaderAndFooterFont);
    p.setAlignment(Element.ALIGN_CENTER);
    RtfHeaderFooterGroup footer = new RtfHeaderFooterGroup();
    footer.setHeaderFooter(new RtfHeaderFooter(p),
            com.lowagie.text.rtf.headerfooter.RtfHeaderFooter.DISPLAY_ALL_PAGES);
    doc.setFooter(footer);//from   w  w w  .  j  av  a 2 s . co  m
}

From source file:open.dolphin.client.AuditController.java

License:Open Source License

private void makePDF() {

    //- ?/*from  w w  w.ja v  a  2 s  .  c o  m*/
    Document doc = new Document(PageSize.A4, 20.0F, 20.0F, 40.0F, 40.0F);

    try {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String fileName = "_" + sdf.format(new java.util.Date()) + ".pdf";

        //()??
        FileOutputStream fos = new FileOutputStream(outputDir.getText() + fileName);
        PdfWriter pdfwriter = PdfWriter.getInstance(doc, fos);
        Font font_header = new Font(BaseFont.createFont("HeiseiKakuGo-W5", "UniJIS-UCS2-H", false), 15.0F, 1);
        Font font_g11 = new Font(BaseFont.createFont("HeiseiKakuGo-W5", "UniJIS-UCS2-H", false), 11.0F);
        Font font_g10 = new Font(BaseFont.createFont("HeiseiKakuGo-W5", "UniJIS-UCS2-H", false), 10.0F);
        //- ?
        Font font_m8 = new Font(BaseFont.createFont("HeiseiMin-W3", "UniJIS-UCS2-HW-H", false), 8.0F);
        Font font_underline_11 = new Font(BaseFont.createFont("HeiseiKakuGo-W5", "UniJIS-UCS2-H", false), 11.0F,
                4);
        Font font_red_11 = new Font(BaseFont.createFont("HeiseiKakuGo-W5", "UniJIS-UCS2-H", false), 11.0F);
        font_red_11.setColor(new Color(255, 0, 0));
        Font font_empty = new Font(BaseFont.createFont("HeiseiKakuGo-W5", "UniJIS-UCS2-H", false), 9.0F);
        font_empty.setColor(new Color(255, 255, 255));

        Paragraph para_NF = new Paragraph(5, "\r\n",
                new Font(BaseFont.createFont("HeiseiKakuGo-W5", "UniJIS-UCS2-H", false), 13, Font.NORMAL));
        para_NF.setAlignment(Element.ALIGN_CENTER);

        // ??
        String author = Project.getProjectStub().getUserModel().getCommonName();
        doc.addAuthor(author);
        doc.addSubject("");

        HeaderFooter header = new HeaderFooter(new Phrase("", font_header),
                false);
        header.setAlignment(1);
        doc.setHeader(header);

        HeaderFooter footer = new HeaderFooter(new Phrase("--"), new Phrase("--"));
        footer.setAlignment(1);
        footer.setBorder(0);
        doc.setFooter(footer);

        doc.open();

        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy''MM''dd'' HH''mm''");
        String today = sdf1.format(new java.util.Date());
        Paragraph para_0 = new Paragraph("?" + today, font_g11);
        para_0.setAlignment(2);
        doc.add(para_0);
        Paragraph para_1 = new Paragraph("?" + author, font_g11);
        para_1.setAlignment(2);
        doc.add(para_1);
        doc.add(new Paragraph(""));
        // 
        doc.add(para_NF);
        doc.add(para_NF);

        for (int cnt = 0; cnt < outputList.size(); cnt++) {

            InnerBean bean = outputList.get(cnt);
            Person person = bean.getPerson();

            Paragraph para_2 = new Paragraph("ID" + person.idProperty().get(), font_underline_11);
            para_2.setAlignment(0);
            doc.add(para_2);
            Paragraph para_3 = new Paragraph("???" + person.nameProperty().get(),
                    font_underline_11);
            para_3.setAlignment(0);
            doc.add(para_3);
            Paragraph para_4 = new Paragraph("" + person.nameKanaProperty().get(),
                    font_underline_11);
            para_4.setAlignment(0);
            doc.add(para_4);
            Paragraph para_5 = new Paragraph("" + person.sexProperty().get(), font_underline_11);
            para_5.setAlignment(0);
            doc.add(para_5);
            Paragraph para_6 = new Paragraph("" + person.birthdayProperty().get(),
                    font_underline_11);
            para_6.setAlignment(0);
            doc.add(para_6);

            Table karteHistoryTable = new Table(5);
            karteHistoryTable.setWidth(100.0F);
            int[] uriage_table_width = { 25, 20, 30, 20, 25 };
            karteHistoryTable.setWidths(uriage_table_width);
            //karteHistoryTable.setDefaultHorizontalAlignment(1);
            //karteHistoryTable.setDefaultVerticalAlignment(5);
            karteHistoryTable.setPadding(3.0F);
            karteHistoryTable.setSpacing(0.0F);
            karteHistoryTable.setBorderColor(new Color(0, 0, 0));

            Cell cell_01 = new Cell(new Phrase("?", font_g10));
            cell_01.setGrayFill(0.8F);
            cell_01.setHorizontalAlignment(Element.ALIGN_CENTER);
            Cell cell_11 = new Cell(new Phrase("?", font_g10));
            cell_11.setGrayFill(0.8F);
            cell_11.setHorizontalAlignment(Element.ALIGN_CENTER);
            Cell cell_21 = new Cell(new Phrase("", font_g10));
            cell_21.setGrayFill(0.8F);
            cell_21.setHorizontalAlignment(Element.ALIGN_CENTER);
            Cell cell_31 = new Cell(new Phrase("", font_g10));
            cell_31.setGrayFill(0.8F);
            cell_31.setHorizontalAlignment(Element.ALIGN_CENTER);
            Cell cell_41 = new Cell(new Phrase("", font_g10));
            cell_41.setGrayFill(0.8F);
            cell_41.setHorizontalAlignment(Element.ALIGN_CENTER);

            karteHistoryTable.addCell(cell_01);
            karteHistoryTable.addCell(cell_11);
            karteHistoryTable.addCell(cell_21);
            karteHistoryTable.addCell(cell_31);
            karteHistoryTable.addCell(cell_41);

            List<KarteBean> list = bean.getResult();
            KarteBean karteInfo = list.get(0);
            List<DocInfoModel> docInfoList = karteInfo.getDocInfoList();

            //- ???
            int stepCount = 22;
            int tempCount = 0;
            int pageCount = 0;

            String firstKarteMaker = null;
            String karteMakeDate = null;
            if (docInfoList != null) {
                for (int i = 0; i < docInfoList.size(); ++i) {
                    DocInfoModel docInfo = docInfoList.get(i);
                    Cell cell = new Cell(new Phrase(docInfo.getFirstConfirmDateTime(), font_m8));
                    if (karteMakeDate == null || !karteMakeDate.equals(docInfo.getFirstConfirmDateTime())) {
                        karteMakeDate = docInfo.getFirstConfirmDateTime();
                        firstKarteMaker = docInfo.getPurpose();
                    }
                    cell.setHorizontalAlignment(0);
                    cell.setHorizontalAlignment(Element.ALIGN_CENTER);
                    karteHistoryTable.addCell(cell);
                    cell = new Cell(new Phrase(firstKarteMaker, font_m8));
                    cell.setHorizontalAlignment(0);
                    cell.setHorizontalAlignment(Element.ALIGN_CENTER);
                    karteHistoryTable.addCell(cell);
                    //- 
                    String addTitle = docInfo.getTitle();
                    addTitle = addTitle.replace("\r\n", "");
                    addTitle = addTitle.replace("\n", "");
                    cell = new Cell(new Phrase(addTitle, font_m8));
                    cell.setHorizontalAlignment(0);
                    karteHistoryTable.addCell(cell);
                    cell = new Cell(new Phrase(docInfo.getPurpose(), font_m8));
                    cell.setHorizontalAlignment(0);
                    cell.setHorizontalAlignment(Element.ALIGN_CENTER);
                    karteHistoryTable.addCell(cell);
                    cell = new Cell(new Phrase(docInfo.getConfirmDateTime(), font_m8));
                    cell.setHorizontalAlignment(0);
                    cell.setHorizontalAlignment(Element.ALIGN_CENTER);
                    karteHistoryTable.addCell(cell);

                    if (stepCount == tempCount) {
                        if (pageCount == 0) {
                            stepCount += 5;
                            pageCount++;
                        }
                        tempCount = 0;
                        doc.add(karteHistoryTable);
                        doc.newPage();
                        karteHistoryTable.deleteAllRows();
                        karteHistoryTable.addCell(cell_01);
                        karteHistoryTable.addCell(cell_11);
                        karteHistoryTable.addCell(cell_21);
                        karteHistoryTable.addCell(cell_31);
                        karteHistoryTable.addCell(cell_41);
                    } else {
                        tempCount++;
                    }
                }

                //                    Cell Empty_Cell = new Cell(new Phrase("empty", font_empty));
                //                    for (int i = docInfoList.size(); i < docInfoList.size() + 4; ++i) {
                //                        for (int j = 0; j < 4; ++j) {
                //                            karteHistoryTable.addCell(Empty_Cell);
                //                        }
                //                    }
                //
                //            Cell cell_goukei = new Cell(new Phrase("?", font_g10));
                //            cell_goukei.setGrayFill(0.8F);
                //            cell_goukei.setColspan(3);
                //            karteHistoryTable.addCell(cell_goukei);
                //            Cell cell_sum = new Cell(new Phrase("136,900", font_m10));
                //            cell_sum.setHorizontalAlignment(2);
                //            karteHistoryTable.addCell(cell_sum);
                doc.add(karteHistoryTable);
                doc.newPage();

            } else {
                // 
                doc.add(para_NF);

                Paragraph noData = new Paragraph("??", font_m8);
                noData.setAlignment(0);
                doc.add(noData);
                doc.newPage();
            }
        }
    } catch (DocumentException | IOException e) {
        Logger.getLogger(AuditController.class.getName()).log(Level.SEVERE, null, e);
    } finally {
        doc.close();
    }
}

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

License:Open Source License

public File getPdfFile(String filename) {
    try {/*from ww w  . j  av a 2 s . com*/
        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.kfs.module.endow.report.util.TransactionSummaryReportPrint.java

License:Educational Community License

/**
 * Generates the report in PDF using iText
 * /* w w w.j av  a  2 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
 * /*from w  w  w. j a v a  2s .c  om*/
 * @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;
}

From source file:org.schreibubi.JCombinations.ui.GridChartPanel.java

License:Open Source License

/**
 * Create PDF//from w ww.j a v a  2s  . c  o m
 * 
 * @param name
 *            Filename
 * @param selection
 *            Selected Nodes
 * @param dm
 *            DataModel
 * @param pl
 *            ProgressListener
 */
@SuppressWarnings("unchecked")
public static void generatePDF(File name, DataModel dm, ArrayList<TreePath> selection, ProgressListener pl) {
    com.lowagie.text.Document document = new Document(PageSize.A4.rotate(), 50, 50, 50, 50);
    try {
        ArrayList<ExtendedJFreeChart> charts = dm.getCharts(selection);
        if (charts.size() > 0) {
            PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(name));
            writer.setViewerPreferences(PdfWriter.PageModeUseOutlines);
            document.addAuthor("Jrg Werner");
            document.addSubject("Created by JCombinations");
            document.addKeywords("JCombinations");
            document.addCreator("JCombinations using iText");

            // we define a header and a footer
            HeaderFooter header = new HeaderFooter(new Phrase("JCombinations by Jrg Werner"), false);
            HeaderFooter footer = new HeaderFooter(new Phrase("Page "), new Phrase("."));
            footer.setAlignment(Element.ALIGN_CENTER);
            document.setHeader(header);
            document.setFooter(footer);

            document.open();
            DefaultFontMapper mapper = new DefaultFontMapper();
            FontFactory.registerDirectories();
            mapper.insertDirectory("c:\\WINNT\\fonts");

            PdfContentByte cb = writer.getDirectContent();

            pl.progressStarted(new ProgressEvent(GridChartPanel.class, 0, charts.size()));
            for (int i = 0; i < charts.size(); i++) {
                ExtendedJFreeChart chart = charts.get(i);
                PdfTemplate tp = cb.createTemplate(document.right(EXTRA_MARGIN) - document.left(EXTRA_MARGIN),
                        document.top(EXTRA_MARGIN) - document.bottom(EXTRA_MARGIN));
                Graphics2D g2d = tp.createGraphics(document.right(EXTRA_MARGIN) - document.left(EXTRA_MARGIN),
                        document.top(EXTRA_MARGIN) - document.bottom(EXTRA_MARGIN), mapper);
                Rectangle2D r2d = new Rectangle2D.Double(0, 0,
                        document.right(EXTRA_MARGIN) - document.left(EXTRA_MARGIN),
                        document.top(EXTRA_MARGIN) - document.bottom(EXTRA_MARGIN));
                chart.draw(g2d, r2d);
                g2d.dispose();
                cb.addTemplate(tp, document.left(EXTRA_MARGIN), document.bottom(EXTRA_MARGIN));
                PdfDestination destination = new PdfDestination(PdfDestination.FIT);
                TreePath treePath = chart.getTreePath();
                PdfOutline po = cb.getRootOutline();
                for (int j = 0; j < treePath.getPathCount(); j++) {
                    ArrayList<PdfOutline> lpo = po.getKids();
                    PdfOutline cpo = null;
                    for (PdfOutline outline : lpo)
                        if (outline.getTitle().compareTo(treePath.getPathComponent(j).toString()) == 0)
                            cpo = outline;
                    if (cpo == null)
                        cpo = new PdfOutline(po, destination, treePath.getPathComponent(j).toString());
                    po = cpo;
                }
                document.newPage();
                pl.progressIncremented(new ProgressEvent(GridChartPanel.class, i));
            }
            document.close();
            pl.progressEnded(new ProgressEvent(GridChartPanel.class));

        }
    } catch (DocumentException de) {
        System.err.println(de.getMessage());
    } catch (IOException ioe) {
        System.err.println(ioe.getMessage());
    }
}

From source file:org.silverpeas.components.almanach.control.AlmanachPdfGenerator.java

License:Open Source License

static public void buildPdf(String name, AlmanachSessionController almanach, String mode)
        throws AlmanachRuntimeException {
    try {/* w ww .j  a  v a  2  s .  c  om*/

        String fileName = FileRepositoryManager.getTemporaryPath(almanach.getSpaceId(),
                almanach.getComponentId()) + name;
        Document document = new Document(PageSize.A4, 50, 50, 50, 50);

        // we add some meta information to the document
        document.addAuthor(almanach.getSettings().getString("author", ""));
        document.addSubject(almanach.getSettings().getString("subject", ""));
        document.addCreationDate();

        PdfWriter.getInstance(document, new FileOutputStream(fileName));
        document.open();

        try {
            Calendar currentDay = Calendar.getInstance();
            currentDay.setTime(almanach.getCurrentDay());
            String sHeader = almanach.getString("events");
            if (mode.equals(PDF_MONTH_ALLDAYS) || mode.equals(PDF_MONTH_EVENTSONLY)) {
                sHeader += " " + almanach.getString("GML.mois" + currentDay.get(Calendar.MONTH));
            }
            sHeader += " " + currentDay.get(Calendar.YEAR);
            HeaderFooter header = new HeaderFooter(new Phrase(sHeader), false);
            HeaderFooter footer = new HeaderFooter(new Phrase("Page "), true);
            footer.setAlignment(Element.ALIGN_CENTER);

            document.setHeader(header);
            document.setFooter(footer);

            createFirstPage(almanach, document);
            document.newPage();

            Font titleFont = new Font(Font.HELVETICA, 24, Font.NORMAL, new Color(255, 255, 255));
            Paragraph cTitle = new Paragraph(almanach.getString("Almanach") + " "
                    + almanach.getString("GML.mois" + currentDay.get(Calendar.MONTH)) + " "
                    + currentDay.get(Calendar.YEAR), titleFont);
            Chapter chapter = new Chapter(cTitle, 1);

            // Collection<EventDetail> events =
            // almanach.getListRecurrentEvent(mode.equals(PDF_YEAR_EVENTSONLY));
            AlmanachCalendarView almanachView;
            if (PDF_YEAR_EVENTSONLY.equals(mode)) {
                almanachView = almanach.getYearlyAlmanachCalendarView();
            } else {
                almanachView = almanach.getMonthlyAlmanachCalendarView();
            }

            List<DisplayableEventOccurrence> occurrences = almanachView.getEvents();
            generateAlmanach(chapter, almanach, occurrences, mode);

            document.add(chapter);
        } catch (Exception ex) {
            throw new AlmanachRuntimeException("PdfGenerator.generate", AlmanachRuntimeException.WARNING,
                    "AlmanachRuntimeException.EX_PROBLEM_TO_GENERATE_PDF", ex);
        }

        document.close();

    } catch (Exception e) {
        throw new AlmanachRuntimeException("PdfGenerator.generate", AlmanachRuntimeException.WARNING,
                "AlmanachRuntimeException.EX_PROBLEM_TO_GENERATE_PDF", e);
    }

}

From source file:recite18th.controller.Controller.java

License:Open Source License

public void print(String action) {
    /** thanks to http://www.java2s.com/Code/Java/PDF-RTF/DemonstratesthecreatingPDFinportraitlandscape.htm
     * QUICK FIX : do landscape//from  ww w .  j  av  a2  s  .c o  m
     */
    response.setContentType("application/pdf"); // Code 1
    if (action.equals("download")) {
        response.setHeader("Content-Transfer-Encoding", "binary");
        response.setHeader("Content-Disposition",
                "attachment; filename=\"" + "Report " + controllerName + ".pdf\"");
    }
    Document document = new Document(PageSize.A1.rotate());
    try {
        PdfWriter writer = PdfWriter.getInstance(document, response.getOutputStream()); // Code 2
        document.open();

        // various fonts
        BaseFont bf_helv = BaseFont.createFont(BaseFont.HELVETICA, "Cp1252", false);
        BaseFont bf_times = BaseFont.createFont(BaseFont.TIMES_ROMAN, "Cp1252", false);
        BaseFont bf_courier = BaseFont.createFont(BaseFont.COURIER, "Cp1252", false);
        BaseFont bf_symbol = BaseFont.createFont(BaseFont.SYMBOL, "Cp1252", false);

        String headerImage = Config.base_path + "images/report-logo.gif";

        Image imghead = Image.getInstance(headerImage);
        imghead.setAbsolutePosition(0, 0);
        PdfContentByte cbhead = writer.getDirectContent();
        PdfTemplate tpLogo = cbhead.createTemplate(600, 300);
        tpLogo.addImage(imghead);

        PdfTemplate tpTitle = cbhead.createTemplate(1100, 300);
        String txtHeader = "BADAN KEPEGAWAIAN DAERAH PEMERINTAH DAERAH";//Config.application_title;
        tpTitle.beginText();
        tpTitle.setFontAndSize(bf_times, 36);
        tpTitle.showText(txtHeader);
        tpTitle.endText();

        PdfTemplate tpTitle2 = cbhead.createTemplate(900, 300);
        String txtHeader2 = "         KABUPATEN BANTUL YOGYAKARTA";
        tpTitle2.beginText();
        tpTitle2.setFontAndSize(bf_times, 36);
        tpTitle2.showText(txtHeader2);
        tpTitle2.endText();

        PdfTemplate tpAlamat = cbhead.createTemplate(1000, 400);
        tpAlamat.beginText();
        tpAlamat.setFontAndSize(bf_times, 24);
        tpAlamat.showText(
                "Alamat : Jln. R. W. Monginsidi No. 01 Kompleks Parasamya Bantul, Telp. (0274) 367509");
        tpAlamat.endText();

        DateFormat df = new SimpleDateFormat("dd MMM yyyy");
        java.util.Date dt = new java.util.Date();
        PdfTemplate tp3 = cbhead.createTemplate(600, 300);
        tp3.beginText();
        tp3.setFontAndSize(bf_times, 16);

        tp3.showText("Tanggal : " + df.format(dt));
        tp3.endText();

        cbhead.addTemplate(tpLogo, 800, 1500);//logo
        cbhead.addTemplate(tpTitle, 1000, 1580);
        cbhead.addTemplate(tpTitle2, 1000, 1540);
        cbhead.addTemplate(tpAlamat, 1000, 1500);//alamat
        cbhead.addTemplate(tp3, 270, 1500);//tanggal

        HeaderFooter header = new HeaderFooter(new Phrase(cbhead + "", new Font(bf_helv)), false);
        header.setAlignment(Element.ALIGN_CENTER);

        document.setHeader(header);

        //PdfContentByte cb = writer.getDirectContent();
        Paragraph par = new Paragraph(
                "\n\n\n\n\n\n\nLAPORAN DATA SELURUH " + controllerName.toUpperCase() + "\n");
        par.getFont().setStyle(Font.BOLD);
        par.getFont().setSize(18);
        par.setAlignment("center");
        document.add(par);
        document.add(new Paragraph("\n\n"));

        // get data
        initSqlViewDataPerPage();
        if (sqlViewDataPerPageForReport == null) {
            sqlViewDataPerPageForReport = sqlViewDataPerPage;
        }
        PreparedStatement pstmt = Db.getCon().prepareStatement(sqlViewDataPerPageForReport,
                ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
        ResultSet resultSet = pstmt.executeQuery();
        ResultSetMetaData metaColumn = resultSet.getMetaData();
        int nColoumn = metaColumn.getColumnCount();
        // thanks to set cell width http://www.jexp.ru/index.php/Java/PDF_RTF/Table_Cell_Size#Setting_Cell_Widths
        if (nColoumn > 0) {
            Model model = initModel();
            String tableName = model.getTableName();
            // create table header
            //     float[] widths = {1, 4};
            PdfPTable table;// = new PdfPTable(nColoumn);
            PdfPCell cell = new PdfPCell(new Paragraph("Daftar " + controllerName));

            Hashtable hashModel = TableCustomization.getTable(model.getTableName());

            int ncolumnHeader = nColoumn + 1; // +1 because of row. number
            if (hashModel != null) {
                ncolumnHeader = Integer.parseInt("" + hashModel.get("columnCount")) + 1;
            }
            table = new PdfPTable(ncolumnHeader);
            cell.setColspan(ncolumnHeader);
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);

            Paragraph p2 = new Paragraph("No.");
            p2.getFont().setSize(20);
            PdfPCell cellColNo = new PdfPCell(p2);
            cellColNo.setNoWrap(true);
            cellColNo.setMinimumHeight(50);
            cellColNo.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.addCell(cellColNo);

            if (hashModel != null) {
                Enumeration k = hashModel.keys();
                while (k.hasMoreElements()) {
                    String key = (String) k.nextElement();
                    if (key.equals("columnCount")) {
                        continue;
                    }
                    PdfPCell cellCol = new PdfPCell(new Paragraph(hashModel.get(key) + ""));
                    cellCol.setNoWrap(true);
                    cellCol.setMinimumHeight(50);
                    cellCol.setHorizontalAlignment(Element.ALIGN_CENTER);

                    table.addCell(cellCol);
                }
            } else {
                for (int i = 1; i < ncolumnHeader; i++) {
                    System.out.println("DATA = " + metaColumn.getColumnName(i));
                    Paragraph p1 = new Paragraph(metaColumn.getColumnName(i) + "");
                    p1.getFont().setSize(20);
                    PdfPCell cellCol = new PdfPCell(p1);
                    cellCol.setHorizontalAlignment(Element.ALIGN_CENTER);
                    table.addCell(cellCol);
                }
            }

            //iterate all columns : table data
            resultSet.beforeFirst();
            int row = 1;
            while (resultSet.next()) {
                System.out.println(row);
                Paragraph p3 = new Paragraph(row + "");
                p3.getFont().setSize(20);
                cell = new PdfPCell(p3);
                cell.setHorizontalAlignment(Element.ALIGN_CENTER);
                table.addCell(cell);
                if (hashModel != null) {//skip dulu u/ kasus ga pny class kustomasi table
                    Enumeration k = hashModel.keys();
                    while (k.hasMoreElements()) {
                        String key = (String) k.nextElement();
                        if (key.equals("columnCount")) {
                            continue;
                        }
                        table.addCell(resultSet.getObject(key) + "");
                    }
                } else {
                    for (int i = 1; i < ncolumnHeader; i++) {
                        System.out.println("DATA = " + metaColumn.getColumnName(i));
                        Paragraph p1 = new Paragraph(resultSet.getObject(metaColumn.getColumnName(i)) + "");
                        p1.getFont().setSize(18);
                        PdfPCell cellCol = new PdfPCell(p1);
                        cellCol.setHorizontalAlignment(Element.ALIGN_CENTER);
                        table.addCell(cellCol);
                    }
                }

                row++;
            }

            document.add(table);
            document.add(new Paragraph("\n\n"));
            par = new Paragraph("Mengetahui");
            par.setAlignment("center");
            document.add(par);
            par = new Paragraph("Kepada Badan Kepegawaian");
            par.setAlignment("center");
            document.add(par);
            par = new Paragraph("\n\n\n");

            document.add(par);
            par = new Paragraph("Drs. Maman Permana");
            par.setAlignment("center");
            document.add(par);
            par = new Paragraph("Nip: 197802042006041013");
            par.setAlignment("center");

            document.add(par);

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