I use this code snippet in the dev tools to print a small portion of a webpage. It copies every CSS stylesheet in the head of the page which helps render the printed content as close as possible to how it appears in the browser.
function printElement(element) {
const newWin = window.open('', 'Print-Window');
// Copy all stylesheets
let stylesheets = '';
for (var i = 0; i < document.styleSheets.length; i++) {
if (document.styleSheets[i].href) {
stylesheets += '<link rel="stylesheet" href="' + document.styleSheets[i].href + '" type="text/css">';
}
}
newWin.document.open();
newWin.document.write('<html><head>' + stylesheets + '</head><body>' + element.innerHTML + '</body></html>');
newWin.document.close();
setTimeout(function () {
newWin.print();
// newWin.close(); // close tab after printing
}, 250); // Delay to ensure styles are applied
}
// Usage
// printElement(document.getElementById('myElementId'));
// printElement(document.querySelector('#myElementId'));
//
// If you already have an element selected in the dev tools:
// printElement($0);
How to use
- Open the dev tools
- Copy & paste the function above into the Console
- Select the div you want to print
- Then run
printElement($0)
Examples
As shown in the screenshot above, I use this often with ChatGPT responses when I want to print just one answer that might be too long to fit on a screenshot. This is actually helpful if you are creating GPTs, where you need to upload a PDF from one of the responses from GPT.
For example, this is how it looks originaly:
This is how it looks when running printElement($0);
on that div:
And this is what it looks if you close the print dialog:
Conclusion
Although this simple function isn't 100% bullet proof, it helps printing certain parts of a website while attempting to keep the styles as best as it can.
Top comments (0)