IT Share you

렌더링 된 HTML 페이지의 일부를 JavaScript로 인쇄하려면 어떻게합니까?

shareyou 2020. 11. 19. 22:19
반응형

렌더링 된 HTML 페이지의 일부를 JavaScript로 인쇄하려면 어떻게합니까?


JavaScript 코드 window.print ()는 현재 HTML 페이지를 인쇄 할 수 있습니다.

HTML 페이지에 div가있는 경우 (예 : ASP.NET MVC 보기 에서 렌더링 된 페이지 ) div 만 인쇄하고 싶습니다.

이 요청을 구현하는 데 눈에 띄지 않는 jQuery JavaScript 또는 일반 JavaScript 코드가 있습니까?

더 명확하게 말하면 렌더링 된 HTML 페이지가 다음과 같다고 가정합니다.

<html xmlns="http://www.w3.org/1999/xhtml">

    <head id="Head" runat="server">
        <title>
            <asp:ContentPlaceHolder runat="server" ID="TitleContent" />
        </title>
    </head>

    <body>
            <div id="div1" class="div1">....</div>
            <div id="div2" class="div2">....</div>
            <div id="div3" class="div3">....</div>
            <div id="div4" class="div4">....</div>
            <div id="div4" class="div4">....</div>
        <p>
            <input id="btnSubmit" type="submit" value="Print" onclick="divPrint();" />
        </p>
    </body>
</html>

그런 다음 인쇄 버튼을 클릭하고 div3 만 인쇄하고 싶습니다.


나는 다음과 같이 그것에 대해 갈 것입니다.

<html>
    <head>
        <title>Print Test Page</title>
        <script>
            printDivCSS = new String ('<link href="myprintstyle.css" rel="stylesheet" type="text/css">')
            function printDiv(divId) {
                window.frames["print_frame"].document.body.innerHTML=printDivCSS + document.getElementById(divId).innerHTML;
                window.frames["print_frame"].window.focus();
                window.frames["print_frame"].window.print();
            }
        </script>
    </head>

    <body>
        <h1><b><center>This is a test page for printing</center></b><hr color=#00cc00 width=95%></h1>
        <b>Div 1:</b> <a href="javascript:printDiv('div1')">Print</a><br>
        <div id="div1">This is the div1's print output</div>
        <br><br>
        <b>Div 2:</b> <a href="javascript:printDiv('div2')">Print</a><br>
        <div id="div2">This is the div2's print output</div>
        <br><br>
        <b>Div 3:</b> <a href="javascript:printDiv('div3')">Print</a><br>
        <div id="div3">This is the div3's print output</div>
        <iframe name="print_frame" width="0" height="0" frameborder="0" src="about:blank"></iframe>
    </body>
</html>

제안 사항 중 일부와 동일한 줄을 따라 적어도 다음을 수행해야합니다.

  • JavaScript를 통해 일부 CSS를 동적으로로드
  • 인쇄 관련 CSS 규칙 작성
  • JavaScript를 통해 멋진 CSS 규칙 적용

CSS 예제는 다음과 같이 간단 할 수 있습니다.

@media print {
  body * {
    display:none;
  }

  body .printable {
    display:block;
  }
}

그러면 JavaScript는 "인쇄 가능한"클래스를 대상 div에 적용하기 만하면되고 인쇄가 발생할 때 표시되는 유일한 것입니다 (다른 충돌하는 CSS 규칙이없는 한-별도의 연습).

<script type="text/javascript">
  function divPrint() {
    // Some logic determines which div should be printed...
    // This example uses div3.
    $("#div3").addClass("printable");
    window.print();
  }
</script>

인쇄가 발생한 후 대상에서 클래스를 선택적으로 제거하거나 인쇄가 발생한 후 동적으로 추가 된 CSS를 제거 할 수 있습니다.

아래는 전체 작업 예제이며 유일한 차이점은 인쇄 CSS가 동적으로로드되지 않는다는 것입니다. 정말 눈에 거슬리지 않게하려면 이 답변과 같이 CSS를 동적으로로드 해야합니다 .

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
  <head>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8" />
    <title>Print Portion Example</title>
    <style type="text/css">
      @media print {
        body * {
          display:none;
        }

        body .printable {
          display:block;
        }
      }
    </style>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
  </head>

  <body>
    <h1>Print Section Example</h1>
    <div id="div1">Div 1</div>
    <div id="div2">Div 2</div>
    <div id="div3">Div 3</div>
    <div id="div4">Div 4</div>
    <div id="div5">Div 5</div>
    <div id="div6">Div 6</div>
    <p><input id="btnSubmit" type="submit" value="Print" onclick="divPrint();" /></p>
    <script type="text/javascript">
      function divPrint() {
        // Some logic determines which div should be printed...
        // This example uses div3.
        $("#div3").addClass("printable");
        window.print();
      }
    </script>
  </body>
</html>

이 JavaScript 코드를 시도하십시오.

function printout() {

    var newWindow = window.open();
    newWindow.document.write(document.getElementById("output").innerHTML);
    newWindow.print();
}

<div id="invocieContainer">
    <div class="row">
        ...Your html Page content here....
    </div>
</div>

<script src="/Scripts/printThis.js"></script>
<script>
    $(document).on("click", "#btnPrint", function(e) {
        e.preventDefault();
        e.stopPropagation();
        $("#invocieContainer").printThis({
            debug: false, // show the iframe for debugging
            importCSS: true, // import page CSS
            importStyle: true, // import style tags
            printContainer: true, // grab outer container as well as the contents of the selector
            loadCSS: "/Content/bootstrap.min.css", // path to additional css file - us an array [] for multiple
            pageTitle: "", // add title to print page
            removeInline: false, // remove all inline styles from print elements
            printDelay: 333, // variable print delay; depending on complexity a higher value may be necessary
            header: null, // prefix to html
            formValues: true // preserve input/form values
        });

    });
</script>

printThis.js 소스 코드의 경우 새 탭 https://raw.githubusercontent.com/jasonday/printThis/master/printThis.js의 URL 아래에 복사하여 붙여 넣으십시오.


You could use a print stylesheet, but this will affect all print functions.

You could try having a print stylesheet externalally, and it is included via JavaScript when a button is pressed, and then call window.print(), then after that remove it.

참고URL : https://stackoverflow.com/questions/1071962/how-do-i-print-part-of-a-rendered-html-page-in-javascript

반응형