html to pdf

public static void main(String[] args) throws Exception{
         String htmlFile = "D:/Demo.html";
        String pdfFile = "D:/test/Pdf.pdf";
        InputStream htmlFileStream = new FileInputStream(htmlFile);
                
        // 创建一个document对象实例
        com.itextpdf.text.Document document = new com.itextpdf.text.Document();
        // 为该Document创建一个Writer实例
        PdfWriter pdfwriter = PdfWriter.getInstance(document,
                new FileOutputStream(pdfFile));
        pdfwriter.setViewerPreferences(PdfWriter.HideToolbar);
        // 打开当前的document
        document.open();
        
        BaseFont baseFont = BaseFont.createFont("C:/Windows/Fonts/Simsunb.TTF",BaseFont.IDENTITY_H,BaseFont.NOT_EMBEDDED);
        Font font = new Font(baseFont);    
        document.add(new Paragraph("解决中文问题了!",font)); 
        InputStreamReader isr = new InputStreamReader(htmlFileStream, "UTF-8");
        XMLWorkerHelper.getInstance().parseXHtml(pdfwriter, document, isr);
        document.close();
}
 public static void main(String[] args)throws Exception {
       String inputFile = "E:/workspace/PDF/WebContent/WEB-INF/signfileInfo.html";
        String outputFile = "E:/workspace/PDF/WebContent/WEB-INF/signfileInfo.pdf";

        OutputStream os = new FileOutputStream(outputFile);       
        ITextRenderer renderer = new ITextRenderer();       
        String url = new File(inputFile).toURI().toURL().toString();   

        renderer.setDocument(url);     

        // 解决中文支持问题       
        ITextFontResolver fontResolver = renderer.getFontResolver();      
        fontResolver.addFont("C:/Windows/Fonts/SIMSUN.TTC", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);       
        //解决图片的相对路径问题  
        renderer.getSharedContext().setBaseURL("file:///E:/workspace/PDF/WebContent/WEB-INF/");  
        renderer.layout();      
        renderer.createPDF(os);    

        os.flush();  
        os.close();  
        System.out.println("转换完成!");
    
}

html代码需要严格规范,所有标签都要有对应的/>进行关闭 
记得用html包围, 
开始的时候没有用这个,导致了一个麻烦的问题,还查了好久才发现。 
为了支持中文,不仅要在java代码中引入字体文件,还需要在html中引用 
body { 
font-family: SimSun; 

原先的core-renderer.jar不支持中文换行功能,有人修改了源码 
中文换行包 
所用的其他几个jar包分别为: 
iText-2.0.8.jar (必需是2.0.8版本)
iTextAsian.jar 
iTextAsianCmaps.jar

猜你喜欢

转载自www.cnblogs.com/Yusco/p/9448889.html