I have a need to create iText Element(s) (or Chunk(s)) that contain HTML. The HTML in part of a HTML document that is parsed into a PDF using the XMLWorker. I've tried using a class that extends the AbstractTagProcessor, but I don't get anything back in the final PDF document. Not sure if this is even possible. Here is the code I'm using:
class Narrative extends AbstractTagProcessor implements TagProcessor {
@Override
public List<com.itextpdf.text.Element> end(WorkerContext ctx, Tag tag, List<com.itextpdf.text.Element> currentContent) {
List<com.itextpdf.text.Element> l = new ArrayList<com.itextpdf.text.Element>();
for (com.itextpdf.text.Element element : currentContent) {
try {
ElementList parsed = XMLWorkerHelper.parseToElementList(element.getChunks().get(0).getContent(), readCSS());
for(com.itextpdf.text.Element elem : parsed) {
l.add(elem);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return l;
}
UPDATE: I think I found the solution. I'm posting it so other may not have to go through what I wen through to find the solution. Feedback welcomed.
class Narrative extends Div implements TagProcessor {
private PdfPTable table = new PdfPTable(1);
public Narrative() {
table.setTotalWidth(650f);
table.setWidthPercentage(100f);
table.setKeepTogether(true);
table.getDefaultCell().setBorder(0);
}
@Override
public List<com.itextpdf.text.Element> end(WorkerContext ctx, Tag tag, List<com.itextpdf.text.Element> currentContent) {
List<com.itextpdf.text.Element> content = new ArrayList<Element>();
try {
content = HTMLWorker.parseToList(new StringReader(currentContent.get(0).getChunks().get(0).getContent()), null);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for(com.itextpdf.text.Element c : content) {
PdfPCell cell = new PdfPCell();
cell.setBorder(0);
cell.addElement(c);
table.addCell(cell);
}
List<com.itextpdf.text.Element> l = new ArrayList<Element>();
l.add(table);
return l;
}