在java中使用htmlworker将html转换为pdf
我正在使用htmlworker(itext库)将html文档转换为pdf,如下所示在java中使用htmlworker将html转换为pdf,java,itext,Java,Itext,我正在使用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))
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();
现在我的问题是,我能够使用上述代码将html转换为pdf。
但是如果我的html页面包含表标记,它将创建大小相同的td。如何在生成的pdf中设置td标记的宽度?提前感谢最终我得到了解决方案:
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();
}