如何使用 Next.js 和 Puppeteer 擷取網頁螢幕截圖
以程式擷取網頁螢幕截圖對於產生預覽、建立基於影像的報告等非常有用。在本指南中,我們將建立一個 Next.js API 路由,該路由採用 URL 並產生 PNG 螢幕截圖。我們的設定使用 Puppeteer 和 chrome-aws-lambda 來利用無頭 Chrome 瀏覽器,使其多功能且可用於生產。
我們將首先設定一個新的 Next.js 項目,並逐步瀏覽程式碼以了解 API 如何擷取螢幕截圖。
先決條件
- 設定 Next.js 應用程式
- 使用 Puppeteer 設定 API 路由
- 為捕獲介面建立React元件
- Puppeteer 本機設定與部署設定的說明
開始新的 Next.js 專案
- 建立一個新的 Next.js 應用程式:
npx create-next-app@latest capture-image-app cd capture-image-app
- 安裝必要的依賴項:
npm install puppeteer puppeteer-core chrome-aws-lambda busboy
第2步:建立產生螢幕截圖的API路由
現在,我們將設定一個 API 端點來根據提供的 URL 擷取並傳回螢幕截圖。
在pages/api資料夾中,建立一個名為generate-png.ts的新檔案並加入以下程式碼:
import { NextApiRequest, NextApiResponse } from "next"; import busboy, { Busboy } from "busboy"; // Use busboy for multipart parsing import chromium from "chrome-aws-lambda"; import puppeteerCore from "puppeteer-core"; // Import puppeteer-core directly import puppeteer from "puppeteer"; // Import puppeteer directly // Conditional import for Puppeteer based on the environment const puppeteerModule = process.env.NODE_ENV === "production" ? puppeteerCore : puppeteer; export const config = { api: { bodyParser: false, // Disable default body parsing to handle raw binary data (Blob) }, }; const delay = (ms: number): Promise<void> => new Promise((resolve) => setTimeout(resolve, ms)); export default async function handler( req: NextApiRequest, res: NextApiResponse ): Promise<void> { try { if (req.method === "POST") { const bb: Busboy = busboy({ headers: req.headers }); let width: number = 1920; // Default width let height: number = 0; // Default height let delayTime: number = 6000; const buffers: Buffer[] = []; bb.on("file", (_name: string, file: NodeJS.ReadableStream) => { file.on("data", (data: Buffer) => buffers.push(data)); }); bb.on("field", (name: string, value: string) => { if (name === "width") width = parseInt(value, 10) || 1920; if (name === "height") height = parseInt(value, 10) || 0; if (name === "delay") delayTime = parseInt(value, 10) || 6000; }); bb.on("finish", async () => { const blobBuffer: Buffer = Buffer.concat(buffers); const htmlContent: string = blobBuffer.toString("utf-8"); const browser = await puppeteerModule.launch({ args: ["--start-maximized"], executablePath: process.env.NODE_ENV === "production" ? await chromium.executablePath || "/usr/bin/chromium-browser" : undefined, // No custom executable path needed for local headless: true, }); const page = await browser.newPage(); // Load the HTML content directly await page.setContent(htmlContent, { waitUntil: "networkidle0" }); //@ts-expect-error todo const bodyHeight = await page.evaluate(() => { return document.body.scrollHeight; // Get the full scrollable height of the body }); await page.setViewport({ width: Number(width), height: height || bodyHeight, // Use the provided height or fallback to the full body height deviceScaleFactor: 2, }); await delay(delayTime); const screenshotBuffer = await page.screenshot({ fullPage: !height, type: "png", omitBackground: false, }); await browser.close(); res.setHeader("Content-Type", "image/png"); res.setHeader( "Content-Disposition", "attachment; filename=screenshot.png" ); res.status(200).end(screenshotBuffer); }); req.pipe(bb); // Pipe the request stream to busboy } else { res.setHeader("Allow", ["POST"]); res.status(405).end(`Method ${req.method} Not Allowed`); } } catch (error) { console.error("ERROR", error); res.status(500).end("Internal Server Error"); } }
*說明:為本地環境和生產環境選擇 Puppeteer
*
在此程式碼中,我們為 puppeteer 設定了動態導入:
本地開發:如果 NODE_ENV 不是生產環境,它會使用 puppeteer,它設定起來更簡單,並且不需要 chrome-aws-lambda。
生產:對於無伺服器部署,環境將檢測 NODE_ENV 作為生產並載入 puppeteer-core 以及 chrome-aws-lambda,這使得它可以在 AWS Lambda 和其他類似環境中工作。在此設定中,chrome-aws-lambda 提供正確的 Chromium 路徑,確保與無伺服器供應商的相容性。
第 3 步:為 UI 建立一個簡單的 React 元件
在這裡,我們將建立一個簡單的表單,讓使用者輸入網頁擷取的值。此表單將觸發生成功能以捕獲並下載 PDF 格式的螢幕截圖。
import { useState } from "react"; export default function ScreenCaptureComponent() { const [isProcessing, setProcessing] = useState(false); const [width, setWidth] = useState<string>("1920"); const [height, setHeight] = useState<string>("1000"); const [delay, setDelay] = useState<string>("6000"); // Function to clone HTML and prepare for capture function takeScreenshot() { const clonedElement = document.body.cloneNode(true) as HTMLElement; const blob = new Blob([clonedElement.outerHTML], { type: "text/html" }); return blob; } // Function to capture screenshot by sending cloned HTML to API async function generateCapture() { setProcessing(true); const htmlBlob = takeScreenshot(); if (!htmlBlob) { setProcessing(false); return; } try { const formData = new FormData(); formData.append("file", htmlBlob); formData.append("width", width); formData.append("height", height); formData.append("delay", delay); const response = await fetch("/api/generate-png", { method: "POST", body: formData, }); if (!response.ok) throw new Error("Capture failed"); const blob = await response.blob(); const downloadUrl = URL.createObjectURL(blob); const link = document.createElement("a"); link.href = downloadUrl; link.download = "capture.png"; link.click(); URL.revokeObjectURL(downloadUrl); } catch (error) { console.error("Failed to capture screenshot", error); } finally { setProcessing(false); } } return ( <div style={{ maxWidth: "400px", margin: "50px auto", padding: "24px", backgroundColor: "white", borderRadius: "8px", width: "100%", boxShadow: "0 4px 6px rgba(0, 0, 0, 0.1)", }} > <h2 style={{ fontSize: "24px", fontWeight: "600", textAlign: "center", marginBottom: "16px", }} > Webpage Screenshot Capture </h2> <form onSubmit={(e) => { e.preventDefault(); generateCapture(); }} style={{ display: "flex", flexDirection: "column", alignItems: "center", marginBottom: "16px", }} > <label style={{ marginBottom: "8px", fontWeight: "500" }} htmlFor="width" > Width (px) </label> <select id="width" value={width} onChange={(e) => setWidth(e.target.value)} style={{ width: "100%", padding: "8px", marginBottom: "16px", borderRadius: "4px", border: "1px solid #ccc", outline: "none", }} > <option value="1920">1920 (Full HD)</option> <option value="1366">1366 (Laptop)</option> <option value="1280">1280 (Desktop)</option> <option value="1024">1024 (Tablet Landscape)</option> <option value="768">768 (Tablet Portrait)</option> <option value="375">375 (Mobile)</option> </select> <label style={{ marginBottom: "8px", fontWeight: "500" }} htmlFor="height" > Height (px) </label> <input type="number" id="height" value={height} onChange={(e) => setHeight(e.target.value)} required style={{ width: "100%", padding: "8px", marginBottom: "16px", borderRadius: "4px", border: "1px solid #ccc", outline: "none", }} /> <label style={{ marginBottom: "8px", fontWeight: "500" }} htmlFor="delay" > Delay (ms) </label> <input type="number" id="delay" value={delay} onChange={(e) => setDelay(e.target.value)} required style={{ width: "100%", padding: "8px", marginBottom: "16px", borderRadius: "4px", border: "1px solid #ccc", outline: "none", }} /> <button type="submit" disabled={isProcessing} style={{ padding: "8px 16px", color: "white", borderRadius: "4px", transition: "background-color 0.3s", backgroundColor: isProcessing ? "#b0bec5" : "#2196F3", cursor: isProcessing ? "not-allowed" : "pointer", }} > {isProcessing ? "Capturing..." : "Capture Screenshot"} </button> </form> {/* Example HTML Element to Capture */} <div id="capture-area" style={{ display: "none" }}> <h3 style={{ fontSize: "20px", fontWeight: "600", }} > Content to Capture </h3> <p>This is an example of the HTML content that will be captured.</p> </div> </div> ); }
結論
本教學涵蓋在 Next.js 中設定網頁擷取工具、使用 Puppeteer 處理螢幕截圖以及建立互動式前端元件。請記住在本地使用 puppeteer 並在生產中切換到 puppeteer-core,以減少捆綁包大小並優化無伺服器環境。快樂編碼!
以上是如何使用 Next.js 和 Puppeteer 擷取網頁螢幕截圖的詳細內容。更多資訊請關注PHP中文網其他相關文章!

熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

不同JavaScript引擎在解析和執行JavaScript代碼時,效果會有所不同,因為每個引擎的實現原理和優化策略各有差異。 1.詞法分析:將源碼轉換為詞法單元。 2.語法分析:生成抽象語法樹。 3.優化和編譯:通過JIT編譯器生成機器碼。 4.執行:運行機器碼。 V8引擎通過即時編譯和隱藏類優化,SpiderMonkey使用類型推斷系統,導致在相同代碼上的性能表現不同。

Python更適合初學者,學習曲線平緩,語法簡潔;JavaScript適合前端開發,學習曲線較陡,語法靈活。 1.Python語法直觀,適用於數據科學和後端開發。 2.JavaScript靈活,廣泛用於前端和服務器端編程。

從C/C 轉向JavaScript需要適應動態類型、垃圾回收和異步編程等特點。 1)C/C 是靜態類型語言,需手動管理內存,而JavaScript是動態類型,垃圾回收自動處理。 2)C/C 需編譯成機器碼,JavaScript則為解釋型語言。 3)JavaScript引入閉包、原型鍊和Promise等概念,增強了靈活性和異步編程能力。

JavaScript在Web開發中的主要用途包括客戶端交互、表單驗證和異步通信。 1)通過DOM操作實現動態內容更新和用戶交互;2)在用戶提交數據前進行客戶端驗證,提高用戶體驗;3)通過AJAX技術實現與服務器的無刷新通信。

JavaScript在現實世界中的應用包括前端和後端開發。 1)通過構建TODO列表應用展示前端應用,涉及DOM操作和事件處理。 2)通過Node.js和Express構建RESTfulAPI展示後端應用。

理解JavaScript引擎內部工作原理對開發者重要,因為它能幫助編寫更高效的代碼並理解性能瓶頸和優化策略。 1)引擎的工作流程包括解析、編譯和執行三個階段;2)執行過程中,引擎會進行動態優化,如內聯緩存和隱藏類;3)最佳實踐包括避免全局變量、優化循環、使用const和let,以及避免過度使用閉包。

Python和JavaScript在社區、庫和資源方面的對比各有優劣。 1)Python社區友好,適合初學者,但前端開發資源不如JavaScript豐富。 2)Python在數據科學和機器學習庫方面強大,JavaScript則在前端開發庫和框架上更勝一籌。 3)兩者的學習資源都豐富,但Python適合從官方文檔開始,JavaScript則以MDNWebDocs為佳。選擇應基於項目需求和個人興趣。

Python和JavaScript在開發環境上的選擇都很重要。 1)Python的開發環境包括PyCharm、JupyterNotebook和Anaconda,適合數據科學和快速原型開發。 2)JavaScript的開發環境包括Node.js、VSCode和Webpack,適用於前端和後端開發。根據項目需求選擇合適的工具可以提高開發效率和項目成功率。
