HTML 转换为 PDF
这种生成 PDF 的方式,不需要模板和 JSON 数据,只需一个标准的 HTML 文件,或者标准的 HTML 字符串。
java
String htmlPath = "/test/convert.html";
String baseUrl = "/test/";
String outputPdf = "/test/convert.pdf";
int pageWidth = 842;
int pageHeight = 596;
CConverterProperties properties = new CConverterProperties();
CSize size = new CSize(pageWidth, pageHeight);
properties.setPageSize(size);
properties.setBaseUri(baseUrl);
CFontProvider fontProvider = new CFontProvider();
properties.setFontProvider(fontProvider);
CHtmlConverter.CErrorCode id = CHtmlConverter.ConvertToPdf(htmlPath, outputPdf, properties);HTML 可以是内容字符串、InputStream、文件对象或文件路径。生成的 PDF 可以是 OutputStream、文件对象或文件路径。 前面的示例使用了文件路径,而以下是使用其他类型的示例。
使用输入流与输出流:
java
String htmlPath = "/test/convert_1.html";
String outPdfPath = "/test/outPdf.pdf";
try {
InputStream htmlIn = new FileInputStream(htmlPath);
OutputStream pdfOut = new FileOutputStream(outPdfPath);
CHtmlConverter.CErrorCode error = CHtmlConverter.ConvertToPdf(htmlIn, pdfOut);
} catch (Exception e) {
}使用内容字符串:
java
String htmlPath = "/test/convert_1.html";
String outPdfPath = "/test/outPdf.pdf";
try {
String htmlStr = getFileContent(htmlPath);
OutputStream pdfOut = new FileOutputStream(outPdfPath);
CHtmlConverter.CErrorCode error = CHtmlConverter.ConvertToPdf(htmlStr, pdfOut);
} catch (Exception e) {
}使用文件:
java
String htmlPath = "/test/convert_1.html";
String outPdfPath = "/test/outPdf.pdf";
try {
File htmlFile = new File(htmlPath);
File pdfFile = new File(outPdfPath);
CHtmlConverter.CErrorCode error = CHtmlConverter.ConvertToPdf(htmlFile, pdfFile);
} catch (Exception e) {
}