Nice programing

웹 페이지의 특정 부분 인쇄

nicepro 2020. 12. 6. 22:05
반응형

웹 페이지의 특정 부분 인쇄


응용 프로그램의 특정 부분을 인쇄하려고합니다.

응용 프로그램에는 이름과 성을 표시하는 사용자 목록이 있습니다. 사용자를 클릭하면 더 자세한 정보가 포함 된 팝업이 표시됩니다.

클릭 한 사용자의 팝업 만 인쇄하려면 어떻게해야합니까? 팝업은 다음과 같습니다.

 <div id="user<?=$user->id;?>" class="popup">
      <div class="details">
           User details...
      </div>
      <a href="#print">Print</a>
 </div>

하지만 인쇄 버튼은 아직 작동하지 않습니다.


간단한 JavaScript를 사용하여 페이지에서 특정 div를 인쇄 할 수 있습니다.

var prtContent = document.getElementById("your div id");
var WinPrint = window.open('', '', 'left=0,top=0,width=800,height=900,toolbar=0,scrollbars=0,status=0');
WinPrint.document.write(prtContent.innerHTML);
WinPrint.document.close();
WinPrint.focus();
WinPrint.print();
WinPrint.close();

사용자가 인쇄 할 수 있기를 원하는 정보 만 포함 된 새 창을 열거 나 새 페이지로 이동해야합니다.

Javscript :

function printInfo(ele) {
    var openWindow = window.open("", "title", "attributes");
    openWindow.document.write(ele.previousSibling.innerHTML);
    openWindow.document.close();
    openWindow.focus();
    openWindow.print();
    openWindow.close();
}

HTML :

<div id="....">
    <div>
        content to print
    </div><a href="#" onclick="printInfo(this)">Print</a>
</div>

몇 가지 참고 사항 : 앵커와 인쇄 할 콘텐츠가 포함 된 div 사이에 공백이 없어야합니다.


모든 복잡한 자바 스크립트 대신 간단하게이 작업을 수행 할 수 CSS있습니다. 하나는 일반 화면 표시 용이고 다른 하나는 인쇄하려는 콘텐츠 표시하기 위해 두 개의 CSS 파일을 사용하면됩니다 . 이 후자의 파일에서는 인쇄하지 않으려는 모든 항목을 숨기고 팝업 만 표시합니다.

media두 CSS 파일 속성 을 정의해야 합니다.

<link rel="stylesheet" href="screen-css.css" media="all" />
<link rel="stylesheet" href="print-css.css" media="print" />

선택한 요소의 HTML을 인쇄하기 위해이 jQuery 확장을 만들었습니다. $('#div2').print();

$.fn.extend({
    print: function() {
        var frameName = 'printIframe';
        var doc = window.frames[frameName];
        if (!doc) {
            $('<iframe>').hide().attr('name', frameName).appendTo(document.body);
            doc = window.frames[frameName];
        }
        doc.document.body.innerHTML = this.html();
        doc.window.print();
        return this;
    }
});

여기 에서 실제로 확인 하십시오 .


CSS를 사용하여 인쇄하지 않으려는 콘텐츠를 숨 깁니다. 사용자가 인쇄를 선택하면 페이지는 " media ="print " CSS에서 페이지 레이아웃에 대한 지침 을 찾습니다 .

미디어 = "인쇄" CSS는 우리가 인쇄 원하지 않는 내용을 숨길 수있는 지침이있다.

<!-- CSS for the things we want to print (print view) -->
<style type="text/css" media="print">

#SCREEN_VIEW_CONTAINER{
        display: none;
    }
.other_print_layout{
        background-color:#FFF;
    }
</style>

<!-- CSS for the things we DO NOT want to print (web view) -->
<style type="text/css" media="screen">

   #PRINT_VIEW{
      display: none;
   }
.other_web_layout{
        background-color:#E0E0E0;
    }
</style>

<div id="SCREEN_VIEW_CONTAINER">
     the stuff I DO NOT want printed is here and will be hidden - 
     and not printed when the user selects print.
</div>

<div id="PRINT_VIEW">
     the stuff I DO want printed is here.
</div>

다음은 CSS 파일을로드하거나 인쇄 할 부품에 이미지 참조가있는 향상된 버전입니다.

이러한 경우에는 print () 함수를 호출하기 전에 CSS 파일이나 이미지가 완전히로드 될 때까지 기다려야합니다. 따라서 print () 및 close () 함수 호출을 html로 이동하는 것이 좋습니다. 다음은 코드 예입니다.

var prtContent = document.getElementById("order-to-print");
var WinPrint = window.open('', '', 'left=0,top=0,width=384,height=900,toolbar=0,scrollbars=0,status=0');
WinPrint.document.write('<html><head>');
WinPrint.document.write('<link rel="stylesheet" href="assets/css/print/normalize.css">');
WinPrint.document.write('<link rel="stylesheet" href="assets/css/print/receipt.css">');
WinPrint.document.write('</head><body onload="print();close();">');
WinPrint.document.write(prtContent.innerHTML);
WinPrint.document.write('</body></html>');
WinPrint.document.close();
WinPrint.focus();

더 나은 옵션이 있습니다.

먼저 인쇄 가능 섹션과 인쇄 불가능 섹션을 클래스 이름 또는 ID로 구분하십시오.

window.onafterprint = onAfterPrint;

function print(){
  //hide the nonPrintable div  
}

function onAfterPrint(){
  // Visible the nonPrintable div
}
<input type="button" onclick="print()" value="Print"/>

그게 다야


https://stackoverflow.com/a/1072151/421243 에서 답변했듯이 Javascript로 숨겨진 프레임에 특정 섹션을 추가하고 초점을 맞춘 다음 인쇄 할 수 있습니다.


In printPageArea() function, pass the specific div ID which you want to print. I've found this JavaScript code from codexworld.com.

function printPageArea(areaID){
    var printContent = document.getElementById(areaID);
    var WinPrint = window.open('', '', 'width=900,height=650');
    WinPrint.document.write(printContent.innerHTML);
    WinPrint.document.close();
    WinPrint.focus();
    WinPrint.print();
    WinPrint.close();
}

The complete code and tutorial can be found from here - How to Print Page Area using JavaScript.


I wrote a tiny JavaScript module called PrintElements for dynamically printing parts of a webpage.

It works by iterating through selected node elements, and for each node, it traverses up the DOM tree until the BODY element. At each level, including the initial one (which is the to-be-printed node’s level), it attaches a marker class (pe-preserve-print) to the current node. Then attaches another marker class (pe-no-print) to all siblings of the current node, but only if there is no pe-preserve-print class on them. As a third act, it also attaches another class to preserved ancestor elements pe-preserve-ancestor.

A dead-simple supplementary print-only css will hide and show respective elements. Some benefits of this approach is that all styles are preserved, it does not open a new window, there is no need to move around a lot of DOM elements, and generally it is non-invasive with your original document.

See the demo, or read the related article for further details.

참고URL : https://stackoverflow.com/questions/12997123/print-specific-part-of-webpage

반응형