由於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還在尋找可行方案中。。