1.想要打印svg图片,同时想要控制大小和偏移量,一通瞎弄发现最后无法识别svg。
2.改变思路:svg=>pdf=>打印
3.希望基于js,ts实现
https://jingyan.baidu.com/article/eae078278272dd1fed548577.html
function downLoadPDFFunc () {
// svg 转为 dataurl
var serializer = new XMLSerializer();
var svg1 = document.querySelector('svg');
var tempExport = svg1.cloneNode(true);
// 转成png时,样式添加,也可直接使用样式, 不添加,导出的树线条样式缺少
const upwardLinkRegExp = /class="upwardLink"/g;
const downwardLinkRegExp = /class="downloadLink"/g;
const str = 'style="fill:none; stroke: #0000cd; stroke-width: 1px;"';
var toExport = tempExport;
var bb = svg1.getBBox();
// 设置svg 的长宽,控制边距
const width = bb.width + 400;
const height = bb.height + 400;
toExport.setAttribute(
'viewBox',
bb.x -50 + ' ' + (bb.y-50) + ' ' + width+ ' ' + height
);
toExport.setAttribute('width', width);
toExport.setAttribute('height', height);
var source = serializer.serializeToString(toExport);
const tempSource = source.repalce(upwardLinkRegExp, str).replace(downwardLinkRegExp, str);
// 创建canvas
var canvas = document.createElement('canvas');
canvas.width = width;
canvas.height =height;
var context = canvas.getContext('2d');
context.fillStyle = '#fff';
context.fillRect(0, 0, width, height);
// 创建图片
var image = new Image();
// 地址使用base64的格式
image.src = 'data:image/svg+xml;base64,' + window.btoa(unescape(encodeURIComponent(tempSource)));
image.style.transform = 'scale(1)';
// 图片下载
image.onload = function() {
// 在canvas中绘制图片
let size = Math.max(width, height);
let tempSize = 0;
// 导出的pdf 的长宽须小于14400, 游览起报错
if (size < 14400) {
tempSize = 1;
} else {
tempSize = 14000 /size;
}
// 绘制图片
context.drawImage(image, 0, 0, width * tempSize , height *tempSize );
var imgDataUri = canvas.toDataURL('image/png', 1.0);
// jsPDF 导出
const doc = new jsPDF({
orientation: width > height ? 'landscape' : 'protrait',
unit: 'pt',
format: [width * tempSize, height * tempSize]
});
dco.addImage(imgDataUri, "PNG", 0, 0, width * tempSize, height * tempSize);
doc.save('导出的pdf.pdf')
}
}