我很多次写过这段代码,下载图像为png。现在我需要将图像下载为pdf,并且我不知道如何在不改变代码结构的情况下执行此实现。任何人都可以帮我这个忙吗?非常感谢你。
我的JQuery:
function genScreenshot() {
html2canvas(document.getElementById('boxes'), {
onrendered: function(canvas) {
$('#container').html("");
$('#container').append(canvas);
if (navigator.userAgent.indexOf("MSIE ") > 0 ||
navigator.userAgent.match(/Trident.*rv\:11\./))
{
var blob = canvas.msToBlob();
window.navigator.msSaveBlob(blob,'yuppy.png');
}
else {
$('#test').attr('href', canvas.toDataURL("image/png"));
$('#test').attr('download','yuppy.png');
$('#test')[0].click();
}
}
});
}
要实施的代码示例:
html2canvas($("#canvas"), {
onrendered: function(canvas) {
var imgData = canvas.toDataURL(
'image/png');
var doc = new jsPDF('p', 'mm');
doc.addImage(imgData, 'PNG', 10, 10);
doc.save('sample-file.pdf');
}
});
答案 0 :(得分:1)
您可以使用jsPDF
:
<强> JS 强>
$('#test').click(genScreenshot);
function genScreenshot() {
html2canvas(document.getElementById('boxes'), {
onrendered: function(canvas) {
$('#container').html("");
$('#container').append(canvas);
var imgData = canvas.toDataURL("image/jpeg", 1.0);
var pdf = new jsPDF();
pdf.addImage(imgData, 'JPEG', 0, 0);
pdf.save('screenshot.pdf');
}
});
}
<强> CSS 强>
#boxes {
background: #fff; /* To avoid a black background in PDF */
}
<强> HTML 强>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.4.1/html2canvas.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.2/jspdf.min.js"></script>
<div id="boxes">
<h1>This is some content for the screenshot</h1>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Repudiandae asperiores est autem corporis natus nesciunt veritatis, ullam inventore distinctio, quisquam nam quis temporibus vero, fugiat tempore officia. Laborum, harum, alias.</p>
</div>
<button id="test">Download as PDF</button>
<div id="container"></div>
注意:我仅在Windows 10上的Chrome,Edge和Firefox中对此进行了测试。您可能需要尝试其他浏览器/系统。
答案 1 :(得分:0)
您可以使用dom-to-image代替html2canvas。根据我的经验,图像质量和utf8支持比html2canvas好得多。
使用jsPDF然后将图像转换为PDF的代码将类似于:
domtoimage.toPng(
document.querySelector("canvasElement"),
{ width: 800, height: 1000, quality: 1}
)
.then(function(dataUrl) {
var doc = new jsPDF();
var img = new Image();
img.src = dataUrl;
img.onload = function() {
doc.addImage(img, 'PNG', 10, 15);
doc.save('filename.pdf');
};
})
.catch(function (error) {
console.error('oops, something went wrong!', error);
});