使用iText把html转成pdf

1、首先要引入iText包,下载地址:https://github.com/itext/itextpdf/releases

下面是一个小demo:

public class HTML2PDF {
    public static void main(String[] args) throws Exception {
        String inputFile = "D:\\07.Android\\dev\\ZHtestUeditor\\WebRoot\\pdfTest.html";
        String outputFile = "D:\\a.pdf";
        convertHtmlToPdf(inputFile,outputFile);
    }
    
    
    public static boolean convertHtmlToPdf(String inputFile, String outputFile)  
            throws Exception {  
                  
                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:/D:/07.Android/dev/ZHtestUeditor/WebRoot/");
                renderer.layout();      
                renderer.createPDF(os);    
                  
                os.flush();  
                os.close();  
                return true;  
            }  

}


你可能感兴趣的:(java基础知识)