簡體   English   中英

打印 DIV 的內容

[英]Print the contents of a DIV

打印 DIV 內容的最佳方法是什么?

與早期版本相比略有變化 - 在 CHROME 上測試

function PrintElem(elem)
{
    var mywindow = window.open('', 'PRINT', 'height=400,width=600');

    mywindow.document.write('<html><head><title>' + document.title  + '</title>');
    mywindow.document.write('</head><body >');
    mywindow.document.write('<h1>' + document.title  + '</h1>');
    mywindow.document.write(document.getElementById(elem).innerHTML);
    mywindow.document.write('</body></html>');

    mywindow.document.close(); // necessary for IE >= 10
    mywindow.focus(); // necessary for IE >= 10*/

    mywindow.print();
    mywindow.close();

    return true;
}

我認為有更好的解決方案。 讓您的 div 打印覆蓋整個文檔,但僅在打印時:

@media print {
    .myDivToPrint {
        background-color: white;
        height: 100%;
        width: 100%;
        position: fixed;
        top: 0;
        left: 0;
        margin: 0;
        padding: 15px;
        font-size: 14px;
        line-height: 18px;
    }
}

盡管@gabe已經說過,但如果您使用的是 jQuery,則可以使用我的printElement插件。

這里有一個示例, 這里有關於插件的更多信息。

用法相當簡單,只需使用 jQuery 選擇器抓取一個元素並打印它:

$("#myDiv").printElement();

我希望它有幫助!

使用 Jquery,只需使用此功能:

<script>
function printContent(el){
var restorepage = $('body').html();
var printcontent = $('#' + el).clone();
$('body').empty().html(printcontent);
window.print();
$('body').html(restorepage);
}
</script>

您的打印按鈕將如下所示:

<button id="print" onclick="printContent('id name of your div');" >Print</button>

編輯:如果您確實有需要保留的表單數據,則克隆不會復制它,因此您只需要獲取所有表單數據並在還原后將其替換為:

<script>
function printContent(el){
var restorepage = $('body').html();
var printcontent = $('#' + el).clone();
var enteredtext = $('#text').val();
$('body').empty().html(printcontent);
window.print();
$('body').html(restorepage);
$('#text').html(enteredtext);
}
</script>
<textarea id="text"></textarea>

從這里https://forums.asp.net/t/1261525.aspx

<html> 
<head>
    <script language="javascript">
        function printdiv(printpage) {
            var headstr = "<html><head><title></title></head><body>";
            var footstr = "</body>";
            var newstr = document.all.item(printpage).innerHTML;
            var oldstr = document.body.innerHTML;
            document.body.innerHTML = headstr + newstr + footstr;
            window.print();
            document.body.innerHTML = oldstr;
            return false;
        }
    </script>

    <title>div print</title>

</head>

<body>
    //HTML Page //Other content you wouldn't like to print
    <input name="b_print" type="button" class="ipt" onClick="printdiv('div_print');" value=" Print ">

    <div id="div_print">
        <h1 style="Color:Red">The Div content which you want to print</h1>
    </div>
    //Other content you wouldn't like to print //Other content you wouldn't like to print
</body>    
</html>

我使用Bill Paetzke答案打印包含圖像的 div,但它不適用於 google chrome

我只需要添加這一行myWindow.onload=function(){使其工作,這是完整的代碼

<html>
<head>
    <script type="text/javascript" src="http://jqueryjs.googlecode.com/files/jquery-1.3.1.min.js"> </script>
    <script type="text/javascript">
        function PrintElem(elem) {
            Popup($(elem).html());
        }

        function Popup(data) {
            var myWindow = window.open('', 'my div', 'height=400,width=600');
            myWindow.document.write('<html><head><title>my div</title>');
            /*optional stylesheet*/ //myWindow.document.write('<link rel="stylesheet" href="main.css" type="text/css" />');
            myWindow.document.write('</head><body >');
            myWindow.document.write(data);
            myWindow.document.write('</body></html>');
            myWindow.document.close(); // necessary for IE >= 10

            myWindow.onload=function(){ // necessary if the div contain images

                myWindow.focus(); // necessary for IE >= 10
                myWindow.print();
                myWindow.close();
            };
        }
    </script>
</head>
<body>
    <div id="myDiv">
        This will be printed.
        <img src="image.jpg"/>
    </div>
    <div>
        This will not be printed.
    </div>
    <div id="anotherDiv">
        Nor will this.
    </div>
    <input type="button" value="Print Div" onclick="PrintElem('#myDiv')" />
</body>
</html>

另外,如果有人只需要打印一個帶有 id 的 div,他就不需要加載 jquery

這是執行此操作的純 JavaScript 代碼

<html>
<head>
    <script type="text/javascript">
        function PrintDiv(id) {
            var data=document.getElementById(id).innerHTML;
            var myWindow = window.open('', 'my div', 'height=400,width=600');
            myWindow.document.write('<html><head><title>my div</title>');
            /*optional stylesheet*/ //myWindow.document.write('<link rel="stylesheet" href="main.css" type="text/css" />');
            myWindow.document.write('</head><body >');
            myWindow.document.write(data);
            myWindow.document.write('</body></html>');
            myWindow.document.close(); // necessary for IE >= 10

            myWindow.onload=function(){ // necessary if the div contain images

                myWindow.focus(); // necessary for IE >= 10
                myWindow.print();
                myWindow.close();
            };
        }
    </script>
</head>
<body>
    <div id="myDiv">
        This will be printed.
        <img src="image.jpg"/>
    </div>
    <div>
        This will not be printed.
    </div>
    <div id="anotherDiv">
        Nor will this.
    </div>
    <input type="button" value="Print Div" onclick="PrintDiv('myDiv')" />
</body>
</html>

我希望這可以幫助某人

function printdiv(printdivname) {
    var headstr = "<html><head><title>Booking Details</title></head><body>";
    var footstr = "</body>";
    var newstr = document.getElementById(printdivname).innerHTML;
    var oldstr = document.body.innerHTML;
    document.body.innerHTML = headstr+newstr+footstr;
    window.print();
    document.body.innerHTML = oldstr;
    return false;
}

這將打印您想要的div區域並將內容設置回原樣。 printdivname是要打印的div

創建一個單獨的打印樣式表,隱藏除您要打印的內容之外的所有其他元素。 加載時使用'media="print"對其進行標記:

<link rel="stylesheet" type="text/css" media="print" href="print.css" />

這允許您為打印輸出加載完全不同的樣式表。

如果你想強制瀏覽器的打印對話框出現在頁面上,你可以使用 JQuery 在加載時這樣做:

$(function() { window.print(); });

或觸發您想要的任何其他事件,例如用戶單擊按鈕。

我編寫了一個插件來解決這種情況。 我對那里的插件不滿意,並着手制作更廣泛/可配置的東西。

https://github.com/jasonday/printThis

我認為目前提出的解決方案有以下缺點:

  1. CSS 媒體查詢解決方案假設只有一個 div 可以打印。
  2. javascript 解決方案僅適用於某些瀏覽器。
  3. 銷毀父窗口內容並重新創建會造成混亂。

我對上述解決方案進行了改進。 這是我已經測試過的東西,它具有以下好處。

  1. 適用於所有瀏覽器,包括 IE、Chrome、Safari 和 firefox。
  2. 不破壞和重新加載父窗口。
  3. 可以在一頁上打印任意數量的 DIV。
  4. 使用 HTML 模板來避免容易出錯的字符串連接。

需要注意的要點:

  1. 必須在新創建的窗口上有一個 onload="window.print()" 。
  2. 不要從父級調用 targetwindow.close() 或 targetwindow.print()。
  3. 確保您執行 targetwindow.document.close() 和 target.focus()
  4. 我正在使用 jquery,但您也可以使用純 javascript 執行相同的技術。
  5. 您可以在此處查看此操作https://math.tools/table/multiplication 您可以通過單擊框標題上的打印按鈕單獨打印每個表格。

 <script id="print-header" type="text/x-jquery-tmpl"> <html> <header> <title>Printing Para {num}</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css"> <style> body { max-width: 300px; } </style> </header> <body onload="window.print()"> <h2>Printing Para {num} </h2> <h4>https://math.tools</h4> </script> <script id="print-footer" type="text/x-jquery-tmpl"> </body> </html> </script> <script> $('.printthis').click(function() { num = $(this).attr("data-id"); w = window.open(); w.document.write( $("#print-header").html().replace("{num}",num) + $("#para-" + num).html() + $("#print-footer").html() ); w.document.close(); w.focus(); //w.print(); Don't do this otherwise chrome won't work. Look at the onload on the body of the newly created window. ///w.close(); Don't do this otherwise chrome won't work }); </script>
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <a class="btn printthis" data-id="1" href="#" title="Print Para 1"><i class="fa fa-print"></i> Print Para 1</a> <a class="btn printthis" data-id="2" href="#" title="Print Para 2"><i class="fa fa-print"></i> Print Para 2</a> <p class="para" id="para-1"> Para 1 : Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p> <p class="para" id="para-2"> Para 2 : Lorem 2 ipsum 2 dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>

接受的解決方案不起作用。 Chrome 正在打印一個空白頁,因為它沒有及時加載圖像。 這種方法有效:

編輯:看來接受的解決方案在我的帖子之后被修改了。 為什么投反對票? 該解決方案也有效。

    function printDiv(divName) {

        var printContents = document.getElementById(divName).innerHTML;
        w = window.open();

        w.document.write(printContents);
        w.document.write('<scr' + 'ipt type="text/javascript">' + 'window.onload = function() { window.print(); window.close(); };' + '</sc' + 'ript>');

        w.document.close(); // necessary for IE >= 10
        w.focus(); // necessary for IE >= 10

        return true;
    }

我知道這是一個老問題,但我用 jQuery 解決了這個問題。

function printContents(id) {
    var contents = $("#"+id).html();

    if ($("#printDiv").length == 0) {
      var printDiv = null;
      printDiv = document.createElement('div');
      printDiv.setAttribute('id','printDiv');
      printDiv.setAttribute('class','printable');
      $(printDiv).appendTo('body');
    }

    $("#printDiv").html(contents);

    window.print();

    $("#printDiv").remove();
}

CSS

  @media print {
    .non-printable, .fancybox-outer { display: none; }
    .printable, #printDiv { 
        display: block; 
        font-size: 26pt;
    }
  }

如果您想擁有原始文檔中的所有樣式(包括內聯樣式),您可以使用這種方法。

  1. 復制完整的文件
  2. 用您要打印的元素替換正文。

執行:

class PrintUtil {
  static printDiv(elementId) {
    let printElement = document.getElementById(elementId);
    var printWindow = window.open('', 'PRINT');
    printWindow.document.write(document.documentElement.innerHTML);
    setTimeout(() => { // Needed for large documents
      printWindow.document.body.style.margin = '0 0';
      printWindow.document.body.innerHTML = printElement.outerHTML;
      printWindow.document.close(); // necessary for IE >= 10
      printWindow.focus(); // necessary for IE >= 10*/
      printWindow.print();
      printWindow.close();
    }, 1000)
  }   
}

盡管@BC 的答案是打印單頁的最佳選擇。

但是要使用 ctrl+P 同時打印多頁 A4 大小的頁面,以下解決方案可能會有所幫助。

@media print{
html *{
    height:0px!important;
    width:0px !important;
    margin: 0px !important;
    padding: 0px !important;
    min-height: 0px !important;
    line-height: 0px !important;
    overflow: visible !important;
    visibility: hidden ;


}


/*assing myPagesClass to every div you want to print on single separate A4 page*/

 body .myPagesClass {
    z-index: 100 !important;
    visibility: visible !important;
    position: relative !important;
    display: block !important;
    background-color: lightgray !important;
    height: 297mm !important;
    width: 211mm !important;
    position: relative !important;

    padding: 0px;
    top: 0 !important;
    left: 0 !important;
    margin: 0 !important;
    orphans: 0!important;
    widows: 0!important;
    overflow: visible !important;
    page-break-after: always;

}
@page{
    size: A4;
    margin: 0mm ;
    orphans: 0!important;
    widows: 0!important;
}}
  • 打開一個新窗口
  • 打開新窗口的文檔對象並在其中寫入一個簡單的文檔,其中只包含您擁有的 div 和必要的 html 標題等 - 您可能還希望將文檔拉入樣式表,具體取決於您的內容是
  • 在新頁面中放一個腳本來調用window.print()
  • 觸發腳本

這是我的 jquery 打印插件

(function ($) {

$.fn.printme = function () {
    return this.each(function () {
        var container = $(this);

        var hidden_IFrame = $('<iframe></iframe>').attr({
            width: '1px',
            height: '1px',
            display: 'none'
        }).appendTo(container);

        var myIframe = hidden_IFrame.get(0);

        var script_tag = myIframe.contentWindow.document.createElement("script");
        script_tag.type = "text/javascript";
        script = myIframe.contentWindow.document.createTextNode('function Print(){ window.print(); }');
        script_tag.appendChild(script);

        myIframe.contentWindow.document.body.innerHTML = container.html();
        myIframe.contentWindow.document.body.appendChild(script_tag);

        myIframe.contentWindow.Print();
        hidden_IFrame.remove();

    });
};
})(jQuery);

這是適用於 IE 和 Chrome 的 IFrame 解決方案:

function printHTML(htmlString) {
    var newIframe = document.createElement('iframe');
    newIframe.width = '1px';
    newIframe.height = '1px';
    newIframe.src = 'about:blank';

    // for IE wait for the IFrame to load so we can access contentWindow.document.body
    newIframe.onload = function() {
        var script_tag = newIframe.contentWindow.document.createElement("script");
        script_tag.type = "text/javascript";
        var script = newIframe.contentWindow.document.createTextNode('function Print(){ window.focus(); window.print(); }');
        script_tag.appendChild(script);

        newIframe.contentWindow.document.body.innerHTML = htmlString;
        newIframe.contentWindow.document.body.appendChild(script_tag);

        // for chrome, a timeout for loading large amounts of content
        setTimeout(function() {
            newIframe.contentWindow.Print();
            newIframe.contentWindow.document.body.removeChild(script_tag);
            newIframe.parentElement.removeChild(newIframe);
        }, 200);
    };
    document.body.appendChild(newIframe);
}

注意:這僅適用於啟用 jQuery 的網站

這個很酷的技巧非常簡單。 它在Google Chrome瀏覽器中對我有用。 Firefox 不允許您在沒有插件的情況下打印為 PDF。

  1. 首先,使用 (Ctrl + Shift + I) / (Cmd + Option + I) 打開檢查器。
  2. 在控制台中鍵入此代碼:

var jqchild = document.createElement('script');
jqchild.src = "https://cdnjs.cloudflare.com/ajax/libs/jQuery.print/1.5.1/jQuery.print.min.js";
document.getElementsByTagName('body')[0].appendChild(jqchild);
$("#myDivWithStyles").print(); // Replace ID with yours
  1. 它啟動打印對話框。 進行物理打印或將其保存為 PDF(在 chrome 中)。 完畢!

邏輯很簡單。 我們正在創建一個新的腳本標簽並將其附加在結束正文標簽的前面。 我們在 HTML 中注入了一個 jQuery 打印擴展。 使用您自己的 Div 標簽 ID 更改myDivWithStyles 現在它負責准備可打印的虛擬窗口。

在任何網站上嘗試。 唯一需要注意的是,有時復雜的 CSS 會導致樣式丟失。 但我們大多數時候都會得到內容。

只需使用PrintJS

let printjs = document.createElement("script");
printjs.src = "https://printjs-4de6.kxcdn.com/print.min.js";
document.body.appendChild(printjs);

printjs.onload = function (){
    printJS('id_of_div_you_want_to_print', 'html');
}

有點晚了,但我發現這真的很好!

function printDiv(divID) {
    //Get the HTML of div
    var divElements = document.getElementById(divID).innerHTML;
    //Get the HTML of whole page
    var oldPage = document.body.innerHTML;

    //Reset the page's HTML with div's HTML only
    document.body.innerHTML = 
       "<html><head><title></title></head><body>" + 
              divElements + "</body>";

    //Print Page
    window.print();

    //Restore orignal HTML
    document.body.innerHTML = oldPage;
          
}

在 Opera 中,嘗試:

    print_win.document.write('</body></html>');
    print_win.document.close(); // This bit is important
    print_win.print();
    print_win.close();

創建了一些通用的東西,可以在任何 HTML 元素上使用

HTMLElement.prototype.printMe = printMe;
function printMe(query){             
     var myframe = document.createElement('IFRAME');
     myframe.domain = document.domain;
     myframe.style.position = "absolute";
     myframe.style.top = "-10000px";
     document.body.appendChild(myframe);
     myframe.contentDocument.write(this.innerHTML) ;
     setTimeout(function(){
        myframe.focus();
        myframe.contentWindow.print();
        myframe.parentNode.removeChild(myframe) ;// remove frame
     },3000); // wait for images to load inside iframe
     window.focus();
}
//usage
document.getElementById('xyz').printMe();
document.getElementsByClassName('xyz')[0].printMe();

希望這可以幫助。

我修改了@BillPaetski 答案以使用 querySelector、添加可選 CSS、刪除強制 H1 標記並使標題可選地指定或從窗口中拉出。 它也不再自動打印並暴露內部結構,因此可以在包裝器功能或您喜歡的情況下切換它們。

僅有的兩個私有變量是 tmpWindow 和 tmpDoc,盡管我相信 title、css 和 elem 訪問可能會有所不同,應該假設所有函數參數都是私有的。

代碼:
 function PrintElem(elem, title, css) { var tmpWindow = window.open('', 'PRINT', 'height=400,width=600'); var tmpDoc = tmpWindow.document; title = title || document.title; css = css || ""; this.setTitle = function(newTitle) { title = newTitle || document.title; }; this.setCSS = function(newCSS) { css = newCSS || ""; }; this.basicHtml5 = function(innerHTML) { return '<!doctype html><html>'+(innerHTML || "")+'</html>'; }; this.htmlHead = function(innerHTML) { return '<head>'+(innerHTML || "")+'</head>'; }; this.htmlTitle = function(title) { return '<title>'+(title || "")+'</title>'; }; this.styleTag = function(innerHTML) { return '<style>'+(innerHTML || "")+'</style>'; }; this.htmlBody = function(innerHTML) { return '<body>'+(innerHTML || "")+'</body>'; }; this.build = function() { tmpDoc.write( this.basicHtml5( this.htmlHead( this.htmlTitle(title) + this.styleTag(css) ) + this.htmlBody( document.querySelector(elem).innerHTML ) ) ); tmpDoc.close(); // necessary for IE >= 10 }; this.print = function() { tmpWindow.focus(); // necessary for IE >= 10*/ tmpWindow.print(); tmpWindow.close(); }; this.build(); return this; }
用法:
 DOMPrinter = PrintElem('#app-container'); DOMPrinter.print();

這應該有效:

function printDiv(divName) {
     var printContents = document.getElementById(divName).innerHTML;
     var originalContents = document.body.innerHTML;
     document.body.innerHTML = printContents;
     window.print();
     document.body.innerHTML = originalContents;
}

HTML > 頭部

  <script type="text/javascript">
    function printDiv() {
        var divToPrint = document.getElementById('printArea');  
    //Firefox was just opening a new window with same content as opener and not performing the printing dialog, so needed to make it open a new instance of the window opener    
        newWin= window.open(self.location.href);
    //We want to format the document appropriately
       newWin.document.write("\<!DOCTYPE html\>\<html lang='es'\>\<head\>\<meta charset='utf-8'\/\>\<meta name='viewport' content='width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no'><meta http-equiv='X-UA-Compatible' content='IE=edge,chrome=1'\>\<meta name='HandheldFriendly' content='true'\/\>");
    //HTML ELEMENTS THAT WE WANT TO HIDE FROM THE PRINTING AREA
        newWin.document.write("<style type='text/css'>@media print{.dataTables_info,.dataTables_filter{height:0!important;width:0!important;margin:0!important;padding:0!important;min-height:0!important;line-height:0!important;overflow:visible!important;visibility:hidden}");
    //General Styling for Printing
        newWin.document.write("body {z-index:100!important;visibility:visible!important;position:relative!important;display:block!important;background-color:lightgray!important;height:297mm!important;width:211mm!important;position:relative!important;padding:0;top:0!important;left:0!important;margin:0!important;orphans:0!important;widows:0!important;overflow:visible!important;page-break-after:always}");
    //Some forced styling in css rules includying page break for a div
        newWin.document.write("body h1{font-size:1em; font-family:Verdana;} a.marked{color:black; text-decoration:none} .pagebreak { page-break-before: always; } ");
        newWin.document.write("@page{size:A4; margin:2em; orphans:0!important;widows:0!important}}</style>\<\/head>\<body>");
        newWin.document.write(divToPrint.innerHTML);
        newWin.document.write("</body></html>");
        newWin.focus();
        newWin.print();
    }
    </script>

HTML > 正文

<div id="printArea">
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
<!-- Page break -->
<div class="pagebreak">&nbsp;</div>
It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like).
</div>

下面的代碼復制了查詢選擇器所針對的所有相關節點,復制了它們在屏幕上看到的樣式,因為用於定位 css 選擇器的許多父元素將丟失。 如果有很多具有很多樣式的子節點,這會導致一些延遲。

理想情況下,您應該准備好打印樣式表,但這適用於沒有要插入的打印樣式表並且您希望在屏幕上看到的打印的用例。

如果您在此頁面的瀏覽器控制台中復制以下項目,它將打印此頁面上的所有代碼片段。

+function() {
    /**
     * copied from  https://stackoverflow.com/questions/19784064/set-javascript-computed-style-from-one-element-to-another
     * @author Adi Darachi https://stackoverflow.com/users/2318881/adi-darachi
     */
    var copyComputedStyle = function(from,to){
        var computed_style_object = false;
        //trying to figure out which style object we need to use depense on the browser support
        //so we try until we have one
        computed_style_object = from.currentStyle || document.defaultView.getComputedStyle(from,null);

        //if the browser dose not support both methods we will return null
        if(!computed_style_object) return null;

            var stylePropertyValid = function(name,value){
                        //checking that the value is not a undefined
                return typeof value !== 'undefined' &&
                        //checking that the value is not a object
                        typeof value !== 'object' &&
                        //checking that the value is not a function
                        typeof value !== 'function' &&
                        //checking that we dosent have empty string
                        value.length > 0 &&
                        //checking that the property is not int index ( happens on some browser
                        value != parseInt(value)

            };

        //we iterating the computed style object and compy the style props and the values
        for(property in computed_style_object)
        {
            //checking if the property and value we get are valid sinse browser have different implementations
                if(stylePropertyValid(property,computed_style_object[property]))
                {
                    //applying the style property to the target element
                        to.style[property] = computed_style_object[property];

                }   
        }   

    };


    // Copy over all relevant styles to preserve styling, work the way down the children tree.
    var buildChild = function(masterList, childList) {
        for(c=0; c<masterList.length; c++) {
           var master = masterList[c];
           var child = childList[c];
           copyComputedStyle(master, child);
           if(master.children && master.children.length > 0) {
               buildChild(master.children, child.children);
           }
        }
    }

    /** select elements to print with query selector **/
    var printSelection = function(querySelector) {
        // Create an iframe to make sure everything is clean and ordered.
        var iframe = document.createElement('iframe');
        // Give it enough dimension so you can visually check when modifying.
        iframe.width = document.width;
        iframe.height = document.height;
        // Add it to the current document to be sure it has the internal objects set up.
        document.body.append(iframe);

        var nodes = document.querySelectorAll(querySelector);
        if(!nodes || nodes.length == 0) {
           console.error('Printing Faillure: Nothing to print. Please check your querySelector');
           return;
        }

        for(i=0; i < nodes.length; i++) {

            // Get the node you wish to print.
            var origNode = nodes[i];

            // Clone it and all it's children
            var node = origNode.cloneNode(true);

            // Copy the base style.
            copyComputedStyle(origNode, node);

            if(origNode.children && origNode.children.length > 0) {
                buildChild(origNode.children, node.children);
            }

            // Add the styled clone to the iframe. using contentWindow.document since it seems the be the most widely supported version.

            iframe.contentWindow.document.body.append(node);
        }
        // Print the window
        iframe.contentWindow.print();

        // Give the browser a second to gather the data then remove the iframe.
        window.setTimeout(function() {iframe.parentNode.removeChild(iframe)}, 1000);
    }
window.printSelection = printSelection;
}();
printSelection('.default.prettyprint.prettyprinted')

這是一個非常老的帖子,但這是我使用正確答案所做的更新。 我的解決方案也使用 jQuery。

這一點是使用正確的打印視圖,包括所有樣式表以進行正確的格式化,並且在大多數瀏覽器中都得到支持。

function PrintElem(elem, title, offset)
{
    // Title constructor
    title = title || $('title').text();
    // Offset for the print
    offset = offset || 0;

    // Loading start
    var dStart = Math.round(new Date().getTime()/1000),
        $html = $('html');
        i = 0;

    // Start building HTML
    var HTML = '<html';

    if(typeof ($html.attr('lang')) !== 'undefined') {
        HTML+=' lang=' + $html.attr('lang');
    }

    if(typeof ($html.attr('id')) !== 'undefined') {
        HTML+=' id=' + $html.attr('id');
    }

    if(typeof ($html.attr('xmlns')) !== 'undefined') {
        HTML+=' xmlns=' + $html.attr('xmlns');
    }

    // Close HTML and start build HEAD
    HTML+='><head>';

    // Get all meta tags
    $('head > meta').each(function(){
        var $this = $(this),
            $meta = '<meta';

        if(typeof ($this.attr('charset')) !== 'undefined') {
            $meta+=' charset=' + $this.attr('charset');
        }

        if(typeof ($this.attr('name')) !== 'undefined') {
            $meta+=' name=' + $this.attr('name');
        }

        if(typeof ($this.attr('http-equiv')) !== 'undefined') {
            $meta+=' http-equiv=' + $this.attr('http-equiv');
        }

        if(typeof ($this.attr('content')) !== 'undefined') {
            $meta+=' content=' + $this.attr('content');
        }

        $meta+=' />';

        HTML+= $meta;
        i++;

    }).promise().done(function(){

        // Insert title
        HTML+= '<title>' + title  + '</title>';

        // Let's pickup all CSS files for the formatting
        $('head > link[rel="stylesheet"]').each(function(){
            HTML+= '<link rel="stylesheet" href="' + $(this).attr('href') + '" />';
            i++;
        }).promise().done(function(){
            // Print setup
            HTML+= '<style>body{display:none;}@media print{body{display:block;}}</style>';

            // Finish HTML
            HTML+= '</head><body>';
            HTML+= '<h1 class="text-center mb-3">' + title  + '</h1>';
            HTML+= elem.html();
            HTML+= '</body></html>';

            // Open new window
            var printWindow = window.open('', 'PRINT', 'height=' + $(window).height() + ',width=' + $(window).width());
            // Append new window HTML
            printWindow.document.write(HTML);

            printWindow.document.close(); // necessary for IE >= 10
            printWindow.focus(); // necessary for IE >= 10*/
console.log(printWindow.document);
            /* Make sure that page is loaded correctly */
            $(printWindow).on('load', function(){                   
                setTimeout(function(){
                    // Open print
                    printWindow.print();

                    // Close on print
                    setTimeout(function(){
                        printWindow.close();
                        return true;
                    }, 3);

                }, (Math.round(new Date().getTime()/1000) - dStart)+i+offset);
            });
        });
    });
}

稍后你簡單地需要這樣的東西:

$(document).on('click', '.some-print', function() {
    PrintElem($(this), 'My Print Title');
    return false;
});

試試看。

將元素傳遞給此函數以打印:

 function printElm(elm) { var orig = document.body.innerHTML; document.body.innerHTML = elm.outerHTML; print(); document.body.innerHTML = orig; }

function printDomElement(element) {
    element.classList.add("printCss");

    let printId = "printId";
    let name = ".printCss";
    let rules = "-webkit-print-color-adjust:exact;height:100%;width:100%;position:fixed;top:0;left:0;margin:0;";

    var style = document.createElement('style');
    style.id = printId;
    style.media = "print";
    document.getElementsByTagName('head')[0].appendChild(style);

    if (!(style.sheet || {}).insertRule)(style.styleSheet || style.sheet).addRule(name, rules);
    else style.sheet.insertRule(name + "{" + rules + "}", 0);

    window.print();

    setTimeout(() => {
      element.classList.remove("printCss");
      let elem = document.getElementById(printId);
      if (elem) elem.remove();
    }, 500);

  }

與最佳答案相同,以防您需要像我一樣打印圖像:

如果要打印圖像:

function printElem(elem)
    {
        Popup(jQuery(elem).attr('src'));
    }

    function Popup(data) 
    {
        var mywindow = window.open('', 'my div', 'height=400,width=600');
        mywindow.document.write('<html><head><title>my div</title>');
        mywindow.document.write('</head><body >');
        mywindow.document.write('<img src="'+data+'" />');
        mywindow.document.write('</body></html>');

        mywindow.print();
        mywindow.close();

        return true;
    }

最好的方法是將 div 的內容提交到服務器並打開一個新窗口,服務器可以將這些內容放入新窗口中。

如果這不是一個選項,您可以嘗試使用像 javascript 這樣的客戶端語言來隱藏頁面上除該 div 之外的所有內容,然后打印頁面......

暫無
暫無

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

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