How to export a SVG in a PDF using JavaScript

Viewed 2865

I have a SVG element inside of some HTML and I would like to be able to export all the HTML to a PDF. I am already able to create the PDF from the HTML using jsPDF, but the SVG element is ignored.

Important note: I don't want to have to convert the SVG to a non-vectorial format and then inserting that element to the PDF.

class ToPDF extends Component {
    constructor(props){
        super(props);
        this.convertToPdf=this.convertToPdf.bind(this);
    }

    convertToPdf() {
        let pdf = new jsPDF('p', 'pt', 'letter');
        const elementHandlers = {
            '#bypassme': function(element, renderer) {
                return true
            }
        };

        const source = document.getElementById('chart');
        pdf.fromHTML(
            source, 
            50, 
            50, 
            {
                'width': 600,
                'elementHandlers': elementHandlers
            }
        );

        pdf.save('test.pdf');
    }

    render() {
        return (
            <div>
                <div id='chart'>
                    <h2>HTML to PDF</h2>
                    <p>Let's try converting this chart to a PDF</p>
                    <svg width="500" height="300">
                        <g>
                            <circle cx="100" cy="100" r="2"></circle>
                            <circle cx="200" cy="200" r="2"></circle>
                        </g>
                    </svg>
                </div>
                <button onClick={this.convertToPdf}>Download PDF</button>
            </div>
        );
    }
}

I simplified the code, but basically I am just rendering a component containing HTML and a SVG. That rendered HTML contains a div with an id of "chart", that's the element I am trying to save as a PDF.

Thanks for your help

1 Answers

I also need to include SVGs using jsPDF. But the parser does not seem to accept all SVGs. It only parses the PATH elements in the 1st level of the SVG. It requires all path string elements to be separated by a space (which I have never seen any program actually export). And it only supports the "c" and "l" directives. So it is not a "real" SVG parser, but rather a proof-of-concept.

In summary: SVG is an experimental function of jsPDF which is not usable, yet.

(Since I desparately need that functionality for a project and I have written several SVG parsers myself, I might implement it and create a pull request soon.)

Related