欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

js解決pdf使用iframe打印報跨域錯誤問題的方法示例

 更新時間:2024年03月27日 09:47:29   作者:舜岳  
這篇文章主要給大家介紹了關于js解決pdf使用iframe打印報跨域錯誤問題的相關資料,文中通過代碼介紹的非常詳細,對大家學習或者使用js具有一定的參考借鑒價值,需要的朋友可以參考下

報錯如下:

Uncaught DOMException: Failed to read a named property ‘print’ from ‘Window’: Blocked a frame with origin “https://xxxx.com” from accessing a cross-origin frame.
at iframe.onload (:10:26)

解決方法:

把 pdf 轉(zhuǎn) blob 二進制數(shù)據(jù), 通過 createObjectURL 生成本地對象 url, 在創(chuàng)建 iframe 調(diào)用打印接口

printPDF()
function printPDF() {
  fetch('https://xxxxx.com/xxxx.pdf')
  .then(response => {
    if (!response.ok) {
      throw new Error('Network response was not ok');
    } 
    return response.blob(); // 獲取二進制數(shù)據(jù)
  })
  .then(blobData => {
      // 替換這里的 PDF_URL 為你要打印的 PDF 文件鏈接
      const PDF_URL = URL.createObjectURL(blobData);
    
      // 創(chuàng)建一個隱藏的 iframe 元素
      const iframe = document.createElement('iframe');
      // 等待 PDF 加載完成后進行打印
      iframe.onload = function() {
        iframe.contentWindow.print();
      };
      iframe.style.display = 'none';
      iframe.src = PDF_URL;
    
      // 將 iframe 添加到頁面中
      document.body.appendChild(iframe);
  })
}

附:iframe打印pdf跨域問題,使用blob流轉(zhuǎn)為同源

 <iframe :src="pdfUrl2" width="100%" height="700px" id="printMe" hidden></iframe>
 <iframe :src="pdfUrl" width="100%" height="700px"></iframe>
 
import axios from 'axios'
 axios({
    method: 'get',
    url: this.pdfUrl,
    responseType: 'blob'
  })
   .then(response => {
    this.pdfUrl2= window.URL.createObjectURL(response.data)
    setTimeout(() => { 
      document.getElementById('printMe').contentWindow.print();
     },2000) 
 
    })
      .catch(function(error) {
       console.log(error)
    })

總結 

到此這篇關于js解決pdf使用iframe打印報跨域錯誤問題的文章就介紹到這了,更多相關js pdf用iframe打印報跨域錯誤內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

最新評論