如何在Chrome 71中使用javascript链接data:application/pdf;filename=generated.pdf;base64;DATA
打开?
来自控制台的链接已成功打开,但不是代码 - 不幸的是。
该片段因安全原因无效。仅用于代码演示。
我读了一些类似的问题,但没有找到答案。
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/[email protected]/dist/jspdf.min.js"></script>
<button id="button">Generate pdf table</button>
试试window.open()
吧。以下代码对我有用。您需要修改窗口/页面大小。
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,
pdf.output('dataurlnewwindow')
的缺点是它打开一个新的选项卡/窗口,其中datauristring
作为pdf文件名,下载按钮不起作用,而window.open(pdf.output('bloburl'))
似乎没有下载按钮。好的,pdf文件可以像这样重命名:
pdf.setProperties({
title: "jsPDF sample"
});
更新2:
为避免在页面放大时页面被切断,one can force the zoom level back to 100% and set the html2canvas scale accordingly.
它实际上非常简单,不要让事情复杂化..
window.open(URL.createObjectURL(doc.output("blob")))
或者更冗长,效率更低的版本:
let newWindow = window.open('/');
fetch(doc.output('datauristring')).then(res => res.blob()).then(blob => {
newWindow.location = URL.createObjectURL(blob);
})
(您需要在onclick后立即打开新窗口,否则Chrome会阻止弹出窗口。此解决方案不太好,因为从datauri到blob有不必要的转换)
这段代码适合我
var doc = new jsPDF();
doc.setProperties({
title: "new Report"
});
doc.output('dataurlnewwindow');
您正在使用Javascript从其原始数据生成PDF。为什么不使用像Adobe这样的读者来渲染它?这是从控制台单击链接时发生的情况。您可以直接打开链接,它将以PDF格式打开。我认为你可能会使这项任务复杂化。
我从本地计算机中的问题运行代码并采取此错误:
不允许将顶部框架导航到数据URL:data:application / pdf; filename = generated.pdf; base64,...
JsPDF - Not allowed to navigate top frame to data URL
我试过@WeihuiGuo的建议。不幸的是我。
我发现Chrome会自动打开pdf。
https://support.google.com/chrome/answer/6213030?hl=en https://groups.google.com/a/chromium.org/forum/#!topic/chromium-bugs/z5hA0H6LFws
而且不仅仅是新标签。也没有在当前页面上打开。 https://sphilee.github.io/jsPDF-CustomFonts-support/
在其他浏览器中,此页面正确显示。
这样的悲伤消息。