我正在尝试使用jsPDF创建一个带有 JavaScript 的 PDF 文件。我有一个小测试页。基本上我有一个下载 PDF 按钮,它从一个跨度中获取 base64 图像并将其用于imgData
. 然后我尝试addImage
将该图像数据转换为pdf,然后保存。一切似乎都正常,它会生成 PDF 并提示下载。但是,当我尝试使用 xpdf 或 Foxit 阅读器查看 PDF 时,我被告知 PDF 已损坏。我是否错误地创建了此 PDF?我的网页很长,所以我把它放在Pastebin上。
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<script type="text/javascript" src="js/jquery/jquery-1.7.1.min.js"></script>
<script type="text/javascript" src="js/jquery/jquery-ui-1.8.17.custom.min.js"></script>
<script type="text/javascript" src="../jspdf.js"></script>
<script type="text/javascript" src="../libs/FileSaver.js/FileSaver.js"></script>
<script type="text/javascript" src="../libs/BlobBuilder.js/BlobBuilder.js"></script>
<script type="text/javascript" src="../jspdf.plugin.addimage.js"></script>
<script type="text/javascript" src="../jspdf.plugin.standard_fonts_metrics.js"></script>
<script type="text/javascript" src="../jspdf.plugin.split_text_to_size.js"></script>
<script type="text/javascript" src="../jspdf.plugin.from_html.js"></script>
<script type="text/javascript" src="js/basic.js"></script>
<title>Sup!</title>
<script>
function changeCan() {
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.fillStyle="#FF0000";
ctx.fillRect(0,0,128,128);
}
function changeCan3() {
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.fillStyle="#FFFFFF";
ctx.fillRect(0,0,128,128);
var image = new Image();
image.src = document.getElementById("3span").innerHTML;
ctx.drawImage(image,0,0);
}
function changeCan4() {
var imgData = document.getElementById("3span").innerHTML;
window.alert(imgData.length);
var doc = new jsPDF();
doc.addImage(imgData, 'JPEG', 15, 40, 128, 128);
doc.save('Test.pdf');
}
</script>
</head>
<body>
Yo!<hr>
<canvas id="myCanvas" width="128" height="128"></canvas><hr>
<button type="button" onClick="changeCan()">Change Me To Red!</button>
<button type="button" onClick="changeCan3()">Change Me To Span!</button>
<button type="button" onClick="changeCan4()">Download Me!</button>
<hr>
<span id="3span" style="display:none;">B64 DATA HERE</span>
</body>
</html>