You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 17:50:36