如何使用JavaScript在window.open()中设置PDF文件名?
解决PDF新标签页打开文件名随机的问题
你当前用bloburl打开PDF时,浏览器会自动生成随机文件名,因为Blob URL不包含文件名元数据。可以通过以下方式指定自定义文件名:
方法1:通过a标签触发打开(推荐)
直接生成Blob对象,创建带download属性的a标签,既能指定文件名,也能在新标签页打开:
html2pdf().from(element).set(opt).toPdf().get('pdf').then(function (pdf) { const blob = pdf.output('blob'); const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href = url; // 替换成你需要的文件名 a.download = '自定义文件名.pdf'; a.target = '_blank'; document.body.appendChild(a); a.click(); document.body.removeChild(a); // 释放URL对象,避免内存泄漏 URL.revokeObjectURL(url); });
方法2:设置PDF元数据
如果希望PDF文件本身携带文件名信息,可在生成配置中添加文档属性:
const opt = { // 你的其他配置 pdf: { // 设置PDF文档标题,部分浏览器会以此作为文件名 title: '自定义文件名', // 可选:添加作者等其他元数据 author: 'xxx' } }; html2pdf().from(element).set(opt).toPdf().get('pdf').then(function (pdf) { const blob = pdf.output('blob'); const url = URL.createObjectURL(blob); window.open(url, '_blank'); URL.revokeObjectURL(url); });
注意:这种方式的兼容性不如方法1,部分浏览器可能仍会使用随机文件名。
内容的提问来源于stack exchange,提问作者Manish Stark
相关产品推荐
相关产品推荐

