PDF技术(四)-Java实现Html/URL转PDF文件

由于Itext对html的转化中,对css不是很支持,在对html进行转化时,会发生样式走样的问题,这个问题任需要解决。

1)使用IText转换

原理:

使用IText将HTML文件转化为PDF文件

缺点:

对CSS样式支持不是很好。

失真情况可能比较大

具体实现

public class HtmlToPdfUtils {
    /**
     * 默认中文字体
     */
    private static final String FONT = "C:\\Windows\\Fonts\\simhei.ttf";

    public static void htmlToPdf(String sourcePath,String tagetPath) throws IOException {
        htmlToPdf(sourcePath,tagetPath,FONT);
    }
    public static void htmlToPdf(String sourcePath,String tagetPath,String fontPath) throws IOException {
        htmlToPdf(sourcePath,tagetPath,fontPath,PageSize.TABLOID);
    }
    public static void htmlToPdf(String sourcePath,String tagetPath,String fontPath,PageSize pageSize) throws IOException {
        // 默认source路径下装载有css、image、以及html等文件的文件夹
        htmlToPdf(sourcePath,tagetPath,fontPath,pageSize,FileUtils.GetFilePath(sourcePath));
    }
    public static void htmlToPdf(String sourcePath,String tagetPath,String fontPath,PageSize pageSize,String baseuri) throws IOException {
        PdfWriter writer = new PdfWriter(tagetPath);
        PdfDocument pdf = new PdfDocument(writer);

        pdf.setTagged();
        // 设置pdf页面大小
        pdf.setDefaultPageSize(pageSize); 
        ConverterProperties properties = new ConverterProperties();
        FontProvider fontProvider = new DefaultFontProvider();
        // 字体
        FontProgram fontProgram = FontProgramFactory.createFont(fontPath);
        fontProvider.addFont(fontProgram);
        properties.setFontProvider(fontProvider); 
        //properties.setBaseUri(html);
        properties.setBaseUri(baseuri); 
        MediaDeviceDescription mediaDeviceDescription = new MediaDeviceDescription(MediaType.SCREEN);
        mediaDeviceDescription.setWidth(pageSize.getWidth());
        properties.setMediaDeviceDescription(mediaDeviceDescription); 
        // 转化
        convertToPdf(sourcePath,pdf, properties);
    }

    private static void convertToPdf(String sourcePath,PdfDocument pdf,ConverterProperties properties ) throws IOException {

        InputStream inputStream = new FileInputStream(sourcePath);
        // 转化
//        HtmlConverter.convertToPdf(new FileInputStream(sourcePath), pdf, properties);
        HtmlConverter.convertToPdf(inputStream, pdf, properties);
        inputStream.close();

    }
    public static void main(String[] args) throws IOException {
        htmlToPdf("F:\\pdf\\1.html","F:\\pdf\\est-04.pdf");
    }
}

具体效果

Converting HTML to PDF _ iText Developers.html

消耗时间:3660

CSS样式丢失:

 

JAVA 将图片转换成pdf文件 - CSDN博客.html

消耗时间:7609

 

样式同样丢失问题

 

itext html转pdf布局问题_百度搜索.html

消耗时间:5485

 

对于HTML转PDF还在寻找可行方案中。。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章