Skip to content

Instantly share code, notes, and snippets.

@dexit
Forked from Noah-Martinez/Print-element-as-PDF.js
Created June 12, 2025 09:48
Show Gist options
  • Save dexit/b6268ef3270704cbbc6a4c181f13ec5b to your computer and use it in GitHub Desktop.
Save dexit/b6268ef3270704cbbc6a4c181f13ec5b to your computer and use it in GitHub Desktop.
Print element as PDF
// ==UserScript==
// @name Print element as PDF
// @namespace http://tampermonkey.net/
// @version 2025-06-12
// @description Adds a function to Window to print a html element as a PDF
// @author Noah Martinez
// @match *://*/*
// @icon https://www.google.com/s2/favicons?sz=64&domain=acrobat.adobe.com
// @grant none
// ==/UserScript==
(function() {
'use strict';
/**
* Opens a new window containing only the given element,
* then invokes window.print() so you can save it as PDF.
* @param {HTMLElement} el
*/
window.printElement = function(el) {
if (!(el instanceof HTMLElement)) {
console.error('printElement: argument is not an HTMLElement');
return;
}
// Clone the element so we don't disturb the original page
const cloned = el.cloneNode(true);
const w = window.open(undefined, undefined, { popup: true });
w.document.write(`
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Print Preview</title>
<style>
/* reset margins so element uses full page width */
@page { margin: 1cm; }
body { margin: 0; padding: 0; }
</style>
</head>
<body></body>
</html>`);
w.document.close();
// Alle <link rel="stylesheet"> und <style> aus dem Original-Head kopieren
const originals = Array.from(document.querySelectorAll('link[rel="stylesheet"], style'));
originals.forEach(node => {
w.document.head.appendChild(node.cloneNode(true));
});
w.document.body.appendChild(cloned);
// give it a moment to render
setTimeout(() => {
w.focus();
w.print();
// optional: auto‐close after printing
// w.close();
}, 250);
};
console.log('🖨️ printElement(el) helper installed. In DevTools Console, select an element and call: printElement($0)');
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment