gpt4 book ai didi

javascript - 如何将 png Canvas 图像下载为 PDF JQuery

转载 作者:行者123 更新时间:2023-11-30 15:32:17 36 4
gpt4 key购买 nike

这段代码我写了很多次,下载 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');
}
});

最佳答案

你可以适应this answer到您的代码,使用 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>

Note: I only tested this in Chrome, Edge and Firefox on Windows 10. You might want to try other browsers/systems.

关于javascript - 如何将 png Canvas 图像下载为 PDF JQuery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42057799/

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