2017-04-25 6 views
1

新しいウィンドウでテーブルを印刷しようとしています。 問題は、ページがレンダリングされる前にprintが印刷しようとしていることです。 私はdocument.writeが非同期であると思われます。 document.write()の代わりにdocument.outerHTML/document.innerHTMLを使用しようとしましたが、CSS/JSファイルがCSSとして正しく解析されていません。 テーブルには、window.print()の後にもキャッシュからロードされているセル内のイメージがあります。window.print()は、レンダリングが完了する前にページを動的に作成しようとします。

ご迷惑をおかけして申し訳ございません。

function printData() { 
 
    let newWin = window.open(""); 
 
    styles=""; 
 

 
    //read styles in different page 
 
    Array.prototype.forEach.call(
 
     document.querySelectorAll("link, style"), 
 
     function(el){ 
 
     styles += (el.outerHTML); 
 
    }); 
 

 
    //DOESNT WORK NOT RENDER STYLES 
 
    // newWin.document.document.querySelector("html").innerHTML=(styles + document.querySelector("table").outerHTML); 
 
    //THIS FINISHES RENDERING AFTER PRINT 
 
     newWin.document.write(styles + document.querySelector("table").outerHTML); 
 

 
     //DOESNT WORK 
 
     newWin.document.addEventListener("DOMContentLoaded", function(){ 
 
     if(newWin.document.addEventListener === "loading"){ 
 
      newWin.print(); 
 
     } 
 
     //DOESNT WORK 
 
     newWin.window.onload= function(){ 
 
      newWin.print(); 
 
     } 
 

 
     //WORKS 
 
     setTimeout(function(){ 
 
     newWin.print(); 
 
     newWin.close(); 
 
     }, 2000); 
 
    }); 
 
}

+0

ここではエキゾチックなものがあります:すべての画像にonload関数を付けます。まず、トリガーイメージの属性「完了」を「true」に設定します。次に、完了していないすべての画像を選択します:$( 'img [done!= "true"]')。長さが0の場合、印刷します。 – Nate

+0

まだ画像をすべて削除しようとしました。 – partizanos

答えて

2

のようなものを試してみてください。 IE11、Chrome、Firefoxで動作します。 window.close()setTimeout()にラップせずに呼び出すと、IE11は印刷ダイアログを表示する前にウィンドウを閉じます。

<script type="text/javascript"> 
    setTimeout(function() { 
     window.print(); 
     setTimeout(function() {window.close();}); 
    }); 
</script> 
+0

非常に良い考え: 私はそれを試して、それは仕事をしませんでしたが、私はそれが動作するように管理print.AndClose = ' '; – partizanos

+0

ありがとう、document.write()が非同期に動作する理由を知っていますか? – partizanos

+0

'document.write'を複数回呼び出すと、複数の文書からビルドアップを行うことができます。暗黙的に 'document.close'を呼び出すことはないので、別の可能な解決策を指しています:' newWin.print() 'を呼び出す前に明示的に' newWin.document.close() 'を呼び出すことができます... – searlea

1

使用window.onloadこれは、ロードするためにページの内容のすべてを待って、広く支持されているので、あなたの関数を発射します。私は<body>の末尾に次のコードを追加することで、同様の問題を解決し

let printAndClose = '<script>onload = function() { window.print(); window.close(); }</sc' + 'ript>'; 

newWin.document.write(
    styles + 
    document.querySelector("table").outerHTML) + 
    printAndClose 
); 
+0

私はそれを使用しています // DOESNT WORK newWin.window.onload = function(){ newWin.print(); } – partizanos

0

関連する問題