Java implementation of HTML to PDF of several methods-mainly to solve the problem of Chinese garbled
First: Colleagues in the HTML to PDF encountered garbled problem
*****************************************************************
She uses the Itext method to implement HTML dump to PDF, the code is as follows:
1 ImportJava.io.FileInputStream;2 ImportJava.io.FileOutputStream;3 4 Importcom.itextpdf.text.Document;5 Importcom.itextpdf.text.PageSize;6 ImportCom.itextpdf.text.pdf.PdfWriter;7 ImportCom.itextpdf.tool.xml.XMLWorkerHelper;8 9 Public classHtmltopdf {Ten Public Static FinalString HTML = "D:/printenforcement.htm"; One Public Static voidMain (string[] args) { A Try { - -Document document =NewDocument (pagesize.letter); thePDFWriter PDFWriter =pdfwriter.getinstance (document, - NewFileOutputStream ("D://testpdf.pdf")); - Document.open (); -Document.addauthor ("Test"); +Document.addcreator ("Test"); -Document.addsubject ("Test"); + document.addcreationdate (); ADocument.addtitle ("XHTML to PDF"); at -Xmlworkerhelper worker =xmlworkerhelper.getinstance (); - -Worker.parsexhtml (PDFWriter, document,NewFileInputStream (HTML),NULL,NewAsianfontprovider ()); - document.close (); -System.out.println ("Done."); in}Catch(Exception e) { - e.printstacktrace (); to } + } - the}
1 ImportCom.itextpdf.text.BaseColor;2 ImportCom.itextpdf.text.Font;3 ImportCom.itextpdf.text.pdf.BaseFont;4 ImportCom.itextpdf.tool.xml.XMLWorkerFontProvider;5 6 Public classAsianfontproviderextendsXmlworkerfontprovider {7 8 PublicFont GetFont (FinalString FontName,FinalString encoding,9 Final BooleanEmbeddedFinal floatSizeFinal intstyle,Ten FinalBasecolor color) { OneBasefont BF =NULL; A Try { -BF = Basefont.createfont ("Stsong-light", "Unigb-ucs2-h", - basefont.not_embedded); the}Catch(Exception e) { - e.printstacktrace (); - } -Font font =NewFont (BF, size, style, color); + font.setcolor (color); - returnfont; + } A}
The idea of the code is simple, a PDFWriter class is responsible for outputting PDF parameters, a document as a parameter in the method, a xmlworkhelper is responsible for converting HTML into PDF documents;
In another class, Xmlworkerfontprovider is currently primarily written about the settings for font parameters.
Two Java files can display a normal PDF file.
Test Code demo included:
Java implementation of HTML to PDF summary