在Chrome的新标签页/窗口中打开jsPDF创建的pdf [英] Open jsPDF created pdf in Chrome's new tab/window
问题描述
如何在Chrome 71中使用JavaScript链接data:application/pdf;filename=generated.pdf;base64;DATA
打开?
不幸的是,来自控制台的链接已成功打开,但未从代码中打开.
出于安全原因,该代码段无效.仅用于代码演示.
我读了一些类似的问题,但没有找到答案.
How can I open with javascript link data:application/pdf;filename=generated.pdf;base64;DATA
in Chrome 71?
Link from console opened successfully, but not from code - unfortunately.
The snippet does not work for security reason. Only for code demonstration.
I read some similar questions, but did not find an answer.
var button = document.getElementById("button");
button.addEventListener("click", generate, false);
function generate() {
var doc = new jsPDF({
orientation: "l",
unit: "mm"
});
doc.text('ACT', 130, 20);
var string = doc.output('datauristring');
console.log(string);
var link = document.createElement('a');
link.href = string;
link.setAttribute('target', '_blank');
document.body.appendChild(link);
link.click();
link.parentNode.removeChild(link);
}
<script src="https://unpkg.com/jspdf@1.5.3/dist/jspdf.min.js"></script>
<button id="button">Generate pdf table</button>
推荐答案
请尝试使用window.open()
.以下代码对我有用.您将需要修改窗口/页面大小.
Try window.open()
instead. The following code worked for me. You will need to modify the window/page size.
let dataSrc = pdf.output("datauristring");
let win = window.open("", "myWindow");
win.document.write("<html><head><title>jsPDF</title></head><body><embed src=" +
dataSrc + "></embed></body></html>");
更新:
没有意识到jsPDF带有内置方法 pdf.output('dataurlnewwindow');
,该方法使用了 iframe ,
Didn't realize that jsPDF comes with a built-in method pdf.output('dataurlnewwindow');
, which uses iframe,
pdf.output('dataurlnewwindow')
的缺点是它会打开一个新的标签页/窗口,并以datauristring
作为pdf文件名,而下载按钮不起作用,而
The downside of pdf.output('dataurlnewwindow')
is that it opens a new tab/window with datauristring
as the pdf file name and the download button doesn't work, while window.open(pdf.output('bloburl'))
seems fine with the download button.
好的,可以这样重命名pdf文件:
Okay, pdf file can be renamed like this:
pdf.setProperties({
title: "jsPDF sample"
});
更新2:
为避免页面缩放时页面被剪掉,您可以相应地设置html2canvas比例. >
To avoid the page being cut off when a page is zoomed, you can set the html2canvas scale accordingly.
这篇关于在Chrome的新标签页/窗口中打开jsPDF创建的pdf的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!