it-source

DIV의 내용을 인쇄합니다.

criticalcode 2022. 10. 21. 22:54
반응형

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되어 있지만 하지 않았습니다.

이 줄만 하면 됐어요.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를 로드할 필요가 없습니다.

여기 이것을 하기 위한 순수한 자바스크립트 코드가 있습니다.

<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는 1개뿐이라고 가정합니다.
  2. Javascript 솔루션은 특정 브라우저에서만 작동합니다.
  3. 상위 창 내용을 삭제하고 엉망진창으로 만드는 재생성.

위의 해결방법이 개선되었습니다.여기 제가 테스트한 것은 다음과 같은 장점을 가지고 매우 잘 작동하는 것입니다.

  1. IE, Chrome, Safari 및 Firefox를 포함한 모든 브라우저에서 작동합니다.
  2. 부모 창을 파기하거나 새로고침하지 않습니다.
  3. 한 페이지에 임의의 수의 DIV를 인쇄할 수 있습니다.
  4. HTML 템플릿을 사용하여 오류가 발생하기 쉬운 문자열 연결을 방지합니다.

주의사항:

  1. 새로 생성된 창에 onload="contract.print()"가 있어야 합니다.
  2. 부모로부터 target window.close() 또는 target window.print()를 호출하지 마십시오.
  3. target window.document.close() 및 target을 실행해야 합니다.포커스()
  4. 저는 jquery를 사용하고 있습니다만, 플레인 javascript에서도 같은 기술을 사용할 수 있습니다.
  5. 기능은 https://math.tools/table/곱셈에서 확인할 수 있습니다.박스 헤더의 인쇄 버튼을 클릭하면, 각 테이블을 개별적으로 인쇄할 수 있습니다.

<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>
  

승인된 솔루션이 작동하지 않았습니다.크롬은 이미지를 제때 로드하지 못해 빈 페이지를 인쇄하고 있었다.이 접근방식은 다음과 같습니다.

편집: 투고 후에 승인된 솔루션이 수정된 것 같습니다.왜 다운보트야?이 솔루션도 동작합니다.

    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;
    }

원본 문서의 모든 스타일(인라인 스타일 포함)을 가지려면 이 방법을 사용할 수 있습니다.

  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)
  }   
}

오래된 질문인 것은 알지만, 저는 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;
    }
  }
  • 새 창을 엽니다.
  • 새 창의 문서 개체를 열고 가지고 있는 div와 필요한 html 머리글 등을 포함하는 간단한 문서를 여기에 씁니다. 내용에 따라 문서를 스타일시트로 가져올 수도 있습니다.
  • 새 페이지에 스크립트를 넣고 window.print()를 호출합니다.
  • 스크립트를 트리거하다

단, 한 페이지 인쇄에는 @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;
}}

여기 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 지원 사이트에서만 작동합니다.

이 멋진 속임수는 매우 간단하다.구글 크롬 브라우저에서 작동했어요.Firefox 에서는, 플러그 인 없이 PDF 로 인쇄할 수 없습니다.

  1. 먼저 (Ctrl + Shift + I) / (Cmd + 옵션 + 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(크롬)로 저장합니다.알았어!

논리는 간단하다.새로운 스크립트 태그를 생성하여 닫는 본문 태그 앞에 부착합니다.HTML에 jQuery 인쇄 확장을 삽입했습니다. myDivWithStyles를 자신의 Div 태그 ID로 변경하십시오.이제 인쇄 가능한 가상 창을 준비하는 작업이 필요하게 되었습니다.

어느 사이트에서나 사용해 보세요.CSS에 의해 스타일이 누락될 수 있는 것은 주의사항뿐입니다.하지만 우리는 대부분의 경우 내용을 얻습니다.

인쇄만 사용JS

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();

이게 도움이 됐으면 좋겠다.

querySelector를 사용하고, 옵션의 CSS를 추가하고, 강제 H1 태그를 삭제하고, 임의로 제목을 지정하거나 창에서 풀하도록 @BillPaetski 응답을 수정했습니다.또한 자동인쇄가 되지 않고 내부가 노출되어 래퍼 기능이나 원하는 대로 전환할 수 있습니다.

tmpWindow와 tmpDoc 두 가지 프라이빗 변수만 있습니다.단, 제목, css 및 elem 액세스는 다를 수 있지만 모든 함수 인수는 프라이빗이라고 가정해야 합니다.

Code:
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;
}
Usage:
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;
    }

언급URL : https://stackoverflow.com/questions/2255291/print-the-contents-of-a-div

반응형