1. 程式人生 > >PDF技術(四)-Html/URL轉PDF檔案

PDF技術(四)-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還在尋找可行方案中。。