我只想打印 iframe 的内容,而不是整个页面

I want to print only the content of the iframe and not the whole page

本文关键字:打印 只想 iframe      更新时间:2023-09-26

我在Iframe中显示PDF,我有一个动态按钮,上面写着打印。单击该按钮时,我只想打印iframe中显示的PDF,而不是整个页面。我正在使用下面的代码进行打印,但它正在打印整个页面。

try {
iframe = document.getElementById('id of iframe');
iframe.contentWindow.document.execCommand('print', false, null);
}
catch (e) {
window.print();
}

在这种情况下,我如何仅打印iframe的内容,即PDF?

如果您的按钮位于 iframe 外部,则单击操作会将焦点设置为父窗口,而不是包含要打印内容的 iframe。

如果是这种情况,请参阅此帖子:将焦点设置为 iframe 内容