简体   繁体   中英

Table creation on separate method using iText in Java

I'm trying to create an PDF document using iText. I followed to THIS nice tutorial and tried to create single page pdf document which has a table. In the tutorial the author keeps table creation of table on separate method such as addMetaData, addTitlePage and addContent. I also would keep them separately, but I'm new to iText and currently I'm stuck. The current code is:

public static void main(String args[]) {
    try {
        Document document = new Document(PageSize.A4);
        PdfWriter.getInstance(document, new FileOutputStream(FILE));
        document.open();
        addMetaData(document);
        addTitlePage(document);
        addContent(document);
        document.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

private static void addTitlePage(Document document) throws DocumentException {
    Paragraph preface = new Paragraph();
    // Add one empty line
    addEmptyLine(preface, 1);
    // Header of the document
    preface.add(new Paragraph("Title here", capFont));

    addEmptyLine(preface, 1);
    // Report generated by: _name, _date
    preface.add(new Paragraph("Report generated by: " + System.getProperty("user.name") + ", " + new Date(), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
        normFont));
    addEmptyLine(preface, 2);
    preface.add(new Paragraph("This document describes some kind of price list which is unknown to me.", normFont));

    document.add(preface);
}

private static void addContent(Document document) throws DocumentException {
    Paragraph content = new Paragraph();
    // Add one empty line
    addEmptyLine(content, 1);

    // Content of the document
    content.add(new Paragraph(createTable(subPart), normFont));   // not working line

    addEmptyLine(content, 5);
    content.add(new Paragraph("This document is a preliminary version and not subject to the license agreement.", redFont));

    document.add(content);
}

private static void createTable(Section subPart) throws BadElementException {
    PdfPTable table = new PdfPTable(3);
    table.setHorizontalAlignment(Element.ALIGN_CENTER);
    // Data
    table.addCell("1");
    table.addCell("2");
    table.addCell("3");
    subPart.add(table);
}

Any help would be appreciated.

So, after one day literature reading and api homepage visiting I came to my solution:

Instead of: content.add(new Paragraph(createTable(subPart), normFont));

I have now: createTable(content);

and of course I changed the type of variable in createTable method to the paragraph in order to get it working.

package src.AutosysPolicyWriter.Utility;

import java.util.StringTokenizer;

import com.lowagie.text.Cell;
import com.lowagie.text.Document;
import com.lowagie.text.Element;
import com.lowagie.text.Font;
import com.lowagie.text.Phrase;
import com.lowagie.text.Rectangle;
import com.lowagie.text.Table;


/**
 * Modification/itext 1.4 - <Modified : September 26, 2013>
 * @author Oliver Lundag
 * @date 2013-09-06
 * Can handle table creation in the PDF
 */
public class PdfTableUtility {

    /***
     * 
     * @param titleFont - font of the title of the table
     * @param fontHeader - font of the headers
     * @param fontData - font of the data
     * @param thisReport - Document
     * @param tableTitle - Name of the table
     * @param headerStrings - headers
     * @param data - data
     * 
     * How to use this function;
     * 
     * Example:
     * 
     *      // Initialize PdfTableUtility object
     *      1. PdfTableUtility tableUtility = new PdfTableUtility();
     * 
     *      // Declare the value for headers.
     *      // Note: Number of columns will depends on how many headers has been declared 
     *      2. String[] headers = {"Customer Name","Age","Plan","Amount"};
     *
     *      // Declare the data that will be put inside 
     *      // Note that the arrangement of the strings are the actual display in the pdf 
     *      // ; - separator
     *      3. String data    = "1.Oliver Lundag;26;Plan A;250,000;"+
     *                          "2.Oliver Lundag;26;Plan A;250,000;"+
     *                          "3.Oliver Lundag;26;Plan A;250,000";
     *
     *      //call the function with specified arguments
     *      //arguments will depend on developers perspective
     *      4. tableUtility.displaytable(FontBold11, FontBold9, FontNormal9, thisReport, "Information", 4, headers, data);
     */
    public void displaytable(Font titleFont, Font fontHeader, Font fontData, Document thisReport,String tableTitle, String[] headerStrings, String data) {
        try{

            //START-(Modification/itext 1.4)  SR-CS-13035  - OLUND <Modified : September 26, 2013> - title
            //1.create table
            Table title = new Table(1);
            title.setLastHeaderRow(1);
            title.setOffset(12f);
            title.setSpaceInsideCell(1f);
            title.setBorder(Rectangle.NO_BORDER);

            //2.create table
            Cell celltitle = new Cell(new Phrase(tableTitle, titleFont));
            celltitle.setLeading(12);
            celltitle.setBorder(Rectangle.NO_BORDER);
            celltitle.setHorizontalAlignment(Element.ALIGN_CENTER);
            title.addCell(celltitle);

            //3.add the title in document
            thisReport.add(title);
            //END -(Modification/itext 1.4)  SR-CS-13035  - OLUND <Modified : September 26, 2013> - title


            //START-(Modification/itext 1.4)  SR-CS-13035  - OLUND <Modified : September 26, 2013> - data
            //1. get the max number of columns
            int numColumns = headerStrings.length;

            //2. create a table
            Table table = new Table(numColumns);
            table.setOffset(12f);
            table.setLastHeaderRow(1);
            table.setSpaceInsideCell(1f);
            table.setTableFitsPage(true);
            table.setAutoFillEmptyCells(true);

            //3.get headers and add it into cells
            for (String header : headerStrings) {
                Cell headerCell = new Cell(new Phrase(header, fontHeader));
                headerCell.setLeading(12);
                headerCell.setHorizontalAlignment(Element.ALIGN_CENTER);
                table.addCell(headerCell);
            }

            //4.get data and add it into cells
            String strToken;
            if (data.length() > 0) {
                StringTokenizer stStr = new StringTokenizer(data,";",false);
                while(stStr.hasMoreTokens()){
                    strToken = stStr.nextToken().toString();
                    Cell cell = new Cell(new Phrase(strToken,fontData));
                    cell.setHorizontalAlignment(Element.ALIGN_CENTER);
                    cell.setLeading(12);
                    table.addCell(cell);
                }
            }

            //5. add the table in the document
            thisReport.add(table);
            //END - (Modification/itext 1.4)  SR-CS-13035  - OLUND <Modified : September 26, 2013> - data

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

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM