2015-08-28 40 views
2

我試圖從網頁上打印一個動態生成的PDF。如何打印動態生成的pdf dataUrl?

var $iframe = $('<iframe>'); 
$iframe.appendTo('body'); 
$iframe.load(function() { 
    var iframe = $iframe[0]; 
    var result = iframe.contentWindow.document.execCommand("print", false, null); 
    if (!result) iframe.contentWindow.print(); 
    $.remove($iframe); 
}); 
$iframe.attr('src', dataUrl); 

的execCommand()給出了錯誤信息:

Uncaught SecurityError: Blocked a frame with origin " http://localhost:2520 " from accessing a frame with origin "null". The frame requesting access has a protocol of "http", the frame being accessed has a protocol of "data". Protocols must match.

此外,設置在src ATTR給出了警告:

Resource interpreted as Document but transferred with MIME type application/pdf:

的dataUrl看起來是這樣的:

data:application/pdf;base64,JVBERi0xLjQKJdP... 

編輯:@Mike C

我可以創建iframe並顯示pdf,但是當我打印時,它是空白的。

<style type="text/css" media="print"> 
    body * { display:none } 
    iframe#theframe { display:block } 
</style> 

var $iframe = $('<iframe id="theframe" src="'+dataUrl+'"></iframe>'); 
$iframe.appendTo('body'); 
$iframe.load(function() { 
    setTimeout(function() { 
     window.print(); 
    }, 1000); 
}); 
+0

[跨網域iframe獲取DOM含量](可能重複http://stackoverflow.com/questions/6170925/get-dom- content-of-cross-domain-iframe) –

+0

我不需要獲取內容,已經有內容!我只需要打印。 – Garfield

+0

如果顯示而不是打印PDF,用戶是否更舒服?也許他們寧願要保存PDF或甚至爲某種原因製作截圖。我不認爲打印PDF按鈕會很方便。 – kay

回答

1

嘗試利用window.open()document.write()setTimeout()

var popup = window.open("", "w"); 

var html = '<!doctype html><html><head></head>' 
      + '<body marginwidth="0" marginheight="0" style="background-color: rgb(38,38,38)">' 
      + '<embed width="100%" height="100%" name="plugin" src="data:application/pdf;base64,JVBERi0xLjQKJdP..." type="application/pdf">' 
      + '<script>setTimeout("print()", 1000)</script></body></html>'; 

popup.document.write(html); 
+0

Chrome在一個短滾動框(150px高)中顯示pdf。它打開打印對話框,但頁面在頁眉和頁腳處空白。 FF還在150px高滾動框中顯示pdf,但不會顯示打印對話框。 IE11完全不顯示PDF,並且不會顯示打印對話框。 – Garfield

+0

@PaulBrown _「它會對服務器執行ajax調用以獲取數據URI。」_可以包含在執行'$ .ajax()'時出現問題的'js'?試圖返回響應爲「Blob」?請參閱http://stackoverflow.com/q/12876000/ – guest271314

+0

我base64編碼在服務器上...但在這裏嘗試http://stackoverflow.com/a/18650249/358954 – Garfield