Skip to content

Instantly share code, notes, and snippets.

@andrewlimaza
Created December 19, 2016 11:31
Show Gist options
  • Star 43 You must be signed in to star a gist
  • Fork 15 You must be signed in to fork a gist
  • Save andrewlimaza/490a69417d9fe2df3f668195a7661605 to your computer and use it in GitHub Desktop.
Save andrewlimaza/490a69417d9fe2df3f668195a7661605 to your computer and use it in GitHub Desktop.
Print certain div / elements using window.print()
<script>
function printDiv(divName){
var printContents = document.getElementById(divName).innerHTML;
var originalContents = document.body.innerHTML;
document.body.innerHTML = printContents;
window.print();
document.body.innerHTML = originalContents;
}
</script>
<h1> do not print this </h1>
<div id='printMe'>
Print this only
</div>
<button onclick="printDiv('printMe')">Print only the above div</button>
@Dazaer
Copy link

Dazaer commented Sep 17, 2021

If you're using bootstrap, just add classname d-print-none to the elements you don't want to display in print

Great! Didn't even think that bootstrap would have this.

@Kam125
Copy link

Kam125 commented Feb 28, 2022

this code worked fine, but it's not working for input fields. Input field values are not printing any solution? @TranQuocViet

@pwketankulkarni
Copy link

pwketankulkarni commented Apr 20, 2022

function printPageArea(areaID){
    var printContent = document.getElementById(areaID);
    var WinPrint = window.open('', '', 'width=900,height=650');
    WinPrint.document.write(printContent.innerHTML);
    WinPrint.document.close();
    WinPrint.focus();
    WinPrint.print();
    WinPrint.close();
}

link - https://www.codexworld.com/print-page-area-javascript/

@tejas-hosamani
Copy link

tejas-hosamani commented Jul 7, 2022

My approach - Simple CSS and JS. Works on React/NextJS too.

  const handlePrint = e => {
    e.preventDefault();
    const bodyElement = document.getElementsByTagName('body')[0];

    bodyElement.classList.add('printing');
    window.print();
    bodyElement.classList.remove('printing');
  };
.printing {
  visibility:hidden;
}

.printView {
  visibility:visible;
}

.printing .printView {
  /* You can have any CSS here to make the view better on print */
  position:absolute;
  top:0;
}

What it does?

  1. Adds .printing class to the body element. With CSS, we hide all body content with visibility:hidden;
  2. At the same time, we keep CSS ready with .printing .printView to have any kind of view we want for the print area.
  3. Trigger window.print();
  4. Remove .printing class from the body element when the user cancels / prints.

Example:

<button onclick="handlePrint">
    Download PDF
</button>

<div>
    <h1>Don't print this</h1>

    <div class="printView">Print this</div>
</div>

Let me know if this helps anyone :)


Edit: If it works for you, please vote on SO - https://stackoverflow.com/a/72896189/11058652

@SudhaM-Hexaware
Copy link

Is there any ways to automate the download pdf option after window.print() ?

@dhruvroytalukdar
Copy link

@CodingCreate101 your solution worked for me thanks.

@tejas-hosamani
Copy link

@crushman1
Copy link

This is a great solution but it breaks the Dom. nothing works after. is there a way to make it open a new tab to do this ?

@Vanilagy
Copy link

Here's a proper, modern solution:

export function printElement(element: HTMLElement) {
    const body = document.body
  
    // Store current children of the body in an array
    const originalChildren: Node[] = [...body.children]
  
    // Clone the element to be printed
    const elementClone = element.cloneNode(true) as HTMLElement
  
    // Remove all current children from the body
    while (body.firstChild) {
        body.firstChild.remove()
    }
  
    // Add the cloned element to be printed
    body.append(elementClone)
  
    // Call window.print and revert the state back after printing
    window.print()
  
    // Revert the state back
    while (body.firstChild) {
        (body.firstChild as HTMLElement).remove()
    }
  
    for (const child of originalChildren) body.append(child)
}

By keeping a reference to the nodes that have been temporarily removed from the DOM, they can be added back without an issue: All listeners and references to these nodes are still valid.

@crushman1
Copy link

@Vanilagy not sure how you got this one to work but i get an error Type 'HTMLCollection' must have a '[Symbol.iterator]()' method that returns an iterator at [...body.children] and when i run the function i get element.cloneNode is not a function in the inspector console

@azeenGAN
Copy link

azeenGAN commented Mar 2, 2024

just add return false after window.print() at the end of print function and your DOM will work properly as before

All other js stopped working on DOM after print call.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment