1

我正在使用 iText 5.5.9 XMLWorker 将 html 转换为 pdf。

<html>
<head></head>
<body>
<div style="width:100%; height:100%;">
    <div>This is sample text.
        <ol>
            <li>
                This is outer list item first
                <ul>
                    <li>Inner list item first</li>
                    <li>Inner list item second</li>
                    <li>Inner list item third</li>
                    <li>Inner list item fourth</li>
                    <li>Inner list item fifth</li>
                </ul>
            </li>
            <li>
                This is outer list item second
            </li>
        </ol>
    </div>
</div>
</body>
</html>

我收到的嵌套列表的输出是:

在此处输入图像描述

转换代码为:

public void createPdf_Using_ElimentList(String outPutPath) {
    Document document = new Document();
    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(outPutPath));
    document.open();
    PdfPCell tempCell = new PdfPCell();
    ElementList elements = null;
    tempCell.setBorder(Rectangle.NO_BORDER);

    elements = parseToElementList_Unicode(clean_str, css);
    if (elements != null) {
        tempCell.setRunDirection(PdfWriter.RUN_DIRECTION_RTL);
        for (com.itextpdf.text.Element e : elements) {
            tempCell.addElement(e);
        }
        tempCell.setPadding(5);
        tempCell.setPaddingBottom(8);

        table.setSplitLate(false);
        table.addCell(tempCell);
        success = true;
    }
    document.add(newTable);

    document.close();
}

public static ElementList parseToElementList_Unicode(String HTMLContent, String CSSContent) {
    PdfPCell tempCell = new PdfPCell();
    ElementList elements = new ElementList();
    CSSResolver cssResolver = new StyleAttrCSSResolver();
    XMLWorkerFontProvider fontProvider = new XMLWorkerFontProvider(XMLWorkerFontProvider.DONTLOOKFORFONTS);

    try {
        InputStream cssIS = new ByteArrayInputStream(CSSContent.getBytes());
        InputStream HTML_IS = new ByteArrayInputStream(HTMLContent.getBytes());

        String dirName = "C:/Tasks/Fonts/";

        fontProvider.register(dirName + "arial.ttf", "Arial");
        CssAppliers cssAppliers = new CssAppliersImpl(fontProvider);
        // HTML
        HtmlPipelineContext htmlContext = new HtmlPipelineContext(cssAppliers);
        htmlContext.setTagFactory(Tags.getHtmlTagProcessorFactory());
        // Pipelines

        ElementHandlerPipeline pdf = new ElementHandlerPipeline(elements, null);
        HtmlPipeline html = new HtmlPipeline(htmlContext, pdf);
        CssResolverPipeline css = new CssResolverPipeline(cssResolver, html);

        // XML Worker
        XMLWorker worker = new XMLWorker(css, true);
        XMLParser p = new XMLParser(worker);

        p.parse(HTML_IS, Charset.forName("UTF-8"));


    } catch (Exception e) {
        e.printStackTrace();
    }
    return elements;

}

使用 iText 7 不是我的选择,因为它不向后兼容。有没有人有 iText 5.5.9 的解决方案。提前致谢。

4

0 回答 0