assisted-mindfulness / browsershot
使用无头Chrome将网页转换为图像或PDF
Requires
- php: ^8.0
- spatie/image: ^2.2
- spatie/phpunit-snapshot-assertions: ^4.0
- spatie/temporary-directory: ^2.1
- symfony/process: ^6.0
Requires (Dev)
- phpunit/phpunit: ^9.5
This package is auto-updated.
Last update: 2024-09-18 12:49:22 UTC
README
该包可以将网页转换为图像或PDF。转换在屏幕背后由Google Chrome完成。此包已在MacOS和Ubuntu上进行了测试。如果您使用其他操作系统,效果可能会有所不同。系统上应安装Chrome。
在通过Forge配置的Ubuntu服务器上,您可以像这样安装最新稳定版本的Chrome
sudo wget -q -O - https://dl-ssl.google.com/linux/linux_signing_key.pub | sudo apt-key add - sudo sh -c 'echo "deb http://dl.google.com/linux/chrome/deb/ stable main" >> /etc/apt/sources.list.d/google.list' sudo apt-get update sudo apt-get -f install sudo apt-get install google-chrome-stable
此外,如有必要,您还需要安装额外的资源,例如用于显示表情符号的字体
sudo apt-get install fonts-noto-color-emoji
安装
此包可以通过Composer安装。
composer require assisted-mindfulness/browsershot
使用方法
在所有示例中,假设您已在文件顶部导入了此命名空间
use AssistedMindfulness\Browsershot\Browsershot;
这是创建网页图像的最简单方法
Browsershot::url('https://example.com')->save($pathToImage);
Browsershot会自动猜测Google Chrome的位置。如果您的系统上找不到Chrome,您可以手动设置其位置
Browsershot::url('https://example.com') ->setChromePath($pathToChrome) ->save($pathToImage);
默认情况下,截图将是png
格式,其大小将与您桌面使用的分辨率相匹配。想要另一个截图大小?没问题!
Browsershot::url('https://example.com') ->windowSize(640, 480) ->save($pathToImage);
您还可以独立于窗口大小设置输出图像的大小。以下是如何将分辨率为1920x1080的截图调整大小,以便适应200x200。
Browsershot::url('https://example.com') ->windowSize(1920, 1080) ->fit(Manipulations::FIT_CONTAIN, 200, 200) ->save($pathToImage);
您还可以通过传递设备缩放因子值为2或3来以更高的像素密度捕获网页。这模仿了网页在视网膜/xhdpi显示屏上的显示方式。
Browsershot::url('https://example.com') ->deviceScaleFactor(2) ->save($pathToImage);
实际上,您可以使用spatie/image提供的所有方法。以下是一个创建灰度图像的示例
Browsershot::url('https://example.com') ->windowSize(640, 480) ->greyscale() ->save($pathToImage);
如果您出于某种原因想要设置在截图时Google Chrome应使用的用户代理,您可以这样做
Browsershot::url('https://example.com') ->userAgent('My Special Snowflake Browser 1.0') ->save($pathToImage);
Browsershot的默认超时设置为60秒。当然,您可以修改此超时
Browsershot::url('https://example.com') ->timeout(120) ->save($pathToImage);
如果传递给save
方法的路径包含pdf
扩展名,Browsershot将保存PDF文件。
// a pdf will be saved Browsershot::url('https://example.com')->save('example.pdf');
或者,您可以明确使用savePdf
方法
Browsershot::url('https://example.com')->savePdf('example.pdf');
Browsershot还可以在JavaScript执行后获取HTML页面的主体
Browsershot::url('https://example.com')->bodyHtml(); // returns the html of the body
您还可以使用任意的HTML输入,只需将url
方法替换为html
Browsershot::html('<h1>Hello world!!</h1>')->save('example.pdf');
许可证
MIT许可证(MIT)。请参阅许可证文件获取更多信息。
这是spatie/browsershot项目的分支,它不需要在您的Web服务器上安装Node和Puppeteer。