在 PHP 中将 HTML 转换为 PDF 很容易。让我们更进一步,使用 PHP 和 JavaScript 将网页转换为 PDF 文件。
为此,您需要安装 Composer 和 Node。
安装完这些东西后,您需要使用 Composer 安装 Dompdf,并使用 npm(Node 包管理器)安装 Puppeteer:
composer require dompdf/dompdf npm install puppeteer
创建 HTML 文件(示例:index.html):
Webpage to Pdf
创建 PHP 文件(示例:web-pdf.php):
getMessage(); } } else { echo "No URL provided."; } function convertHTML($content) { $dompdf = new Dompdf(); $dompdf->loadHtml($content); // Setup the paper size and orientation $dompdf->setPaper('A4', 'landscape'); // Render the HTML as PDF $dompdf->render(); ob_end_clean(); // Output the generated PDF $dompdf->stream(); } ?>
最后,创建一个 JavaScript 文件以使用 Puppeteer(示例:download.js):
const puppeteer = require('puppeteer'); // Get URL from command-line arguments const url = process.argv[2]; (async () => { try { const browser = await puppeteer.launch(); const page = await browser.newPage(); await page.goto(url); // Use the URL passed from PHP await page.waitForSelector('main', { timeout: 10000 }); // Adjust selector and timeout as needed const content = await page.content(); console.log(content); await browser.close(); } catch (error) { console.error('Error:', error); } })();
注意:如果内容不符合您的预期,请删除十秒超时或更改元素(主要)。
给你!就像这样,你就有了一个网页到PDF转换器。
祝大家编码愉快!
免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。
Copyright© 2022 湘ICP备2022001581号-3