HTML Partial Print

Use JavaScript and iframes to print only part of a website.

by backupbrain

HTML

<script src="https://code.jquery.com/jquery-3.4.1.slim.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.css">
<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>

JavaScript

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
  console.log(iFrame);
  console.log(iFrame.contentDocument);
  iFrame.contentDocument.body.innerHTML = printHtml;
  iFrame.focus();
	iFrame.contentWindow.print();
  
});