【问题标题】:pdfmake - Transform SVG to image64 in ANGULAR 4pdfmake - 在 ANGULAR 4 中将 SVG 转换为 image64
【发布时间】:2018-01-31 20:35:17
【问题描述】:

我正在尝试将SVG 转换为带有pdfmake 的图像。

const svg = document.getElementById('chart-grafico-pizza').childNodes[0];
const img = document.createElement('img');
const canvas = document.getElementById('teste-canvas');

// get svg data
const xml = new XMLSerializer().serializeToString(svg);

// make it base64
const svg64 = btoa(xml);
const b64Start = 'data:image/svg+xml;base64,';

// prepend a "header"
const image64 = b64Start + svg64;

// set it as the source of the img element
img.src = image64;
// draw the image onto the canvas
(canvas as HTMLCanvasElement).getContext('2d').drawImage(img, 0, 0);

图像始终返回为undefined

【问题讨论】:

  • 你有没有在调试器中逐行检查这一行,看看它在什么时候失败了?这样做时你会得到什么输出?
  • @AgiHammerthief 是的,代码正在运行,但返回未定义
  • @AgiHammerthief svg 怎么会这么大,不能转换?
  • 我遇到了同样的问题。虽然 pdfmake 文档声明它支持 base64 数据 URI,但它确实在此文档页面的顶部提到仅“支持 JPEG 和 PNG 格式”:pdfmake.github.io/docs/0.1/document-definition-object/images
  • 我已经在 pdfmake GitHub repo 上提交了一个问题:github.com/bpampuch/pdfmake/issues/2326

标签: javascript html angular svg pdfmake


【解决方案1】:

我认为您的代码没有任何问题,SVG 也没有。 你的代码,你显然是从这里得到的 Drawing an SVG file on a HTML5 canvas 假设您的查询选择器工作正常,工作得很好。这可能正是这里的问题...由于您没有提供 HTML,我们当然不能检查。

https://jsbin.com/qacodugive/1/edit

“图像未定义”是什么意思?变量 img 显然不是。它在任何时间点都是一个 DOM 元素。

HTML

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>

  <div>SVG here</div>
  <svg height="100">
    <rect width="100" height="100" />
  </svg>

  <div>Canvas here (Click "Run with JS" to render)</div>
  <canvas></canvas>

</body>
</html>

JS

var svg = document.querySelector('svg');
var img = document.createElement('img');
var canvas = document.querySelector('canvas');

// get svg data
var xml = new XMLSerializer().serializeToString(svg);

// make it base64
var svg64 = btoa(xml);
var b64Start = 'data:image/svg+xml;base64,';

// prepend a "header"
var image64 = b64Start + svg64;

// set it as the source of the img element
img.src = image64;

// draw the image onto the canvas
canvas.getContext('2d').drawImage(img, 0, 0);

【讨论】:

    猜你喜欢
    • 2019-11-25
    • 1970-01-01
    • 2018-03-08
    • 2018-11-07
    • 1970-01-01
    • 2019-09-29
    • 2018-08-22
    • 2020-02-21
    • 1970-01-01
    相关资源
    最近更新 更多