tibin mathew
tibin mathew

Reputation: 2084

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 portion of a page?

If anyone has an idea, please share it with me.

Upvotes: 6

Views: 6763

Answers (4)

Adonis Gaitatzis
Adonis Gaitatzis

Reputation: 3739

It can be done using JavaScript and iframes:

  1. Dump the innerHTML of the container into the iFrame (plus any print-specific CSS
  2. 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>

Upvotes: 2

Quentin
Quentin

Reputation: 944441

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.

Upvotes: 1

marcgg
marcgg

Reputation: 66515

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.

Upvotes: 9

strager
strager

Reputation: 90062

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.

Upvotes: 0

Related Questions