使用parseToElementList

时间:2016-08-21 18:54:28

标签: html itext

我正在使用Java中的itextpdf创建一个简单的pdf。我需要将pre标签中包含的html添加到一些单元格中(来自JTextPane,其中pre标签完美地工作)。 我这样做,这样用户可以在生成pdf时保留其标签,空格,粗体,斜体等。

这是解析的html(直接来自JTextPane,然后由JSoup清理):

<html>\n 
<head></head>\n
 <body>\n
  <pre><b>SomePerson Surname \n\n

</b>10 Acme Drive<b>
\nEmail:\tsomeperson@gmail.com</b></pre> \n
 </body>\n
</html>

任何帮助将不胜感激。 这是输出:

**SomePerson Surname**    
10 Acme Drive    
**Email:**    
someperson@gmail.com

这是应该看的样子(JTextPane渲染它就好了):

**SomePerson Surname**

10 Acme Drive
**Email:**  someperson@gmail.com

这是我使用itextpdf添加html元素的简单方法:

private void CreateHTMLPdfCell(PdfPTable topTable, String html, int horizontalAlignment, int border, int colSpan) {

    String CSS = "pre {\n" +
    "    display: inline;\n" +
    "    margin: 0;\n" +
    "}";
    PdfPCell cell = new PdfPCell();
    cell.setHorizontalAlignment(horizontalAlignment);
    cell.setBorder(border);
    cell.setColspan(colSpan);   

    org.jsoup.nodes.Document doc = Jsoup.parse(html);          
    Whitelist WHITELIST = Whitelist.relaxed();
    Cleaner cleaner = new Cleaner(WHITELIST);
    org.jsoup.nodes.Document clean = cleaner.clean(doc);

    try {
        for (Element e : XMLWorkerHelper.parseToElementList(clean.html(), CSS)) {
            cell.addElement(e);
        }
    }
    catch(IOException ex) {
    }
    topTable.addCell(cell);
}

0 个答案:

没有答案
相关问题