问题
I have a fabricjs canvas that I need to input a PDF, similar to how images are loaded. I expect that I'd need to convert the PDF to a PNG via PDFjs before loading onto canvas?
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]);
}
I'm just not sure how to go about it.
回答1:
To solve this I converted the PDF to PNG with PDF.js and stored toDataURL
, then retreived the PNG image fromURL
and set as background.
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>
来源:https://stackoverflow.com/questions/57027267/load-pdf-into-fabricjs-canvas