簡體   English   中英

打開具有不同 HTML 內容的打印對話框窗口

[英]Open print dialog window with different HTML content

為了打開當前頁面的打印對話框,我們執行如下操作:

<a href="javascript:window.print()">Print</a>

如何在當前頁面中創建一個鏈接,以打開與實際頁面不同上下文的打印對話框?


Chrome 中的打印對話框: 在此處輸入圖片說明

打印對話框

在玩耍(和一些谷歌搜索)之后,我提出了這個解決方案:

我向當前視圖添加了一個non-printable printable類,向可打印的容器元素添加了一個non-printable類。 在我的 CSS 中,我使用了css 媒體查詢,其中@media screen@media print狀態包含相應的顯示行為:

@media screen {
  .printable { display: none; }
  .non-printable { display: block; }
}

@media print {
  .printable { display: block; }
  .non-printable { display: none; }
}

現在,我可以從當前視圖打印新內容,而無需打開新選項卡或更改當前視圖。

查看此jsFiddle支持的瀏覽器列表。

我不確定這是否真的是您問題的答案,因為您的問題幾乎沒有關於打開新窗口的含義的詳細信息。

如果你在 /page/one 並且你想打開一個鏈接 /report/page 並自動打開打印對話框......那么這就像在加載事件上觸發window.print一樣簡單,例如

<body onload='window.print()'>

如果您不希望該頁面始終打開打印對話框,則在您想要打印時以及在 URL 中找到該頁面時,創建指向新頁面的鏈接/report/page?print=1或其他類似內容觸發 onload 事件。

在 div 中包含可打印的內容。 喜歡:

HTML:

<div id='printarea'>
    <p>This is a sample text for printing purpose.</p>
    <input type='button' id='btn' value='Print' onclick='printFunc();'>
</div>
<p>Do not print.</p>

查詢:

function printFunc() {
    var divToPrint = document.getElementById('printarea');
    var htmlToPrint = '' +
        '<style type="text/css">' +
        'table th, table td {' +
        'border:1px solid #000;' +
        'padding;0.5em;' +
        '}' +
        '</style>';
    htmlToPrint += divToPrint.outerHTML;
    newWin = window.open("");
    newWin.document.write("<h3 align='center'>Print Page</h3>");
    newWin.document.write(htmlToPrint);
    newWin.print();
    newWin.close();
    }

它只會打印可打印的 div。謝謝

有一個很好的 Javascript 插件叫做PrintThis可以很容易地完成這個。

您只需要使用jQuery選擇器並調用插件,例如:

$('selector').printThis();

https://github.com/jasonday/printThis

暫無
暫無

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

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