0

我正在使用 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();

现在我的问题是我能够使用上面的代码将 html 转换为 pdf。但如果我的 html 页面包含table标记,它将创建相同大小的td。如何在生成的 pdf 中设置td标签的宽度?提前致谢

4

1 回答 1

2

最后我得到了解决方案:

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();
        }
于 2013-08-06T10:31:04.197 回答