1

我正在使用 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;

通过 Banana 仪表板的多页 PDF 的像素显示不佳

4

0 回答 0