天天看點

chrome實作直接列印 js調用iframe列印局部内容 js新開視窗列印局部内容

chrome實作直接列印

預覽頁自動點選列印

準備工作:

  1. 電腦連接配接列印機,并設定一個預設列印機
  2. --kiosk-printing (chrome啟動加該參數,這是在預覽頁自動點選列印按鈕的)

在chrome的快捷方式這裡加上該參數,重新開機chrome

chrome實作直接列印 js調用iframe列印局部内容 js新開視窗列印局部内容
function dayin(){
  var newWindow=window.open('','_blank','width=1,height=1,top=10000,left=10000');
  var html = "";// 這裡的html可由别處傳參,也可自己去接口擷取
  newWindow.document.write(html);
  newWindow.document.close();
  newWindow.print();
  newWindow.close();
}      
var iframe = document.createElement('IFRAME');
                    iframe.setAttribute('style', 'position:absolute;width:0px;height:0px;left:-500px;top:-500px;');
                    document.body.appendChild(iframe);
                    var doc = iframe.contentWindow.document;
                    // 實踐證明 doc.innerHTML = '要列印的html内容';這種寫法是不行的
                    // doc.innerHTML = '要列印的html内容';
                    // 需要用
                    doc.write('要列印的html内容');
                    iframe.contentWindow.focus();
                    iframe.contentWindow.print();
                    document.body.removeChild(iframe);