NoNewLineParagraph无法强制转换为Element

时间:2015-03-05 06:56:26

标签: java html parsing itext xmlworker

我关注了itextpdf示例http://itextpdf.com/sandbox/htmlworker/HtmlContentForCell

我有以下代码:

// Relevant code from main part of the class:

   ByteArrayOutputStream baos = new ByteArrayOutputStream();
   Document document = new Document(PageSize.A4, 40, 40, 40, 40);
   PdfWriter writer = PdfWriter.getInstance(document, baos);
   document.open();
   document.add(buildContent());
   document.close();

// method that should provide content to the document.

public PdfPTable buildContent() throws IOException {
    InfoList infoList = infoListInstance.get();
    PdfPTable table = new PdfPTable(2);
    for (InfoListMessage message
            : infolistList.getMessages()) {
        renderMessageMetadata(message, table);
        renderMessageContent(message, table);
    }
    return table;
}

// method where the problem occurs and exception is thrown in the for-loop line

public void renderMessageContent(
        InfoListMessage message,
        PdfPTable table) throws IOException {

PdfPCell cell = new PdfPCell();

for (Element e : XMLWorkerHelper.parseToElementList(message.getContent(), null)) {
    cell.addElement(e);
}  
    table.addCell(cell);
}

带有for循环的行#34; for(元素e ..."导致以下异常:

java.lang.ClassCastException:com.itextpdf.tool.xml.html.pdfelement.NoNewLineParagraph无法转换为com.itextpdf.text.Element

为什么呢?我无法通过Google搜索找到有关此例外的任何信息。

在这种情况下,html-snippet - 由message.getContent()返回 - 我试图使用,看起来原来是这样的:

<html>
 <head></head>
 <body>
 justrandomtexthere
 </body>
</html>

1 个答案:

答案 0 :(得分:2)

问题解决了。

这是由我的itextpdf和xmlworker版本略有不同造成的。

通过获得两个依赖项的完全相同的版本(在我的情况下为5.5.5),解决了这个和许多其他问题。

经过2天严格敲打墙壁后,我无法强调这一点:为了避免使用itext和xmlworker出现大量问题,确保它们始终与项目中的版本完全相同。

希望这对其他人有帮助。

相关问题