產製PDF在拉版時往往相對耗時,尤其是在有多頁的情況下相對搞工。測出來HTML FILE直轉PDF效果還不賴,做個備忘。
import com.itextpdf.html2pdf.ConverterProperties;
import com.itextpdf.html2pdf.HtmlConverter;
import com.itextpdf.html2pdf.resolver.font.DefaultFontProvider;
import com.itextpdf.html2pdf.HtmlConverter;
import com.itextpdf.html2pdf.resolver.font.DefaultFontProvider;
import com.itextpdf.io.font.FontProgram;
import com.itextpdf.io.font.FontProgramFactory;
public void ConvertPDF(String htmlPath ) {
String src = htmlPath;
try {
ConverterProperties properties = new ConverterProperties();
DefaultFontProvider fontProvider = new DefaultFontProvider();
FontProgram fontProgram;
try {
fontProgram = FontProgramFactory.createFont("c:\\windows\\fonts\\kaiu.TTF");
fontProvider.addFont(fontProgram);
properties.setFontProvider(fontProvider);
} catch (IOException e) {
System.out.println("creat base font erro:" + e );
}
HtmlConverter.convertToPdf(new File(src), new File(htmlPath.replace(".html", ".pdf")), properties);
} catch (Exception ex) {
System.out.println(ex);
}
}
String src = htmlPath;
try {
ConverterProperties properties = new ConverterProperties();
DefaultFontProvider fontProvider = new DefaultFontProvider();
FontProgram fontProgram;
try {
fontProgram = FontProgramFactory.createFont("c:\\windows\\fonts\\kaiu.TTF");
fontProvider.addFont(fontProgram);
properties.setFontProvider(fontProvider);
} catch (IOException e) {
System.out.println("creat base font erro:" + e );
}
HtmlConverter.convertToPdf(new File(src), new File(htmlPath.replace(".html", ".pdf")), properties);
} catch (Exception ex) {
System.out.println(ex);
}
}
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>html2pdf</artifactId>
<version>4.0.3</version>
</dependency>
後記:
2022/12/12 使用者反映轉出來的PDF有文字被裁切的問題,檢視後發現Bootstrap的CSS套用上拋了許多Exception出來,看來是HTML套版改用Bootstrap造成的問題,解決方式更新為 V4.0.4 後再檢視PDF成果已無被裁切之情事,結案。
沒有留言:
張貼留言