How to add SVG image to PDF built with HTML and Flying Saucer library (and Batik)?

后端 未结 1 1057
北荒
北荒 2021-01-18 10:38

Im working on generation of PDFs with XHTML using the flying saucer library (old but open source). I got that working but I also want to add SVG images. Ive started working

相关标签:
1条回答
  • 2021-01-18 11:02

    I dont know why exactly, but replacing the code in SVGReplacedElement.paint(...) fixed it.

    New code:

    @Override
    public void paint(RenderingContext renderingContext, ITextOutputDevice outputDevice, 
            BlockBox blockBox) {
        PdfContentByte cb = outputDevice.getWriter().getDirectContent();
        float width = (float) (cssWidth / outputDevice.getDotsPerPoint());
        float height = (float) (cssHeight / outputDevice.getDotsPerPoint());
    
        PdfTemplate template = cb.createTemplate(width, height);
        Graphics2D g2d = template.createGraphics(width, height);
        PrintTranscoder prm = new PrintTranscoder();
        TranscoderInput ti = new TranscoderInput(svg);
        prm.transcode(ti, null);
        PageFormat pg = new PageFormat();
        Paper pp = new Paper();
        pp.setSize(width, height);
        pp.setImageableArea(0, 0, width, height);
        pg.setPaper(pp);
        prm.print(g2d, pg, 0);
        g2d.dispose();
    
        PageBox page = renderingContext.getPage();
        float x = blockBox.getAbsX() + page.getMarginBorderPadding(renderingContext, CalculatedStyle.LEFT);
        float y = (page.getBottom() - (blockBox.getAbsY() + cssHeight)) + page.getMarginBorderPadding(
                renderingContext, CalculatedStyle.BOTTOM);
        x /= outputDevice.getDotsPerPoint(); 
        y /= outputDevice.getDotsPerPoint();
    
        cb.addTemplate(template, x, y);
    }
    

    got it from a tutorial.

    Might have had something to do with the new UserAgent and DocumentLoader etc I created that were not linked to the original document. In any case it works now. Hope it will help someone in the future. If people want to comment or add another answer as to why this works now, that might help other reading this later.

    0 讨论(0)
提交回复
热议问题