如何使用pdf.js和d3绘制图形?

时间:2019-04-16 19:03:22

标签: typescript d3.js pdf.js

我正在尝试

1)在d3中绘制线形图

2)将d3画布打印为pdf图像 但是我有一些问题。

以下是我代码的相关部分。此时,我在pdf上只有一个黑色图像。

任何对此的帮助或建议都非常欢迎。

谢谢!

const doc = new jsPDF('', '', '', true);
doc.addPage('a4', 'landscape'); 
const svg = drawCastLine(samples); // drawCastLine returns SVGSVGELEMENT
const svgStr = (new XMLSerializer()).serializeToString(svg);
$(canvas).attr({
      width: `${1100}px`,
      height: `${700}px`,
});
canvg(canvas, svgStr); // import from 'canvg-fixed'
let svgimg = canvas.toDataURL('image/jpeg');
doc.addImage(svgimg, 'JPEG', 20, 20, 245, 150, undefined, 'FAST');

function drawCastLine(samplesPoints) {
      // samplesPoints is Array<[number,number]>, each [number,number] 
      // represents one data point (x,y)

      const svgDom = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
      svgDom.setAttributeNS('http://www.w3.org/2000/xmlns/', 'xmlns:xlink', 'http://www.w3.org/1999/xlink');

      const svg = d3.select(svgDom)
        .attr('class', 'svg');

      const margin = { top: 20, bottom: 20, left: 20, right: 100 };
      const svgWidth = 500;
      const svgHeight = 200;
      const width = svgWidth - margin.left - margin.right;
      const height = svgHeight - margin.bottom - margin.top;
      svg.attr('width', svgWidth).attr('height', svgHeight);

      const canvas = svg.append('g')
        .attr('class', 'cast-line-canvas');

      const benchContX = d3.scaleLinear().domain(distanceX).range([0, width]);
     // distanceX is array of x value of samplePoints
      const benchContY = d3.scaleLinear().domain(elevationY).range([0, height]); 
     // elevationY is array of y value of samplePoints

      const cont = canvas.append('g')
        .attr('class', 'burden-cliff-depth-cont');

      drawElevation(cont, samplePoints, 3);

      function drawElevation(cont, points, strokeWidth?) {
        const curveGen = d3.line()
          .curve(d3.curveCatmullRom)
          .x(d => { return (width - benchContX(Math.abs(d[0])) + 5); })
          .y(d => { return benchContY(d[1]); });

        const curve = cont
          .selectAll('elevation-curve')
          .data([points])
          .enter()
          .append('path')
          .attr('class', 'elevation-curve')
          .attr('d', d => curveGen(d))
          .attr('stroke', 'black')
          .attr('fill', 'none')
          .attr('stroke-width', strokeWidth);
      }

      return svg.node();

    }
doc.save('titile.pdf');

0 个答案:

没有答案