javahtmlpdfsvgflying-saucer

Svg integration in pdf using flying saucer


I under gone a situation of converting html to pdf, Thankfully I can achieved this through flying saucer api. But My HTML consists of svg tags while converting I am unable to get the svg in pdf. It can be achieved using a Stackoverflow question and Tutorial.

What is meant by the replacedElementFactory?

ChainingReplacedElementFactory chainingReplacedElementFactory 
        = new ChainingReplacedElementFactory();
chainingReplacedElementFactory.addReplacedElementFactory(replacedElementFactory);
chainingReplacedElementFactory.addReplacedElementFactory(new SVGReplacedElementFactory());
renderer.getSharedContext().setReplacedElementFactory(chainingReplacedElementFactory);

Solution

  • It's just an error in the tutorial, the line with replacedElementFactory is not needed.

    Here is my working example.

    Java:

    import java.io.ByteArrayOutputStream;
    import java.io.FileOutputStream;
    import java.io.OutputStream;
    
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    
    import org.w3c.dom.Document;
    import org.xhtmlrenderer.pdf.ITextRenderer;
    
    public class PdfSvg {
        public static void main(String[] args) throws Exception {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            factory.setNamespaceAware(true);
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document inputDoc =  builder.parse("svg.html");
    
            ByteArrayOutputStream output = new ByteArrayOutputStream();
    
            ITextRenderer renderer = new ITextRenderer();
    
            ChainingReplacedElementFactory chainingReplacedElementFactory = new ChainingReplacedElementFactory();
            chainingReplacedElementFactory.addReplacedElementFactory(new SVGReplacedElementFactory());
            renderer.getSharedContext().setReplacedElementFactory(chainingReplacedElementFactory);
    
            renderer.setDocument(inputDoc, "");;
            renderer.layout();
            renderer.createPDF(output);
    
            OutputStream fos = new FileOutputStream("svg.pdf");
            output.writeTo(fos);
        }
    }
    

    HTML:

    <html>
    <head>
    <style type="text/css">
        svg {display: block;width:100mm;height:100mm}
    </style>
    </head>
    <body>
        <div>
            <svg xmlns="http://www.w3.org/2000/svg">
                <circle cx="50" cy="50" r="40" stroke="black" stroke-width="3"
                    fill="red" />
            </svg>
        </div>
    </body>
    </html>
    

    The ChainingReplacedElementFactory, SVGReplacedElement and SVGReplacedElementFactory comes from the tutorial.