DEV Community

Kristof Gilicze
Kristof Gilicze

Posted on

3 2

Print a page with JS in the background

Print a given URL

async function printURL(url: string): Promise<void> {
    const iframe: HTMLIFrameElement;

    iframe = await document.createElement('iframe');
    iframe.setAttribute("src", url);
    await document.body.appendChild(iframe);

    iframe.contentWindow.print();
}
Enter fullscreen mode Exit fullscreen mode

Print an existing HTML node

function printHTMLElement(element: HTMLElement) {

    const cloned = element.cloneNode(true)
    let section = document.getElementById("print")

    if (!section) {
        section = document.createElement("div")
        section.id = "print"
        document.body.appendChild(section)
    }

    section.innerHTML = `
        <style>
           @page {
                size: landscape;
                margin: 0mm;
            }

            @media screen {
              #print {
                display: none;
               }
            }

            @media print {

                body * {
                    visibility:hidden;
                }
                #print, #print * {
                    visibility:visible;
                }
                #print {
                    position:absolute;
                    left:0;
                    top:0;
                    padding: 1.5rem;
                }

                .hidden-on-print {
                    visibility:hidden;
                }
            }
        </style>
    `;
    section.appendChild(cloned);
    window.print();
}
Enter fullscreen mode Exit fullscreen mode

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (0)

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay