1

I want to add a paragraph, containing HTML, to a document.
As far as I know, iText only supports adding HTML to a document directly via XMLWorkerHelper.

Furthermore I want to change the font of the HTML, but this can be done with a css-file.

My approach is similar to this code:

XMLWorkerHelper worker = XMLWorkerHelper.getInstance();
worker.parseXHtml(pdfWriter, document, fis);

But this solution is writing to the document directly. I want to add the HTML to a paragraph, so I may add some additional formatting to that section.

Alexis Pigeon
  • 7,423
  • 11
  • 39
  • 44
MST
  • 19
  • 1
  • 3
  • Possible the duplicate http://stackoverflow.com/questions/235851/using-itext-to-convert-html-to-pdf – Akshay Joy May 21 '13 at 12:01
  • Nearly what I need, but they only create complete documents, too. What I need is the possibility to add sections of HTML to a document. I will try to create a seperate document and merge both documents. – MST May 21 '13 at 13:11

2 Answers2

2
String html = "<p>Html code here</p>";
 Paragraph comb = new Paragraph();

StringBuilder sb = new StringBuilder();
sb.append(html);

ElementList list = XMLWorkerHelper.parseToElementList(sb.toString(), null);
for (Element element : list) {
    comb.add(element);
}

para = new Paragraph(comb);
cell = new PdfPCell(para);
cell.setHorizontalAlignment(Element.ALIGN_LEFT);
cell.setBorder(Rectangle.NO_BORDER);
cell.setPaddingTop(0);
cell.setPaddingBottom(15f);
cell.setLeading(3f, 1.2f);

table.addCell(cell);
SeniorJD
  • 6,946
  • 4
  • 36
  • 53
FlyingTurtle
  • 145
  • 4
  • 19
1

Go to parsing HTML step by step. In that example, the final pipeline is a PdfWriterPipeline which isn't what you want (because this pipeline writes stuff to the document). You want to replace this final pipeline with an ElementHandlerPipeline, converting all the HTML tags that are encountered to an ElementList.

Once you have this list of Element instances, it's up to you to decide what to do with it (adding them to a Paragraph is one option).

Bruno Lowagie
  • 75,994
  • 9
  • 109
  • 165