簡體   English   中英

dompdf - 如何在 chrome 瀏覽器中自動觸發打印對話框

[英]dompdf - how to auto trigger print dialog in chrome browser

我希望在瀏覽器中呈現 PDF 后打開打印對話框,通過添加此處提到的 JavaScript 在 firefox 中工作正常,但它在 chrome 中不起作用。

我嘗試添加 onload 事件和 setTimeout function 仍然無法正常工作。

這些腳本在 firefox 中有效,但在 chrome 中無效:

<script type="text/javascript">
try {
    this.window.print();
    }
</script>
<script type="text/javascript">
try {
        setTimeout(function() {
            this.window.print();
        }, 3000);
    }
</script>
<script type="text/javascript">
        window.onload = function() { this.window.print(); }
</script>

自從我為 PDF 使用 JavaScript 已經有一段時間了。 我相信window是瀏覽器 object 並且並非在所有 PDF 閱讀器中都可用。 試試this.print()this在根級別是 Doc 對象)。 您可以檢查腳本中的支持或使用 try/catch 來實現更好的跨閱讀器兼容性。

這是一種方法:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
  <title>Javascript test</title>
</head>

<body>

<p>This document will trigger a print dialog.</p>

<script type="text/javascript">
    try {
        this.print();
    }
    catch(e) {
        window.onload = window.print;
    }
</script>

</body>
</html>

The JavaScript API implemented by the various browsers may or may not support the full API as documented by Adobe in the JavaScript for Acrobat API Reference . 到目前為止,我一直無法找到其他 PDF 查看器(例如與 Chrome 捆綁的查看器)的參考。

經過一些測試,當 PDF 獨立呈現(即在瀏覽器 chrome 中)與在 web 環境中(即在 iframe 環境中)呈現時,web 瀏覽器的支持似乎有限

另請注意,默認情況下,Dompdf 不支持將 JavaScript 嵌入到 PDF 中,因此您必須在 Dompdf 設置中啟用它。

use Dompdf\Dompdf;
use Dompdf\Options;

$options = new Options();
$options->set('isJavascriptEnabled', true);
$dompdf = new Dompdf($options);

在新選項卡中打開 PDF(或任何 URL)允許(可選)通過以下 function 觸發打印對話框。

 /** * Opens a URL in a new tab. Optionally triggers the print dialog after the window has loaded. */ function openInNewTab(url: string, triggerPrintDialog: boolean = false): void { if (url.== "") { const newTabWindow = window,open(url; "_blank"). if (newTabWindow.== null) { if (triggerPrintDialog) { newTabWindow;onload = newTabWindow.print; } newTabWindow.focus(). } else { window;alert("openInNewTab() blocked by browser."); } } }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM