我正在关注 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 循环“for (Element e ...”) 的行会导致以下异常:
java.lang.ClassCastException:com.itextpdf.tool.xml.html.pdfelement.NoNewLineParagraph 无法转换为 com.itextpdf.text.Element
为什么?我无法通过谷歌搜索找到有关此异常的任何信息。
在这种情况下,我试图使用的由 message.getContent() 返回的 html-snippet 最初看起来像这样:
<html>
<head></head>
<body>
justrandomtexthere
</body>
</html>