0

I am using iText 2.1.7 to generate a document from a database. One of the fields I need to add is in XHTML format. I can use the HTMLWorker class to generate the HTML but this is a bit limited.

I convert this to XHTML using the following code:

String url = chapterDesc.getString("description").toString(); // get the HTML string from the database
org.w3c.dom.Document doc = XMLResource.load(new ByteArrayInputStream(url.getBytes())).getDocument();

ITextRenderer renderer = new ITextRenderer();
renderer.setDocument(doc, null);
ByteArrayOutputStream os = new ByteArrayOutputStream();
renderer.layout();
renderer.createPDF(os);

I want to add this information to the document in memory. Is this possible?

Do I need to use PdfStamper? I believe that this requires the document to be closed? If it is possible I would like to avoid using multiple passes to add these descriptions.

Neil
  • 227
  • 2
  • 8

2 Answers2

0

I know it's been more than two years since you've asked, but I'm facing the same problem. I googled for a solution and apparently there is none anywhere to be found. So I had to develop my own and I thought I might as well share it. Hope it'll be useful to someone.

I tried to use flying saucer as you did, but it didn't work for me. My piece of HTML was just a simple table so I could use iText HTMLWorker to do the parsing.

So first I get a PdfStamper as you suggested.

PdfReader template = new PdfReader(templateFileName);
PdfStamper editablePage = new PdfStamper(template, reportOutStream);

Then I work with the document (fill the fields, insert some images) and after that I need to insert an HTML snippet.

//getting a 'canvas' to add parsed elements
final ColumnText page = new ColumnText(editablePage.getOverContent(pageNumber)); 
//finding out the page sizefinal 
Rectangle pagesize = editablePage.getReader().getPageSize(pageNumber);     
//you can define any size here, that will be where your parsed elements will be added
page.setSimpleColumn(0, 0, pagesize.getWidth(), pagesize.getHeight()); 

If you need simple styling, HTMLWorker can do some

StyleSheet styles = new StyleSheet();
styles.loadStyle("h1", "color", "#008080");

//parsing
List<Element> parsedTags = HTMLWorker.parseToList(new StringReader(htmlSnippet), styles); 
for (Element tag : parsedTags)
{       
  page.addElement(tag);
  page.go();
}

These are just some basic ideas of how to do that, hope it helps.

Ilayna
  • 1
  • 2
0

Flying saucer does not work correctly with any version of iText other than 2.0.8. Also since you meantioned creating the pdf in memory are you using JSF, JSP, or servlets? If you are than you can just send your ByteArrayOutputStream as a response on one of these pages using something along the lines of

response.setContentType("application/pdf");
response.setContentLength(os.size());
os.writeTo(response.getOutputStream());
response.flushBuffer();
flyingCaffine
  • 382
  • 1
  • 4
  • 9