How to print a portion of an HTML page?
I have an html page i want to print a portion of this html page, I know a javascript function to print a page,
onClick="javascript:window.print(); return false;
but how can I print a por开发者_开发技巧tion of a page?
If anyone has an idea, please share it with me.
You should use a separate css for the print media. This allows you to hide/show portions of the page when it gets printed.
html :
<div class="dont-print-that">
blah
</div>
print this!
include:
<link rel="stylesheet" type="text/css" media="print" href="print.css" />
print.css
.dont-print-that{display:none;}
The other solution is to open a new window with only the content you want to print. You could either do that in a popup or an iframe. Personally I find the CSS solution more elegant, but that's up to you.
If you want to implement multiple "Print this section" features on a page, then print media stylesheets (described in other answers) are the way forward…
… but combine that with alternative stylesheets so you can switch to one for each section.
It can be done using JavaScript and iframes:
- Dump the innerHTML of the container into the iFrame (plus any print-specific CSS
- print the iFrame contents.
Try it out in JSFiddle
You can see the code here, but it won't work due to what are probably security limitations in StackOverflow's renderer.
const printButton = document.getElementById('print-button');
printButton.addEventListener('click', event => {
// build the new HTML page
const content = document.getElementById('name-card').innerHTML;
const printHtml = `<html>
<head>
<meta charset="utf-8">
<title>Name Card</title>
</head>
<body>${content}</body>
</html>`;
// get the iframe
let iFrame = document.getElementById('print-iframe');
// set the iFrame contents and print
iFrame.contentDocument.body.innerHTML = printHtml;
iFrame.focus();
iFrame.contentWindow.print();
});
<h1>Print your name badge</h1>
<div id="name-card" class="card">
<p>Hello my name is</p>
<h2>Max Powers</h2>
</div>
<p>You will be required to wear your name badge at all times</p>
<a id="print-button" class="btn btn-primary">Print</a>
<iframe id="print-iframe" width="0" height="0"></iframe>
You can apply a CSS style to hide everything but what you want printed for media="print"
using Javascript.
You can also load the page in another window or a [hidden] <iframe>
and print that.
精彩评论