如何在保存打印页时为文件创建自定义文件名



在这里,我正在通过window.print()事件打印一个页面,在打印之前,我需要保存此页面,为此我需要在此事件中硬核文件名。

   <a href="_javascript:window.print()">
    <img class="noPrint" src="Images/Print_icon.png" border="0"></a>

有什么建议吗?

您可以通过document.title更改标题:

<a href="someRealUrl" onclick="document.title='My new title'; window.print(); return false;"><img class="noPrint" src="Images/Print_icon.png" border="0"></a>
onClick="document.title = "My new title";window.print();"

请参阅:

https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onbeforeprinthttps://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onafterprint

打印

前和印后事件允许页面在打印开始之前更改其内容(例如,可能删除横幅),然后在打印完成后还原这些更改。通常,您应该首选使用@media打印 CSS 规则,但在某些情况下可能需要使用这些事件。

问题的解决方案是更改事件处理程序beforeprint document.title,并在事件处理程序中恢复到其原始值afterprint

我知道这是一个

旧线程,但只是为了向 Lukasz Prus 答案添加示例,您可以使用以下行document.title(如在接受的答案中一样)(在打印前将页面标题更改为所需的标题,然后更改回原始标题):

window.addEventListener("beforeprint", (event) => {
  document.title='My desired save filename';
});
window.addEventListener("afterprint", (event) => {
  document.title='The original page title';
});

最新更新