Thursday 7 November 2013

Convert Html To PDF for Simple and Special Char Using Java

Convert Html To PDF

import com.nik.pdf;
import java.io.ByteArrayInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.clapper.util.html.HTMLUtil;
import org.xhtmlrenderer.pdf.ITextRenderer;

public class HtmlToPdf {

    public static void convertHtmlToPdf() {

        try {

            StringBuffer bufferForHtml = new StringBuffer();
            bufferForHtml
                    .append("<html>"
                            + "<head>"
                            + "<style language='text/css'>"
                            + ".c1{font-size:12px;font-family:\"Times New Roman\";}"
                            + ".pos_right{position:relative;left:20px;}"
                            + ".pos_top{position:relative;top:-50px;}"
                            + ".top_alignment{vertical-align:text-top;}"
                            + ".bottom_alignment{vertical-align:text-bottom;}"
                            + "table.layout1 {table-layout:auto;}"
                            + "table.layout2 {table-layout:fixed;}"
                            + "</style>"
                            + "</head>"
                            + "<body class='c1'>"
                            + "<p align=\"center\">This is a test PDF  by Nitesh  &copy;</p>"
                            + "<p>Few mathematical notations : &#8825;&#8904;&#8939; </p>"
                            + "</body></html>");
            String htmlConvert = HTMLUtil
                    .convertCharacterEntities(bufferForHtml.toString());
            DocumentBuilder builder = DocumentBuilderFactory.newInstance()
                    .newDocumentBuilder();
            org.w3c.dom.Document doc = builder.parse(new ByteArrayInputStream(
                    htmlConvert.getBytes("UTF-8")));
            ITextRenderer renderer = new ITextRenderer();
//For mathematical latin symbols use -->renderer.getFontResolver().addFont("E:\\ARIALUNI.TTF",BaseFont.IDENTITY_H, //BaseFont.NOT_EMBEDDED);
//Change  BaseFont for different type of Character encoding like BaseFont.CP152 for chinese char
            renderer.setDocument(doc, null);
            OutputStream outputFile = new FileOutputStream("E:\\test.pdf");
            renderer.layout();
            renderer.createPDF(outputFile);
            outputFile.close();
        }

        catch (Exception e) {
            System.out.println("catch me");
            throw new RuntimeException(e);

        }

    }

    public static void main(String[] arg) {
        convertHtmlToPdf();
    }

}