1

For a project we implemented a custom button to print to current page. By using the event handlers we do further adjustment to the page, like changing the colors, displaying certain areas and all in all to make it more printable.

 window.addEventListener('beforeprint', handleBeforeprint);
 window.addEventListener('afterprint', handleAfterprint);

The implementation is working for only those cases, when using the print feature from the browser or by triggering the browser print by the keyboard CMD + P. Whenever I trigger the print using window.print(), the events are not triggered.

DWOME
  • 79
  • 8

1 Answers1

1

I have faced a similar issue before, it turns out that it was a bug with chrome and firefox both. I will try to find the link and attach it to this answer. you can easily trigger a handleBeforeprint function you might face a problem in handleAfterprint.

I have created a function like so for my use case it just worked fine.

const print = () =>{
    handleBeforeprint();
    window.print();
    handleAfterprint();
}

I have another way to do this but that is fairly complex to implement(I have done that for another project) if it is something really important for your use case then you can use something like HTMLtoCanvas. let me know if you need more details on this approach.

Side hack:

window.printv2 = () => {
    handleBeforeprint();
    window.print();
    handleAfterprint();
}

now you can call window.printv2() from anywhere ;)

Kartik Malik
  • 460
  • 4
  • 11