使用 EMBED 和 URL.createObjectURL 设置 pdf 名称(不可下载)

问题描述 投票:0回答:1

重复标记的免责声明:这个问题与下载文件无关。请先阅读问题,然后再将其标记为重复。

我正在使用嵌入在 HTML 文档中呈现 PDF 文件。如果我按照以下步骤进行:

const embed = document.createElement("EMBED");

const url = "../pdf_files/test.pdf";
embed.src = url;

const content = document.getElementById("content");
content.innerHTML = "";
content.appendChild(embed);

浏览器 pdf 查看器使用文件名呈现文档,如下图突出显示:

enter image description here

但是如果我使用 Blob/File/URL.createObjectURL,pdf 查看器不会使用文件名:

const embed = document.createElement("EMBED");
const url = "../pdf_files/test.pdf";

const existingPdfBytes = await fetch(url).then(res => res.arrayBuffer());

const blob = new Blob([existingPdfBytes], {
    type: 'application/pdf'
});
const file = new File([blob], "hello.pdf", {"type": "application/pdf"});

embed.src = window.URL.createObjectURL(file)

const content = document.getElementById("content");
content.innerHTML = "";
content.appendChild(embed);

enter image description here

有没有办法设置此文件名,以便使用 URL.createObjectURL 在 pdf 查看器上正确显示它?

javascript pdf dom
1个回答
0
投票

正如 Kevin Brown 已经指出的那样,这两种情况本质上都发生了相同的事情:网址的最后一部分显示在顶部。

embed.src = window.URL.createObjectURL(file)
console.log(embed.src) // This will show you the url which ends with a uid

也许你想尝试手动将

title
<embed>
设置为文件名:

embed.setAttribute("title", url.split("/").pop())
© www.soinside.com 2019 - 2024. All rights reserved.