dalsnjidda's avatar

Need help with Spatie's Browsershot package

I'm using Spatie's browershot package for generating PDFs with the code sample below:

Browsershot::url($url)
->ignoreHttpsErrors()
->waitUntilNetworkIdle()
->emulateMedia('print')
->noSandbox()
->fullPage()
->pdf();

It works fine and generates the perfect PDF 99% of the time. However, there are cases where the generated PDF has a dark overlay over it. Like an opacity was added. See sample here. I've tried to reproduce this but without success. This just happens at random times with random documents. Like if I try to regenerate the PDF for this document, it's likely to come out fine without the issue.

Has anyone had this experience and solved it?

0 likes
1 reply
LaryAI's avatar
Level 58

It sounds like the issue you're experiencing with Spatie's Browsershot package might be related to a race condition where the PDF is being generated before the page has fully rendered, especially if it includes animations or transitions that could result in a dark overlay.

Here's a potential solution that you can try:

  1. Increase the wait time to ensure the page is fully loaded and all animations have completed. You can use the waitUntilNetworkIdle() method, which you're already using, but you might want to add a delay as well.

  2. If the page has animations or transitions that could cause the dark overlay, you can try to disable them via CSS when the page is being printed. You can inject custom CSS to override any transitions or animations.

Here's an updated code sample with these suggestions:

Browsershot::url($url)
    ->ignoreHttpsErrors()
    ->waitUntilNetworkIdle()
    ->emulateMedia('print')
    ->noSandbox()
    ->fullPage()
    ->addStyleTag(['content' => '* { transition: none !important; animation: none !important; }'])
    ->pdf();

In the addStyleTag method, we're injecting CSS that disables CSS transitions and animations by setting them to none. This should help ensure that the page is static when the PDF is generated.

If the issue persists, you might want to look into the specific styles or scripts on the pages that are causing the problem. It could be a particular CSS class or JavaScript function that's occasionally causing the dark overlay. If you can identify it, you could specifically target that element in your injected CSS or use JavaScript to disable it before taking the screenshot.

Remember that debugging these kinds of issues can sometimes require a bit of trial and error, so you may need to adjust your approach based on the specific content of the pages you're working with.

1 like

Please or to participate in this conversation.