标签搜索

Linux系统centos通过php、thinkphp5.1框架将HTML网页转为图片方法

basil
2022-05-10 / 215 阅读

思路

使用PHP调用chrome浏览器来完成

centos安装chrome浏览器

添加源vim /etc/yum.repos.d/google-chrome.repo

[google-chrome]
name=google-chrome
baseurl=https://dl.google.com/linux/chrome/rpm/stable/x86_64
enabled=1
gpgcheck=1
gpgkey=https://dl.google.com/linux/linux_signing_key.pub

执行安装命令

yum -y install google-chrome-stable

如果安装失败则执行

yum -y install google-chrome-stable

通过chrome-php插件以及chrome的headless模式将HTML转为图片

安装chrome-php插件

composer require chrome-php/chrome

demo

$browserFactory = new BrowserFactory(Env::get('chrome.bin_path', '/opt/google/chrome/chrome'));
        $browserFactory->setOptions([
            'userAgent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.4951.41 Safari/537.36 Edg/101.0.1210.32',
            'windowSize' => [1920, 1000],
        ]);
        $browser = $browserFactory->createBrowser();
        try {
            $page = $browser->createPage();
            $url = Env::get('webpage.customer_contacts_relation_graph_url') . "?company_id=$companyId";
            $page->navigate($url)->waitForNavigation(Page::NETWORK_IDLE, 60000);
            $saveFilePath = $this->getSavePath($companyId);
            $page->screenshot([
                'captureBeyondViewport' => true,
                'clip' => $page->getFullPageClip(),
                'format' => 'jpeg', // default to 'png' - possible values: 'png', 'jpeg',
                'quality' => 100
            ])->saveToFile($saveFilePath);
            return $saveFilePath;
        }catch (\Exception $e){
            $browser->close();
            throw $e;
        } finally {
            $browser->close();
        }
0