我正在使用html2canvas和pdfmake进行多页pdf下载。 我可以下载pdf,但生成的pdf的页面高度,页面宽度不正确,分辨率低/模糊。代码如下。请参阅随附的屏幕截图。
谢谢。
我使用的代码是:
html2canvas(document.getElementById('newId')).then(
canvas=>{
var image = canvas.toDataURL('image/png');
const PAGE_WIDTH = 500;
const PAGE_HEIGHT = 700;
const content = [];
var w=500;
var h=700;
function getPngDimensions (base64) {
const header = atob(base64.slice(22, 70)).slice(16, 24);
const uint8 = Uint8Array.from(header, c => c.charCodeAt(0));
const dataView = new DataView(uint8.buffer);
return {
width: dataView.getInt32(0),
height: dataView.getInt32(4)
};
}
const splitImage = (img, content, callback) => () => {
const canvas = document.createElement('canvas');
canvas.width = w*2;
canvas.height=h*2;
canvas.style.width=w+'px';
canvas.style.height=h+'px';
const ctx = canvas.getContext('2d');
ctx.scale(2,2);
const printHeight = img.height * PAGE_WIDTH / img.width;
for (let pages = 0; printHeight > pages * PAGE_HEIGHT; pages++) {
canvas.height = Math.min(PAGE_HEIGHT, printHeight - pages * PAGE_HEIGHT);
ctx.drawImage(img, 0, -pages * PAGE_HEIGHT, img.width, printHeight);
content.push({ image: canvas.toDataURL(), margin: [0, 5],width:PAGE_WIDTH });
}
callback();
};
function next () {
pdfMake.createPdf({ content }).open();
}
const { width, height } = getPngDimensions(image);
const printHeight = height * PAGE_WIDTH / width;
if (printHeight > PAGE_HEIGHT) {
const img = new Image();
img.onload = splitImage(img, content, next);
img.src = image;
return;
}
content.push({ image, margin: [0, 5], width: PAGE_WIDTH });
next();
}
);
更新: 我尝试更新由画布形成的图像的宽度和高度,但仅增加宽度会增加像素大小,并进一步截断仪表板的右端。
const PAGE_WIDTH = 500;
const PAGE_HEIGHT = 700;
//some more code here as mentioned in the detailed snippet
const content = [];
var w=500;
var h=700;
通过香蕉仪表板
显示的多页PDF像素显示不佳