问题描述
我正在关注itextpdf示例 http://itextpdf.com/sandbox/htmlworker/HtmlContentForCell.
I'm following the itextpdf example 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 ..."的行)导致以下异常:
The line with the for-loop "for (Element e ..." causes the following exception:
java.lang.ClassCastException:com.itextpdf.tool.xml.html.pdfelement.NoNewLineParagraph无法转换为com.itextpdf.text.Element
为什么?我无法通过谷歌搜索找到有关此异常的任何信息.
Why? I can't find any info on this exception by googling.
在这种情况下,我试图使用的由message.getContent()返回的html片段本来看起来像这样:
In this case, the html-snippet - returned by message.getContent() - I was trying to use, looks originally like this:
<html>
<head></head>
<body>
justrandomtexthere
</body>
</html>
推荐答案
问题已解决.
这是由于我的itextpdf和xmlworker版本略有不同所致.
It was caused by my itextpdf and xmlworker being slightly different versions.
通过获得两个依赖项的完全相同的版本(在我的情况下为5.5.5)解决了这个问题和许多其他问题.
This and MANY other problems were solved by getting the exact same versions (5.5.5 in my case) of both dependencies.
在将我的头猛烈地撞到墙上两天后,我对此压力还不够大:为避免itext和xmlworker出现大量问题,请确保它们始终与您的项目中的版本完全相同.
After 2 days of banging my head to the wall rigorously I cannot stress this enough: To avoid tons of problems with itext and xmlworker, make sure they are always the exact same version in your project.
希望这对其他人有帮助.
Hopefully this is helpful to others.
这篇关于NoNewLineParagraph无法转换为Element的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!