I had this requirement of generating PDF out of HTML content. Users can add any kind of html content on a Rich text editor from few lines to a full paragraph as notes for a file and save it on the server. Now I had to notify other users when some user adds a note. Now in the past I have generated PDF for reports but that was on a structured data straight out of database so I could easily use something like itext or jasperreports but this one seems an interesting problem as user can do any free form html in the editor.
Ultimately the solution came to be:
Ultimately the solution came to be:
- Convert the html added by user into xhtml using JTidy
- Use flying saucer's ITextRenderer (http://code.google.com/p/flying-saucer/) to generate the pdf out of xhtml.
public class TextSectionConverter {
private String notesContent;
public TextSectionConverter(String notesContent) {
this.notesContent = notesContent;
}
public void writeAsPdf(FileOutputStream fos)
throws Exception {
convertToXHTML();
ITextRenderer renderer = new ITextRenderer();
renderer.setDocumentFromString(notesContent);
renderer.layout();
renderer.createPDF(fos);
}
void convertToXHTML() throws Exception {
notesContent = "" + notesContent + "";
StringWriter writer = new StringWriter();
Tidy tidy = new Tidy();
tidy.setTidyMark(false);
tidy.setDocType("omit");
tidy.setXHTML(true);
tidy.setInputEncoding("utf-8");
tidy.setOutputEncoding("utf-8");
tidy.parse(new StringReader(notesContent), writer);
writer.close();
notesContent = writer.toString();
}
Comments
Post a Comment