java pdf 导出方案
java代码
import com.itextpdf.text.DocumentException; import com.itextpdf.text.pdf.BaseFont; import org.xhtmlrenderer.pdf.ITextFontResolver; import org.xhtmlrenderer.pdf.ITextRenderer; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; public class ITextRendererCNWebDiy { public static void main( String[] args ) throws DocumentException, IOException { //注 :如果样式 body里加了,那么 具体的div span里面就不要加,否则显示不出来? 不对,是 div span里的字体写错了 要这么写,不能小写 SimSun String inputFile="index-cn.html"; String outputFile="F:\develop\workspace-idea\iTextStudy\ITextRendererCNWebDiy.pdf"; OutputStream os = new FileOutputStream(outputFile); ITextRenderer renderer = new ITextRenderer(); String url = new File(inputFile).toURI().toURL().toString(); renderer.setDocument("http://120.26.208.6:8090/xieyi.jsp"); // 解决中文支持问题 ITextFontResolver fontResolver = renderer.getFontResolver(); try { //注 俩个方式都可以 但是linux服务器中 估计要用后者 //fontResolver.addFont("C:/Windows/Fonts/simsun.ttc", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED); fontResolver.addFont("src/simsun.ttc", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED); }catch (Exception e){ e.printStackTrace(); } //解决图片的相对路径问题 renderer.getSharedContext().setBaseURL("file:/D:/"); renderer.layout(); try { renderer.createPDF(os); }catch (Exception ex){ ex.printStackTrace(); } os.flush(); os.close(); } }
html文件:
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>HTML to PDF</title> <link href="style.css" rel="stylesheet" type="text/css" /> </head> <body> <h1>HTML to PDF</h1> <p> <span class="itext">itext</span> 5.4.2 <span class="description"> converting HTML to PDF</span> </p> <table> <tr> <th class="label" style="font-size:12.0pt; font-family:SimSun">Title-中午网页</th> <td>iText - Java HTML to PDF 你好网页</td> </tr> <tr> <th>URL</th> <td>http://hmkcode.com/itext-html-to-pdf-using-java</td> </tr> </table> </body> </html>