gpt4 book ai didi

fabricjs - 将 PDF 加载到 fabricjs Canvas 中

转载 作者:行者123 更新时间:2023-12-04 12:17:15 28 4
gpt4 key购买 nike

我有一个 fabricjs Canvas ,我需要输入 PDF,类似于加载图像的方式。我希望在加载到 Canvas 上之前我需要通过 PDFjs 将 PDF 转换为 PNG 吗?

    document.getElementById('imgLoader').onchange = function handleImage(e) {
var reader = new FileReader();
reader.onload = function (event) {
console.log('fdsf');
var imgObj = new Image();
imgObj.src = event.target.result;
imgObj.onload = function () {
var image = new fabric.Image(imgObj);
image.set({
left: 320,
top: 5,
});
canvas.add(image);
}
}
reader.readAsDataURL(e.target.files[0]);
}

我只是不知道该怎么做。

最佳答案

为了解决这个问题,我使用 PDF.js 将 PDF 转换为 PNG并存储 toDataURL ,然后检索 PNG 图像 fromURL并设置为背景。

document.querySelector("#pdf-upload").addEventListener("change", function(e) {
var file = e.target.files[0]
if (file.type != "application/pdf") {
console.error(file.name, "is not a pdf file.")
return
}

var fileReader = new FileReader();

fileReader.onload = function() {
var typedarray = new Uint8Array(this.result);

PDFJS.getDocument(typedarray).then(function(pdf) {
// you can now use *pdf* here
console.log("the pdf has ", pdf.numPages, "page(s).")
pdf.getPage(pdf.numPages).then(function(page) {
// you can now use *page* here
var viewport = page.getViewport(2.0);
var canvasEl = document.querySelector("canvas")
canvasEl.height = viewport.height;
canvasEl.width = viewport.width;

page.render({
canvasContext: canvasEl.getContext('2d'),
viewport: viewport
}).then(function() {

var bg = canvasEl.toDataURL("image/png");

fabric.Image.fromURL(bg, function(img) {
img.scaleToHeight(1123);
canvas.setHeight(1123);
canvas.setWidth(1588);
canvas.setBackgroundImage(img);
});
canvas.renderAll();
});
});

});
};
fileReader.readAsArrayBuffer(file);
});
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.6.3/fabric.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/1.8.349/pdf.min.js"></script>
</head>

<body>
<span style="font-size: 14px"><b>Load PDF</b></span>
<input id="pdf-upload" type="file">

<canvas id="pdfcanvas"></canvas>
</body>

关于fabricjs - 将 PDF 加载到 fabricjs Canvas 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57027267/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com