javascript - 通过从指定的文件 url 获取文件来在打印窗口中打开文件

标签 javascript jquery

我正在尝试使用 jQuery 在我的应用程序中实现打印选项。我会有url of the file打印为src <a> tag 的属性。我想做的就是从指定的 url 获取文件,并在用户可以打印的打印窗口中打开它。我使用的代码如下:

<a id="print-5569" href="http://www.ibiblio.org/ebooks/Baum/Santa_Claus.pdf "><i class="fa fa-download"></i></a>

我尝试了很多在网上找到的解决方案,但注意到对我有用。我尝试过的示例之一如下: https://www.sitepoint.com/load-pdf-iframe-call-print/

当我在线搜索时,我找到了这方面的插件。但我不想为此添加一个插件。有没有办法解决这个问题。

最佳答案

直接从同一页面打印文件

第 1 步:将文件下载为 Blob

// Using fetch
const response = await fetch("http://www.ibiblio.org/ebooks/Baum/Santa_Claus.pdf");
const blob = await response.blob();
// Using axios
const response = await axios.get("http://www.ibiblio.org/ebooks/Baum/Santa_Claus.pdf",
  { responseType: "blob" }
);
const blob = response.data;

第 2 步:创建 iframe 并打开打印提示

const fileUrl = URL.createObjectURL(blob);

let iframe = document.createElement("iframe");
document.body.appendChild(iframe);

iframe.style.display = "none";
iframe.src = fileUrl;
iframe.onload = function () {
  iframe.focus();
  iframe.contentWindow.print();
};

关于javascript - 通过从指定的文件 url 获取文件来在打印窗口中打开文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45628634/

相关文章:

Javascript - 过滤对象

javascript - 如何使用链接展开/折叠网页中的信息列表

javascript - 定位并换行小数点后的第 3 位数字

jquery - 在 Webkit 浏览器中悬停后的 CSS3 动画速度不正确

javascript - 从表中添加/删除行

javascript - `add_to_cart: function(name, price, attr, image_src)` -> 如何保存php mysql表列/名称、价格、数量/

javascript - Angular 2/4 中关于 BrowserModule 的困惑

javascript - div 相对于静态元素的绝对位置

javascript - 用于外部点击的 @HostListener OnClick 在 Firefox 中不起作用

javascript - 如何通过我的模块化 js 结构中的 ajax 调用接收回数据?