1. Required jar Package: Org.xhtmlrenderer.flying-saucer-pdf-itext5,itext.itext,maven depends on the following:
1 <dependency> 2 <groupId>org.xhtmlrenderer</groupId> 3 <artifactid >flying-saucer-pdf-itext5</artifactId> 4 <version>9.0.7</version> 5 </ Dependency> 6 <dependency> 7 <groupId>itext</groupId> 8 < Artifactid>itext</artifactid> 9 <version>1.3</version> </dependency >
2. Chinese Support
Because Chinese is present in the HTML code, we need to add Chinese support and need to add the required font files to the Project.
3. Convert PDF Main code
1 /**2 * HTML transcoding to PDF document3 * 4 * @paramcontent to be converted HTML code5 * @paramStoragepath The path saved as a PDF file6 */7 @Override8 public voidparsepdf (string content, string Storagepath) {9FileOutputStream OS =NULL;Ten Try { oneFile File =NewFile (storagepath); a if(!file.exists ()) { - file.createnewfile (); - } theOS =NewFileOutputStream (file); - -Itextrenderer renderer =NewItextrenderer (); - //Resolve Chinese support issues +Itextfontresolver resolver =Renderer.getfontresolver (); -Resolver.addfont ("/static/font/arialuni. TTF ", basefont.identity_h, basefont.not_embedded); + renderer.setdocumentfromstring (content); a //solve relative path problem of picture, picture path must start with file at //renderer.getsharedcontext (). setbaseurl ("file:/"); - renderer.layout (); - renderer.createpdf (os); - -}Catch(documentexception E) { - e.printstacktrace (); in}Catch(ioexception E) { - e.printstacktrace (); to}finally { + if(NULL!=OS) { - Try { the os.close (); *}Catch(ioexception E) { $ e.printstacktrace ();Panax Notoginseng } - } the } +}
4, If you read the HTML code from the file, you need to use InputStream to read, do not use FileReader read, do not know why, using the FileReader read content parsing error
1StringBuilder content =NewStringBuilder ();2 byte[] bys =New byte[1024];3 intlen;4in =NewBufferedinputstream (NewFileInputStream (htmlfilepath));5 while(len = In.read (bys))! =-1) {6Content.append (NewString (bys, 0, len));7}
Java uses flying saucer to implement HTML code to generate PDF documents