打印后如何删除iframe?



export const printPdf = (data: any) => {
const newBlob = new Blob([data], { type: 'application/pdf' })
const fileLink = window.URL.createObjectURL(newBlob)
const iframe = document.createElement('iframe')
iframe.src = fileLink
iframe.id = 'print_pdf'
iframe.name = 'print_pdf'
// iframe.setAttribute('style', 'display:none')
iframe.onload = () => {
iframe.contentWindow!.onafterprint = () => {
document.body.removeChild(iframe)
}
}
document.body.appendChild(iframe)
window.frames['print_pdf'].focus()
window.frames['print_pdf'].print()
window.frames['print_pdf'].onafterprint = () =>
document.body.removeChild(iframe)
}

我尝试了我发现的一切。而且,打印后 iframe 窗口没有此事件侦听器,因此不会调用任何内容。

我有一个技巧给你(一个对我有用的简单技巧(: 您可以创建iframe,而不是删除它,只是不要在UI中显示它。所以你的UI很好,你的打印是执行的。下次您要打印另一个PDF时,您可以检查是否存在iframe,首先将其删除,然后继续与以前相同。 所以你的代码将是:

export const printPdf = (data: any) => {
const newBlob = new Blob([data], { type: 'application/pdf' })
const fileLink = window.URL.createObjectURL(newBlob)
const previousIframe=document.getElemenById('print_pdf');
if(previousIframe){
previousIframe.remove()
}
const iframe = document.createElement('iframe')
iframe.src = fileLink
iframe.id = 'print_pdf'
iframe.name = 'print_pdf'

iframe.onload = () => {
document.body.appendChild(iframe)
window.frames['print_pdf'].focus()
window.frames['print_pdf'].print()
iframe.style.display = "none";
}

这个问题是很久以前的问题,但我为将来会有这个问题的人写一个答案,因为我前一天有这个问题。

最新更新