I am trying to convert an HTML String to a PDF document. But only the text part is printed in PDF, but not SVG. Here is what I have tried.
- Convert HTML string to org.w3c.dom.Document
- Using Flying-Saucer to generate pdf
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.StringReader;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.xhtmlrenderer.layout.SharedContext;
import org.xhtmlrenderer.pdf.ITextRenderer;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import com.lowagie.text.DocumentException;
public class PDFCreator {
public static void main(String[] args) {
PDFCreator pdfCreator = new PDFCreator();
String html = "<!DOCTYPE html> <html> <head> <meta name=\"generator\" content=\"HTML Tidy for Java (vers. 2009-12-01), see jtidy.sourceforge.net\" /> <style type=\"text/css\"> #svg {display:block;}</style> <title>Sample Document</title> </head> <body> <h1>My First HTML Document with SVG</h1> <div id=\"svg\"> <svg width=\"100\" height=\"100\"> <circle cx=\"50\" cy=\"50\" r=\"40\" stroke=\"green\" stroke-width=\"4\" fill=\"yellow\" /></svg></div> </body></html>";
Document document = pdfCreator.createDocument(html);
pdfCreator.create(document);
}
public void create(Document document) {
try {
String outputFile = "D:\\htmlWithSVG.pdf";
OutputStream os = new FileOutputStream(outputFile);
ITextRenderer renderer = new ITextRenderer();
renderer.setDocument(document, null);
ChainingReplacedElementFactory chainingReplacedElementFactory = new ChainingReplacedElementFactory();
chainingReplacedElementFactory.addReplacedElementFactory(new SVGReplacedElementFactory());
SharedContext sharedContext = renderer.getSharedContext();
sharedContext.setReplacedElementFactory(chainingReplacedElementFactory);
renderer.layout();
renderer.createPDF(os);
os.close();
} catch (DocumentException ex) {
ex.printStackTrace();
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
}
public Document createDocument(String xml) {
InputSource inputSource = new InputSource(new StringReader(xml));
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
DocumentBuilder builder = null;
Document document = null;
try {
builder = factory.newDocumentBuilder();
document = builder.parse(inputSource);
} catch (ParserConfigurationException ex) {
ex.printStackTrace();
} catch (SAXException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
return document;
}}
I also reviewed the following tutorial, and the classes ChainingReplacedElementFactoryand SVGReplacedElementFactoryare used from this tutorial.
http://www.samuelrossille.com/home/render-html-with-svg-to-pdf-with-flying-saucer.html
source
share