jquery 如何在JavaScript中打印呈现的HTML页面的一部分?

j2qf4p5b  于 12个月前  发布在  jQuery
关注(0)|答案(7)|浏览(123)

JavaScript代码窗口.print()可以打印当前HTML页面。
如果我在HTML页面中有一个div(例如,从ASP.NET MVC视图呈现的页面),那么我只想打印div。
是否有任何jQuery unobtrusive 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。

rggaifut

rggaifut1#

我会这样说:

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

字符串

72qzrwbm

72qzrwbm2#

沿着与一些建议相同的路线,您至少需要执行以下操作:

  • 通过JavaScript动态加载一些CSS
  • 制作一些特定于打印的CSS规则
  • 通过JavaScript应用您的CSS规则

一个CSS的例子可以像这样简单:

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

  body .printable {
    display:block;
  }
}

字符串
然后,您的JavaScript只需要将“printable”类应用于目标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>

gudnpqoy

gudnpqoy3#

尝试以下JavaScript代码:

function printout() {

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

字符串

qzlgjiam

qzlgjiam4#

<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

htrmnn0y

htrmnn0y5#

您可以使用打印样式表,但这将影响所有打印功能。
您可以尝试在外部拥有一个打印样式表,当按下按钮时,它通过JavaScript包含在内,然后调用window.print(),然后删除它。

zvms9eto

zvms9eto6#

你可以使用jquery来做这件事。

$('#btnSubmit').click(function(){
    var divContent = $("#div3").html();
    var originalContents = $("body").html();

    $("body").empty().html(divContent );
    window.print();
    $("body").html(originalContents);
})

字符串

3pmvbmvn

3pmvbmvn7#

我有一个问题,输入控件在打印时丢失了它们的值,所以我编写了这个代码。这一系列的函数允许你打印一些静态HTML片段或特定节点的内容,并保留输入值和功能,用类“hideToPrint”隐藏选定的元素。并提供了一个回调函数来修改打印的HTML,这样你就可以用其他方式修改它,而不会干扰原始节点。当打印对话框打开时,body看起来像你正在打印的东西。
这只在Chrome上测试过。
CSS:

@media print {
  .hideToPrint {
    display: none;
  }
}

字符串
JS:

/**
 * Takes the outerHTML of the element referenced by contentId
 * and applies the fnModifyHtml(printContents) to the 
 * outerHTML content if specified, and prints it.
 * Any content element that has the class "hideToPrint" will
 * be hidden for printing.
 * @param {string} contentId host element id
 * @param {function=} fnModifyHtml 
 */
async function as_printContent(contentId, fnModifyHtml=null) {
  const aHideToPrint = Array.from(document.getElementsByClassName('hideToPrint'));
  aHideToPrint.forEach((el) => {
    hide(el);
  });

  await as_printRawContent(ge(contentId), fnModifyHtml);
  aHideToPrint.forEach((el) => {
    show(el);
  });
}

/**
 * Asynchronously prints the raw content of an element.
 *
 * @param {Element|string} elContent - The element or HTML string to print.
 * @param {function} fnModifyHtml - A function to modify the printed HTML.
 * @return {Promise<void>} A promise that resolves when the printing is done.
 */
async function as_printRawContent(elContent, fnModifyHtml = null) {
  if (typeof(elContent) == 'string') {
    // this is HTML and needs to be placed into a temporary element
    const html = elContent;
    elContent = document.createElement('div');
    elContent.innerHTML = html;
  }
  const aBodyValues = saveNodeValues(document.body);
  const bodyHTML = document.body.innerHTML;

  const aPrintContentValues = saveNodeValues(elContent);
  let printContents = elContent.outerHTML;
  if (fnModifyHtml) {
    printContents = fnModifyHtml(printContents);
  }

  document.body.innerHTML = printContents;
  restoreNodeValues(document.body, aPrintContentValues);

  await delay(1);
  window.print();
  document.body.innerHTML = bodyHTML;
  restoreNodeValues(document.body, aBodyValues);

  addEventHandlers();
}

/**
 * Retrieve the values of all input, select, and textarea elements within a given node.
 *
 * @param {HTMLElement} node - The node to search for input elements.
 * @return {Array} An array of objects containing the id, value, and type of each input element.
 */
function saveNodeValues(node) {
  return Array.from(node.querySelectorAll('input, select, textarea')).map((el) => {
    if (!el.id) {
      console.assert(el.id, `Element ${el.outerHTML} has no id`);
    }
    return { 
      id: el.id, 
      value: (el.type == 'checkbox') ? el.checked : el.value, 
      type: el.type 
    };
  });
}

/**
 * Restores the values of the specified DOM elements based on the provided array of values.
 *
 * @param {Node} node - The root node from which the DOM elements will be searched.
 * @param {Array} aValues - An array of objects containing the id, value, and type of each element to be restored.
 * @param {string} aValues[].id - The id of the DOM element.
 * @param {any} aValues[].value - The value to be restored on the DOM element.
 * @param {string} aValues[].type - The type of the DOM element (e.g., 'checkbox', 'text', etc.).
 */
function restoreNodeValues(node, aValues) {
  aValues.forEach(({ id, value, type }) => {
    const el = ge(id);
    if (el) {
      if (type === 'checkbox') {
        el.checked = value ? 'checked' : '';
      } else {
        el.value = value;
      }
    }
  });
}

/**
 * Delays the execution of subsequent code for a specified amount of time.
 * @param {number} time The amount of time to delay in milliseconds.
 * @returns {Promise} A promise that resolves after the specified time has passed.
 */
async function delay(time) {
  return new Promise((resolve) => {
    setTimeout(resolve, time);
  });
}

相关问题