DEV Community

Kristof Gilicze
Kristof Gilicze

Posted on

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

Top comments (0)