Reporting examples

This is a code example of iText PDF, discover more.

8th November 2015
admin-marketing

Switch code for this example

In these examples, we use XHTML, CSS and a PDF that acts as stationery to create reports.



FillTemplate1.java
package sandbox.xmlworker.reporting;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.tool.xml.ElementList;
import com.itextpdf.tool.xml.html.Tags;
import sandbox.WrapToTest;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

@WrapToTest
public class FillTemplate1 {

    public static final String DEST = "results/xmlworker/report1.pdf";
    public static final String PDF =  "resources/pdfs/stationery.pdf";
    public static final String HTML = "resources/xml/movies.html";
    public static final String CSS = "resources/xml/style1.css";
    
    public void createPdf(String result) throws IOException, DocumentException {
        FillTemplateHelper template = new FillTemplateHelper(PDF);
        template.setSender("Bruno Lowagie\nAdolf Baeyensstraat 121\n9040 Sint-Amandsberg\nBELGIUM");
        template.setReceiver("iText Software Corp.\nCambridge Innovation Center\n1 Broadway, 14th Floor\nCambridge, MA 02142 USA");
        // step 1
        Document document = new Document(template.getPageSize(),
            template.getmLeft(), template.getmRight(), template.getmTop(), template.getmBottom());
        // step 2
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(result));
        writer.setPageEvent(template);
        // step 3
        document.open();
        // step 4
        ElementList elements = FillTemplateHelper.parseHtml(HTML, CSS, Tags.getHtmlTagProcessorFactory());
        for (Element e : elements) {
            document.add(e);
        }
        // step 5
        document.close();
    }
    
    public static void main(String[] args) throws IOException, DocumentException {
        File file = new File(DEST);
        file.getParentFile().mkdirs();
        new FillTemplate1().createPdf(DEST);
    }
}
FillTemplate2.java
package sandbox.xmlworker.reporting;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.pdf.ColumnText;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.tool.xml.ElementList;
import com.itextpdf.tool.xml.html.Tags;
import sandbox.WrapToTest;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

@WrapToTest
public class FillTemplate2 {

    public static final String DEST = "results/xmlworker/report2.pdf";
    public static final String PDF = "resources/pdfs/stationery.pdf";
    public static final String HTML = "resources/xml/movies.html";
    public static final String CSS = "resources/xml/style2.css";
    
    public void createPdf(String result) throws IOException, DocumentException {
        FillTemplateHelper template = new FillTemplateHelper(PDF);
        template.setSender("Bruno Lowagie\nAdolf Baeyensstraat 121\n9040 Sint-Amandsberg\nBELGIUM");
        template.setReceiver("iText Software Corp.\nCambridge Innovation Center\n1 Broadway, 14th Floor\nCambridge, MA 02142 USA");
        // step 1
        Document document = new Document(template.getPageSize());
        // step 2
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(result));
        writer.setPageEvent(template);
        // step 3
        document.open();
        // step 4
        ColumnText ct = new ColumnText(writer.getDirectContent());
        ct.setSimpleColumn(template.getBody());
	ElementList elements = FillTemplateHelper.parseHtml(HTML, CSS, Tags.getHtmlTagProcessorFactory());
        int status;
        float yLine;
        int rowsDrawn;
        for (Element e : elements) {
            if (!ColumnText.isAllowedElement(e))
                continue;
            if (e instanceof PdfPTable)
                ((PdfPTable)e).setHeaderRows(1);
            yLine = ct.getYLine();
            ct.addElement(e);
            status = ct.go(true);
            // the content fits:
            if (!ColumnText.hasMoreText(status)) {
                 // return to the original position
                ct.setYLine(yLine);
                // add the element FOR REAL
                ct.addElement(e);
                ct.go();
            }
            else {
                rowsDrawn = ct.getRowsDrawn();
                ct.setText(null);
                ct.addElement(e);
                ct.setSimpleColumn(template.getBody());
                status = ct.go(true);
                if (ColumnText.hasMoreText(status) && rowsDrawn > 2) {
                    ct.setYLine(yLine);
                    ct.setText(null);
                    ct.addElement(e);
                    ct.go();
                }
                else {
                    ct.setText(null);
                    ct.addElement(e);
                }
                document.newPage();
                ct.setSimpleColumn(template.getBody());
                status = ct.go();
                while (ColumnText.hasMoreText(status)) {
                    document.newPage();
                    ct.setSimpleColumn(template.getBody());
                    status = ct.go();
                }
            }
        }
        // step 5
        document.close();
    }
    
    public static void main(String[] args) throws IOException, DocumentException {
        File file = new File(DEST);
        file.getParentFile().mkdirs();
        new FillTemplate2().createPdf(DEST);
    }
}
FillTemplate3.java
package sandbox.xmlworker.reporting;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.pdf.ColumnText;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.tool.xml.ElementList;
import com.itextpdf.tool.xml.html.Tags;
import sandbox.WrapToTest;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

@WrapToTest
public class FillTemplate3 {

    public static final String DEST = "results/xmlworker/report3.pdf";
    public static final String PDF = "resources/pdfs/stationery_landscape.pdf";
    public static final String HTML = "resources/xml/movies.html";
    public static final String CSS = "resources/xml/style3.css";
    
    public void createPdf(String result) throws IOException, DocumentException {
        FillTemplateHelper template = new FillTemplateHelper(PDF);
        template.setSender("Bruno Lowagie\nAdolf Baeyensstraat 121\n9040 Sint-Amandsberg\nBELGIUM");
        template.setReceiver("iText Software Corp.\nCambridge Innovation Center\n1 Broadway, 14th Floor\nCambridge, MA 02142 USA");
        // step 1
        Document document = new Document(template.getPageSize());
        // step 2
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(result));
        writer.setPageEvent(template);
        // step 3
        document.open();
        // step 4
        ColumnText ct = new ColumnText(writer.getDirectContent());
        ct.setSimpleColumn(template.getBody());
	ElementList elements = FillTemplateHelper.parseHtml(HTML, CSS, Tags.getHtmlTagProcessorFactory());
        int status;
        float yLine;
        int rowsDrawn;
        for (Element e : elements) {
            if (!ColumnText.isAllowedElement(e))
                continue;
            if (e instanceof PdfPTable)
                ((PdfPTable)e).setHeaderRows(1);
            yLine = ct.getYLine();
            ct.addElement(e);
            status = ct.go(true);
            // the content fits:
            if (!ColumnText.hasMoreText(status)) {
                 // return to the original position
                ct.setYLine(yLine);
                // add the element FOR REAL
                ct.addElement(e);
                ct.go();
            }
            else {
                rowsDrawn = ct.getRowsDrawn();
                ct.setText(null);
                ct.addElement(e);
                ct.setSimpleColumn(template.getBody());
                status = ct.go(true);
                if (ColumnText.hasMoreText(status) && rowsDrawn > 2) {
                    ct.setYLine(yLine);
                    ct.setText(null);
                    ct.addElement(e);
                    ct.go();
                }
                else {
                    ct.setText(null);
                    ct.addElement(e);
                }
                document.newPage();
                ct.setSimpleColumn(template.getBody());
                status = ct.go();
                while (ColumnText.hasMoreText(status)) {
                    document.newPage();
                    ct.setSimpleColumn(template.getBody());
                    status = ct.go();
                }
            }
        }
        // step 5
        document.close();
    }
    
    public static void main(String[] args) throws IOException, DocumentException {
        File file = new File(DEST);
        file.getParentFile().mkdirs();
        new FillTemplate3().createPdf(DEST);
    }
}
FillTemplate4.java
package sandbox.xmlworker.reporting;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.pdf.ColumnText;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.tool.xml.ElementList;
import com.itextpdf.tool.xml.Tag;
import com.itextpdf.tool.xml.WorkerContext;
import com.itextpdf.tool.xml.html.DefaultTagProcessorFactory;
import com.itextpdf.tool.xml.html.Div;
import com.itextpdf.tool.xml.html.TagProcessorFactory;
import com.itextpdf.tool.xml.html.table.Table;
import com.itextpdf.tool.xml.html.table.TableData;
import com.itextpdf.tool.xml.html.table.TableRow;
import com.itextpdf.tool.xml.html.table.TableRowElement;
import sandbox.WrapToTest;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@WrapToTest
public class FillTemplate4 {
    
    public static final String DEST = "results/xmlworker/report4.pdf";
    public static final String PDF = "resources/pdfs/stationery.pdf";
    public static final String XML = "resources/xml/movies.xml";
    public static final String CSS = "resources/xml/style4.css";
    
    
    public void createPdf(String result) throws IOException, DocumentException {
        FillTemplateHelper template = new FillTemplateHelper(PDF);
        template.setSender("Bruno Lowagie\nAdolf Baeyensstraat 121\n9040 Sint-Amandsberg\nBELGIUM");
        template.setReceiver("iText Software Corp.\nCambridge Innovation Center\n1 Broadway, 14th Floor\nCambridge, MA 02142 USA");
        // step 1
        Document document = new Document(template.getPageSize());
        // step 2
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(result));
        writer.setPageEvent(template);
        // step 3
        document.open();
        // step 4
        ColumnText ct = new ColumnText(writer.getDirectContent());
        ct.setSimpleColumn(template.getBody());
	ElementList elements = FillTemplateHelper.parseHtml(XML, CSS, getTagProcessorFactory());
        int status;
        float yLine;
        for (Element e : elements) {
            if (!ColumnText.isAllowedElement(e))
                continue;
            yLine = ct.getYLine();
            ct.addElement(e);
            status = ct.go(true);
            if (ColumnText.hasMoreText(status) && yLine < 140) {
                document.newPage();
                ct.setSimpleColumn(template.getBody());
            }
            else {
                ct.setYLine(yLine);
            }
            ct.setText(null);
            ct.addElement(e);
            status = ct.go();
            while (ColumnText.hasMoreText(status)) {
                document.newPage();
                ct.setSimpleColumn(template.getBody());
                status = ct.go();
            }
        }
        // step 5
        document.close();
    }
    
    protected TagProcessorFactory getTagProcessorFactory() {
        TagProcessorFactory factory = new DefaultTagProcessorFactory();
        factory.addProcessor(new Div(), "description", "moviecountry");
        factory.addProcessor(new Div(), "title", "country");
        factory.addProcessor(new Table(), "movies");
        factory.addProcessor(new TableRow(), "movie");
        factory.addProcessor(new TableRow() {
	    public List end(WorkerContext ctx, final Tag tag, final List currentContent) {
    	        List l = new ArrayList(1);
                l.add(new TableRowElement(currentContent, TableRowElement.Place.HEADER));
                return l;
            }
        }, "movieheader");
        factory.addProcessor(new TableData(), "column1", "columnheader1", "column2", "columnheader2", "column3", "columnheader3");
        return factory;
    }
    
    public static void main(String[] args) throws IOException, DocumentException {
        File file = new File(DEST);
        file.getParentFile().mkdirs();
        new FillTemplate4().createPdf(DEST);
    }
}
FillTemplateHelper.java
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package sandbox.xmlworker.reporting;

import com.itextpdf.text.Chunk;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.ExceptionConverter;
import com.itextpdf.text.Font;
import com.itextpdf.text.Image;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.AcroFields;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.ColumnText;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfPageEventHelper;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfTemplate;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.tool.xml.ElementList;
import com.itextpdf.tool.xml.XMLWorker;
import com.itextpdf.tool.xml.XMLWorkerHelper;
import com.itextpdf.tool.xml.css.CssFile;
import com.itextpdf.tool.xml.css.StyleAttrCSSResolver;
import com.itextpdf.tool.xml.html.TagProcessorFactory;
import com.itextpdf.tool.xml.parser.XMLParser;
import com.itextpdf.tool.xml.pipeline.css.CSSResolver;
import com.itextpdf.tool.xml.pipeline.css.CssResolverPipeline;
import com.itextpdf.tool.xml.pipeline.end.ElementHandlerPipeline;
import com.itextpdf.tool.xml.pipeline.html.HtmlPipeline;
import com.itextpdf.tool.xml.pipeline.html.HtmlPipelineContext;

import java.io.FileInputStream;
import java.io.IOException;
import java.nio.charset.Charset;
import java.text.DateFormat;
import java.util.Calendar;
import java.util.Locale;

/**
 *
 * @author iText
 */
public class FillTemplateHelper extends PdfPageEventHelper {
    // initialized in constructor
    protected PdfReader reader;
    protected Rectangle pageSize;
    protected Rectangle body;
    protected float mLeft, mRight, mTop, mBottom;
    protected Rectangle to;
    protected Rectangle from;
    protected Rectangle date;
    protected Rectangle footer;
    protected BaseFont basefont;
    protected Font font;
    // initialized with setter
    protected String sender = "";
    protected String receiver = "";
    // initialized upon opening the document
    protected PdfTemplate background;
    protected PdfTemplate total;
    protected String today;
        
    public FillTemplateHelper(String stationery) throws IOException, DocumentException {
        reader = new PdfReader(stationery);
        AcroFields fields = reader.getAcroFields();
        pageSize = reader.getPageSize(1);
        body = fields.getFieldPositions("body").get(0).position;
        mLeft = body.getLeft() - pageSize.getLeft();
        mRight = pageSize.getRight() - body.getRight();
        mTop = pageSize.getTop() - body.getTop();
        mBottom = body.getBottom() - pageSize.getBottom();
        to = fields.getFieldPositions("to").get(0).position;
        from = fields.getFieldPositions("from").get(0).position;
        date = fields.getFieldPositions("date").get(0).position;
        footer = fields.getFieldPositions("footer").get(0).position;
        basefont = BaseFont.createFont();
        font = new Font(basefont, 12);
    }

    public void setSender(String sender) {
        this.sender = sender;
    }
    public void setReceiver(String receiver) {
        this.receiver = receiver;
    }

    public Rectangle getPageSize() {
        return pageSize;
    }

    public float getmLeft() {
        return mLeft;
    }

    public float getmRight() {
        return mRight;
    }

    public float getmTop() {
        return mTop;
    }

    public float getmBottom() {
        return mBottom;
    }
    
    public Rectangle getBody() {
        return body;
    }

    public String getToday() {
        return today;
    }

    public void setToday(String today) {
        this.today = today;
    }

    @Override
    public void onOpenDocument(PdfWriter writer, Document document) {
        background = writer.getImportedPage(reader, 1);
        total = writer.getDirectContent().createTemplate(30, 15);
        Calendar c = Calendar.getInstance();
        c.set(2015, 9, 13);
        today = DateFormat.getDateInstance(DateFormat.LONG, Locale.US).format(c.getTime());
    }
    
    @Override
    public void onEndPage(PdfWriter writer, Document document) {
        PdfContentByte canvas = writer.getDirectContentUnder();
        // background
        canvas.addTemplate(background, 0, 0);
        try {
            // date
            ColumnText ct = new ColumnText(canvas);
            ct.setSimpleColumn(date);
            ct.addText(new Chunk(today, font));
            ct.go();
            // footer (page X of Y)
            ct.setSimpleColumn(footer);
            ct.addText(new Chunk("page " + writer.getPageNumber(), font));
            ct.addText(new Chunk(Image.getInstance(total), 0, 0));
            ct.go();
            // from address
            ct.setSimpleColumn(from);
            ct.addElement(new Paragraph(sender, font));
            ct.go();
            // to address
            ct.setSimpleColumn(to);
            ct.addElement(new Paragraph(receiver, font));
            ct.go();
        } catch (DocumentException e) {
            // can never happen, but if it does, we want to know!
            throw new ExceptionConverter(e);
        }
    }
    
    @Override
    public void onCloseDocument(PdfWriter writer, Document document) {
        // we only know the total number of pages at the moment the document is closed.
        String s = "/" + (writer.getPageNumber() - 1);
        Phrase p = new Phrase(12, s, font);
        ColumnText.showTextAligned(total, Element.ALIGN_LEFT, p, 0.5f, 0, 0);
    }

    public static ElementList parseHtml(String content, String style, TagProcessorFactory tagProcessors) throws IOException {
        // CSS
        CSSResolver cssResolver = new StyleAttrCSSResolver();
        CssFile cssFile = XMLWorkerHelper.getCSS(new FileInputStream(style));
        cssResolver.addCss(cssFile);
        // HTML
        HtmlPipelineContext htmlContext = new HtmlPipelineContext(null);
        htmlContext.setTagFactory(tagProcessors);
        htmlContext.autoBookmark(false);
        // Pipelines
        ElementList elements = new ElementList();
        ElementHandlerPipeline end = new ElementHandlerPipeline(elements, null);
        HtmlPipeline html = new HtmlPipeline(htmlContext, end);
        CssResolverPipeline css = new CssResolverPipeline(cssResolver, html);
        // XML Worker
        XMLWorker worker = new XMLWorker(css, true);
        XMLParser p = new XMLParser(worker);

        p.parse(new FileInputStream(content),Charset.forName("cp1252"));
        return elements;
    }
}
Contact

Still have questions? 

We're happy to answer your questions. Reach out to us and we'll get back to you shortly.

Contact us
Stay updated

Join 11,000+ subscribers and become an iText PDF expert by staying up to date with our new products, updates, tips, technical solutions and happenings.

Subscribe Now