The jar file used
Xmlworker-5.5.11.jar
Itextpdf-5.5.11.jar
: Https://pan.baidu.com/s/1i5AIBvZ
The following is the test code
Packagecom.test;ImportJava.io.ByteArrayInputStream;ImportJava.io.ByteArrayOutputStream;ImportJava.io.File;ImportJava.io.FileInputStream;ImportJava.io.FileOutputStream;ImportJava.io.InputStream;Importcom.itextpdf.text.Document;ImportCom.itextpdf.text.pdf.PdfWriter;ImportCom.itextpdf.tool.xml.XMLWorkerHelper; Public classhtml2pdf{ Public Static voidMain (String [] args)throwsException {String Urlsource= Geturlsource (NewFile ("d:/test.html")); String Csssource= Geturlsource (NewFile ("D:/css.css")); Htmltopdf (Urlsource,csssource); } //Support Chinese Public Static voidHtmltopdf (String htmlstr,string csssource)throwsException {String outputFile= "D:/test.pdf"; Document Document=NewDocument (); PDFWriter writer=NULL; Writer= Pdfwriter.getinstance (document,NewFileOutputStream (outputFile)); Document.open (); InputStream bis=NewBytearrayinputstream (Htmlstr.tostring (). GetBytes ());
InputStream cssis = new Bytearrayinputstream (csssource.tostring (). GetBytes ());
Xmlworkerhelper.getinstance (). parsexhtml (writer, document, bis,cssis);
Document.close (); } /*** Obtain the source code of the website through the website domain URL * *@paramURL *@returnString *@throwsException*/ Public StaticString geturlsource (File URL)throwsException {inputstream instream=Newfileinputstream (URL); //get HTML binary data from an input stream byte[] data = Readinputstream (instream);//converts binary data to byte byte dataString Htmlsource =NewString (data); Instream.close (); returnHtmlsource; } /*** transfer binary into byte array * *@paraminstream *@returnbyte[] *@throwsException*/ Public Static byte[] Readinputstream (InputStream instream)throwsException {bytearrayoutputstream OutStream=NewBytearrayoutputstream (); byte[] buffer =New byte[1204]; intLen = 0; while(len = instream.read (buffer))! =-1) {outstream.write (buffer,0, Len); } instream.close (); returnOutstream.tobytearray (); }}
Questions about adding CSS styles to PDFs using Itext to HTML