How do I create easily a PDF from an SVG with jsPDF?

前端 未结 5 1407
逝去的感伤
逝去的感伤 2020-12-05 16:21

I\'m trying to create a pdf but I have some SVG pictures. I found information about this problem, but I just have to use JavaScript, that\'s to say, no jQuery.

I fou

5条回答
  •  心在旅途
    2020-12-05 16:37

    You can use the canvas plugin that comes with jsPDF to render the SVG on the PDF with canvg. I've had to set a few dummy properties on the jsPDF canvas implementation, and disable the interactive/animation features of canvg for this to work without errors:

    var jsPdfDoc = new jsPDF({
        // ... options ...
    });
    
    // ... whatever ...
    
    // hack to make the jspdf canvas work with canvg
    jsPdfDoc.canvas.childNodes = {}; 
    jsPdfDoc.context2d.canvas = jsPdfDoc.canvas;
    jsPdfDoc.context2d.font = undefined;
    
    // use the canvg render the SVG onto the 
    // PDF via the jsPDF canvas plugin.
    canvg(jsPdfDoc.canvas, svgSource, {
        ignoreMouse: true,
        ignoreAnimation: true,
        ignoreDimensions: true,
        ignoreClear: true
    });
    

    This seems to me a much better solution than the SVG plugin for jsPDF, as canvg has much better support of SVG features. Note that the width and height properties should be set on the element of your SVG for canvg to render it correctly (or at least so it seemed to me).

提交回复
热议问题