Easy printing with the afterprint event

Resources

1
2
3
4
5
6
7
8
9
10
11
12
13
/* set print page to landscape */
@media print{
@page {
size: landscape
}
}

/* class to size page to landscape a4 */
.print {
width: 10in;
height: 7.7in;
margin: 0 auto;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// sleep function
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}

// print variable is a true/false toggle based on a button click

// afterprint event toggles page back to normal
window.addEventListener("afterprint", (event) => {
print = false
})

// print button click event
async function printPreview() {
print = !print
if (print) {
await sleep(600)
window.print()
}
}