SVG line not getting rendered properly in PDF

2019-05-21 08:23发布

问题:

I am using iText and some SVG rendering library.

I want to render a SVG image to PDF. I am using following code to do that. Now the problem is I am giving an area chart SVG to it, it is not rendering line properly. Attaching screenshots.

Following classes has been used:

import org.apache.batik.bridge.BridgeContext;
import org.apache.batik.bridge.DocumentLoader;
import org.apache.batik.bridge.GVTBuilder;
import org.apache.batik.bridge.UserAgent;
import org.apache.batik.bridge.UserAgentAdapter;
import org.apache.batik.dom.svg.SAXSVGDocumentFactory;
import org.apache.batik.gvt.GraphicsNode;
import org.apache.batik.util.XMLResourceDescriptor;
import org.w3c.dom.svg.SVGDocument;

and here the cop snippet:

    String parser = XMLResourceDescriptor.getXMLParserClassName();
    factory = new SAXSVGDocumentFactory(parser);

    UserAgent userAgent = new UserAgentAdapter();
    DocumentLoader loader = new DocumentLoader(userAgent);
    ctx = new BridgeContext(userAgent, loader);
    ctx.setDynamicState(BridgeContext.DYNAMIC);

    builder = new GVTBuilder();

    PdfContentByte cb = writer.getDirectContent();


    PdfTemplate chartImageTemplate = cb.createTemplate(1000, 1000);


    SVGDocument svgDoc=null;
    try {
        InputStream in = new ByteArrayInputStream(chartImage.getBytes());
        svgDoc = factory.createSVGDocument("", in);
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    try{
        GraphicsNode mapGraphics = builder.build(ctx, svgDoc);

        DefaultFontMapper mapper = new DefaultFontMapper();
        PdfGraphics2D g2 = (PdfGraphics2D)cb.createGraphics(1000, 500, mapper);
        Graphics2D g2d = g2;
        mapGraphics.paint(g2d);
        g2d.dispose();

        cb.addTemplate(chartImageTemplate, 0, 0);
        return mapGraphics.getGeometryBounds().getHeight();
    }catch(Exception e){

    }

You can find SVG here: http://speedy.sh/xvDp8/demo.svg

Actual SVG:

Rendered PDF