java 在java中使用htmlworker将html转换为pdf
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15500560/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
html to pdf using htmlworker in java
提问by Butani Vijay
i am converting html document to pdf using htmlworker (itext library )as follow
我正在使用 htmlworker(itext 库)将 html 文档转换为 pdf,如下所示
String path = "temp.pdf";
PdfWriter pdfWriter = null;
// create a new document
Document document = new Document();
pdfWriter = PdfWriter.getInstance(document, new FileOutputStream(
path));
document.open();
HTMLWorker htmlWorker = new HTMLWorker(document);
String str = "";
StringBuilder contentBuilder = new StringBuilder();
BufferedReader in = null;
try {
in = new BufferedReader(new FileReader("temp1.html"));
while ((str = in.readLine()) != null) {
contentBuilder.append(str);
}
} catch (IOException e) {
System.out.print("HTML file close problem:" + e.getMessage());
} finally {
in.close();
}
String content = contentBuilder.toString();
htmlWorker.parse(new StringReader(content));
document.close();
now my question is i am able to convert html to pdf using above code. but if my html page contain tabletag it will create tdwith same size. how can i set width of tdtag in generated pdf? thanks in advance
现在我的问题是我可以使用上面的代码将 html 转换为 pdf。但如果我的 html 页面包含table标签,它将创建具有相同大小的td。如何在生成的 pdf 中设置td标签的宽度?提前致谢
回答by Butani Vijay
Finally i got Solution :
最后我得到了解决方案:
try {
// get Instance of the PDFWriter
pdfWriter = PdfWriter.getInstance(document, new FileOutputStream(
path));
//pdfWriter.setPdfVersion(PdfWriter.PDF_VERSION_1_4);
pdfWriter.setLinearPageMode();
pdfWriter.setFullCompression();
// document header attributes
document.addAuthor("");
document.addCreationDate();
document.addProducer();
document.addCreator("aaa");
document.addTitle("");
document.setPageSize(PageSize.A4);
// open document
document.open();
HTMLWorker htmlWorker = new HTMLWorker(document);
String str = "";
StringBuilder contentBuilder = new StringBuilder();
BufferedReader in = null;
System.out.println("Html Content :");
try {
in = new BufferedReader(new FileReader(
htmlfile));
while ((str = in.readLine()) != null) {
contentBuilder.append(str);
System.out.println(str);
}
} catch (IOException e) {
System.out.print("HTML file close problem:" + e.getMessage());
} finally {
in.close();
System.gc();
}
String content = contentBuilder.toString();
htmlWorker.parse(new StringReader(content));
document.close();
pdfWriter.close();
}
catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (DocumentException e) {
e.printStackTrace();
}