Use Freemarker and itext to turn HTML into PDF

Source: Internet
Author: User

1. To the HTML to PDF, first of all must solve the Chinese display problem, CSS style problems and possible JS problems, first on the example, their own experience.

2. Download the SIMSUN.TTC font first;

2.demo.html

<!DOCTYPE HTML><HTMLLang= "en"><Head>    <MetaCharSet= "UTF-8"/>    <title>Title</title>    <style>. Color{Color:Green;        }. POS{position:Absolute; Left:200px;Top:5px;width:200px;font-size:10px;        }    </style></Head><Bodystyle= "Font-family:simsun">    <imgsrc= "Logo.png"width= "600px" />    <Divclass= "Color pos">Hello,${name}; </Div></Body></HTML>

3.java Implementing the conversion code

 Packagecom.ra.truck.createpdf;ImportCom.itextpdf.text.pdf.BaseFont;Importcom.lowagie.text.*;ImportCom.lowagie.text.Font;ImportCom.lowagie.text.Rectangle;ImportCom.lowagie.text.pdf.PdfWriter;Importfreemarker.template.Configuration;Importfreemarker.template.Template;ImportOrg.xhtmlrenderer.pdf.ITextFontResolver;ImportOrg.xhtmlrenderer.pdf.ITextRenderer;Importjava.awt.*;ImportJava.io.*;ImportJava.util.HashMap;ImportJava.util.Map;/*** @Auther: Lanhao * @Date: 2018/8/7 11:46 * @Description:*/ Public classJavatopdfhtmlfreemarkerfs {Private Static FinalString DEST = ".. /helloworld_cn_html_freemarker_fs_index.pdf "; Private Static FinalString HTML = "demo.html"; Private Static FinalString FONT = "SIMSUN.TTC";Private Static FinalString Logo_path = "file:/" +pathutil.getcurrentpath () + "/" + "demo448" + ". png"; Private StaticConfiguration freemarkercfg=NULL; Static{freemarkercfg=NewConfiguration (); //Template directory for Freemarker        Try{freemarkercfg.setdirectoryfortemplateloading (NewFile (Pathutil.getcurrentpath ())); } Catch(IOException e) {e.printstacktrace (); }    }     Public Static voidMain (string[] args) {String os=system.getproperty ("Os.name");        SYSTEM.OUT.PRINTLN (OS); Map<String,Object> data =NewHashmap<>(); Data.put ("Name", "Lan Hao"); String content=Freemarkerrender (data,html);    CreatePDF (content,dest); }    /*** Freemarker Rendering HTML*/     Public StaticString Freemarkerrender (map<string, object>data,string htmltmp) {Writer out=NewStringWriter (); Try {            //get the template and set the encoding methodTemplate Template =freemarkercfg.gettemplate (htmltmp); Template.setencoding ("UTF-8"); //merging data models with templatesTemplate.process (data, out);//writes the merged data and template to the stream, the character stream used hereOut.flush (); returnout.tostring (); } Catch(Exception e) {e.printstacktrace (); } finally {            Try{out.close (); } Catch(IOException ex) {ex.printstacktrace (); }        }        return NULL; }    Private Static voidcreatepdf (String content,string dest) {Try{itextrenderer render=NewItextrenderer (); //solve Chinese non-explicit problemsItextfontresolver Fontresolver =Render.getfontresolver ();            Fontresolver.addfont (font,basefont.identity_h,basefont.not_embedded); //parsing HTML generation PDFrender.setdocumentfromstring (content); //solve the problem of picture relative pathRender.getsharedcontext (). Setbaseurl (Logo_path);            Render.layout (); Render.createpdf (NewFileOutputStream (dest)); }Catch(Exception e) {e.printstacktrace (); }    }}

Note: All referenced files are placed in the resource root directory of the project

Use Freemarker and itext to turn HTML into PDF

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.