问题
It's the topic connected with List items in table cell are not formatted. I'm using XmlWorker to process HTML output from formattable control (dijit/Editor from Dojo). There are some blocks (when you use centering or margin formatters) like that:
<div>
<p align="center"><font size="5"><b> <font color="#32cd32">My centered Para</font></b></font><font color="#32cd32"> </font></p>
</div>
However, when I add them to the Paragraph
that is added to the Table like here:
PdfPCell htmlCell = new PdfPCell();
htmlCell.setBackgroundColor(new BaseColor(213, 226, 187));
htmlCell.addElement(html2Para(html));
htmlCell.setPaddingBottom(5);
htmlCell.setPaddingLeft(5);
table.addCell(htmlCell);
private Paragraph html2para(String html) {
final Paragraph para = new Paragraph();
try {
XMLWorkerHelper.getInstance().parseXHtml(new ElementHandler() {
@Override
public void add(Writable wri) {
if (wri instanceof WritableElement) {
List<Element> elems = ((WritableElement) wri).elements();
for (Element elem : elems) {
para.add(elem);
}
}
}
}, new StringReader(StringUtils.trimToEmpty(html)));
} catch (IOException e) {
log.error(e.getMessage(), e);
}
return para;
}
Everything that is inside the Element
that is the instance of PdfDiv
is not visible.
So, when I meet the PdfDiv, I add its content:
private void addElem2para(Element elem, Paragraph target) {
if (elem instanceof PdfDiv) {
for (Element inside : ((PdfDiv)elem).getContent()) {
addElem2para(inside, target);
}
} else {
target.add(elem);
}
}
However, now that formatting like centering or margin that were the properties of the PdfDiv
are 'lost'.
How should one deal with the PdfDiv
elements from XmlWorker?
I'm using iText and XmlWorker in version 5.5.2
回答1:
(I think) I understand your question, but I don't understand your code.
The ParseHtml example shows how I interpreted your question:
StringBuilder sb = new StringBuilder();
sb.append("<div>\n<p align=\"center\">");
sb.append("<font size=\"5\">");
sb.append("<b> <font color=\"#32cd32\">My centered Para</font></b>");
sb.append("</font>");
sb.append("<font color=\"#32cd32\"> </font>");
sb.append("</p>\n</div>");
PdfPTable table = new PdfPTable(1);
PdfPCell cell = new PdfPCell();
ElementList list = XMLWorkerHelper.parseToElementList(sb.toString(), null);
for (Element element : list) {
cell.addElement(element);
}
table.addCell(cell);
document.add(table);
You have some HTML (I stored your HTML snippet in sb
) that you want to parse into a series of iText objects to be added to a table cell.
This is the result of this operation:

That looks pretty much the way I expected.
来源:https://stackoverflow.com/questions/28472400/adding-pdfdiv-to-paragraph