问题描述
我正在使用HTML5 Canvas进行工作。
这一切都很好,除了现在,我可以导出画布内容到PNG使用Canvas2image。但我想导出它到PDF。我做了一些研究,我很确定它的可能...但我似乎不能理解我需要改变我的代码,使其工作。我已经阅读了一个插件叫做pdf.js ...但我不知道如何隐含它在我的代码。
I am working on something using HTML5 Canvas.It's all working great, except right now, I can export the canvas content to PNG using Canvas2image. But I would like to export it to PDF. I've made some research and I'm pretty sure it's possible...but I can't seem to understand what I need to change in my code to make it work. I've read about a plugin called pdf.js...but I can't figure out how to implent it in my code.
第一部分:
function showDownloadText() {
document.getElementById("buttoncontainer").style.display = "none";
document.getElementById("textdownload").style.display = "block";
}
function hideDownloadText() {
document.getElementById("buttoncontainer").style.display = "block";
document.getElementById("textdownload").style.display = "none";
}
function convertCanvas(strType) {
if (strType == "PNG")
var oImg = Canvas2Image.saveAsPNG(oCanvas, true);
if (strType == "BMP")
var oImg = Canvas2Image.saveAsBMP(oCanvas, true);
if (strType == "JPEG")
var oImg = Canvas2Image.saveAsJPEG(oCanvas, true);
if (!oImg) {
alert("Sorry, this browser is not capable of saving " + strType + " files!");
return false;
}
oImg.id = "canvasimage";
oImg.style.border = oCanvas.style.border;
oCanvas.parentNode.replaceChild(oImg, oCanvas);
showDownloadText();
}
而保存图片的JS:
document.getElementById("convertpngbtn").onclick = function() {
convertCanvas("PNG");
}
document.getElementById("resetbtn").onclick = function() {
var oImg = document.getElementById("canvasimage");
oImg.parentNode.replaceChild(oCanvas, oImg);
hideDownloadText();
}
}
推荐答案
您需要为此使用两个插件:
1)
2)
You need to use 2 plugins for this:1) jsPDF2) canvas-toBlob.js
然后添加这段代码以生成轻量级PDF:
Then add this piece of code to generate light weight PDF:
canvas.toBlob(function (blob) {
var url = window.URL || window.webkitURL;
var imgSrc = url.createObjectURL(blob);
var img = new Image();
img.src = imgSrc;
img.onload = function () {
var pdf = new jsPDF('p', 'px', [img.height, img.width]);
pdf.addImage(img, 0, 0, img.width, img.height);
pdf.save(fileName + '.pdf');
};
});
这篇关于将画布内容导出为PDF的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!