net.dervism.FlyingSaucerDemo.java Source code

Java tutorial

Introduction

Here is the source code for net.dervism.FlyingSaucerDemo.java

Source

package net.dervism;

import com.lowagie.text.DocumentException;
import com.lowagie.text.pdf.BaseFont;
import org.apache.commons.io.IOUtils;
import org.xhtmlrenderer.pdf.ITextFontResolver;
import org.xhtmlrenderer.pdf.ITextRenderer;
import utils.TemplateUtils;
import static utils.TemplateUtils.safestring;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URISyntaxException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * User: dervism
 * Date: 11.12.13
 * Time: 10:11
 */
public class FlyingSaucerDemo {

    /**
     * This tool uses a customizable XHTML template that supports the CSS 2.1 specification.
     *
     * Included with this project is two fonts supporting a large set of the UNICODE charset,
     * meaning that you can use HTML entities like ☑ (checked checkbox special character ).
     * With UNICODE support you can easily create PDF's with complex symbols for math, currency,
     * geometry and many more. See this page for the full list of UNICODE characters available:
     * http://www.utf8-chartable.de/unicode-utf8-table.pl
     *
     * Fonts:
     * Source Sans Pro (SIL Open Font License (OFL), open source, free for personal and commercial use)
     * Source Sans Pro, Adobe's first open source typeface family, was designed by Paul D. Hunt. It is a
     * sans serif typeface intended to work well in user interfaces.
     *
     * DejaVu Sans, Freeware, (free for personal and commercial use)
     *
     * Font are downloaded from fontspace.com:
     * http://www.fontspace.com/category/unicode
     *
     * This tool is built on Flying Saucer 9.0.4 (GNU LGPL license) and IText 2.1.7 (dual licensed
     * under MPL/LGPL) frameworks. The template is CSS-paged XHTML
     *
     * @param templatepath
     * @param params
     * @return
     * @throws DocumentException
     * @throws IOException
     * @throws URISyntaxException
     */
    public byte[] toPdf(String templatepath, Map<String, String> params)
            throws DocumentException, IOException, URISyntaxException {

        InputStream resourceAsStream = this.getClass().getResourceAsStream(templatepath);
        String template = IOUtils.toString(resourceAsStream);

        // collect the generated data in a buffer
        ByteArrayOutputStream os = new ByteArrayOutputStream();

        if (template != null) {

            // customs params to be replaced
            for (String param : params.keySet()) {
                String replacewith = params.get(param);
                template = template.replaceFirst(param, safestring(replacewith));
            }

            Calendar today = Calendar.getInstance();
            SimpleDateFormat shortDate = new SimpleDateFormat("dd-MM-yyyy");

            // extra utiliy tags that can be used in the template
            template = template.replaceAll("#shortdate", "" + shortDate.format(today.getTime()));
            template = template.replaceAll("#pagebreak", TemplateUtils.getPageBreak());

            // choose which font to use
            template = template.replaceAll("#fontfamily", TemplateUtils.UNICODE_TRUETYPE_SOURCE_SANS_PRO);

            // example unicode characters for rendering two 'ballot box' characters
            template = template.replaceAll("#checked", "&#9745;");
            template = template.replaceAll("#unchecked", "&#9744;");

            // prepare the 'Flying Saucer' and IText frameworks
            ITextRenderer render = new ITextRenderer();

            // we need a font resolver for loading our custom fonts
            ITextFontResolver resolver = render.getFontResolver();

            // unicode truetype font supporting 655 characters
            resolver.addFont(this.getClass().getResource("/fonts/SourceSansPro-Regular.ttf").getPath(),
                    BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);

            // unicode truetype font supporting 5572 characters
            // this font supports almost all the special characters ranging
            // from U+25A0 to U+25FF ("Geometric Shapes")
            resolver.addFont(this.getClass().getResource("/fonts/DejaVuSans.ttf").getPath(), BaseFont.IDENTITY_H,
                    BaseFont.NOT_EMBEDDED);

            // insert the template with replaced values
            render.setDocumentFromString(template);

            // render XHTML and CSS 2.1
            render.layout();

            // create the final PDF
            render.createPDF(os);
        }

        // return the generated bytes
        return os.toByteArray();
    }

}