yWorks/svg2pdf.js

How to concatenate multiple SVG files?

fablau opened this issue · 2 comments

fablau commented

Hello,
I am trying to understand how to concatenate several SVG files into a single PDF file.

I have tried the following, but with no luck:

var doc = new jsPDF();

x = 0;
y = 0;
width = 200;
height = 300;

var svgElement = document.getElementById(svg_id_1);
svgElement.getBoundingClientRect();

doc.svg(svgElement, {
  x,
  y,
  width,
  height
})

doc.addPage()

var svgElement = document.getElementById(svg_id_2);
svgElement.getBoundingClientRect();

doc.svg(svgElement, {
  x,
  y,
  width,
  height
})

doc.addPage()

doc.save('myPDF.pdf')

What I get is a 2 pages long PDF file with empty, blank pages.

What is the correct way to do it?

Thanks in advance.

Hi,

I manage to make it work by waiting for one svg to be added to the pdf first and then the next svg will be added using the .then() callback. Below is example on how I achieve it

        // add header with logo and title of the chart
        const logo = new Image();
        logo.src = 'logo.png';
        logo.onload = () => {
            pdf.addImage(logo, 'png', (canvasW / 2) - 100, 10, 50, 50);
            pdf.setFontSize(20);
            pdf.setFont('helvetica', 'bold');
            pdf.text((canvasW / 2) - 40, 45, 'Chart');

            // add a line 
            pdf.setLineWidth(1);
            pdf.line(0, 70, canvasW, 70);
        
            pdf.svg(svg1, {x:20, y: 80, width, height})
            .then(() => {
                // add text before the legend
                pdf.text(width + 15, 120, 'Legend');
                pdf.svg(svg2, { x: width + 9, y: 130, width, height })
                .then(() => {
                    pdf.save('myPDF.pdf');
                });
            });
        }

Hope it helps.

fablau commented

Yes, that worked! Thanks!