如何使用 Nextjs 和 Puppeteer 捕获网页屏幕截图
本篇文章向大家介绍《如何使用 Nextjs 和 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,以减少捆绑包大小并优化无服务器环境。快乐编码!
到这里,我们也就讲完了《如何使用 Nextjs 和 Puppeteer 捕获网页屏幕截图》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于的知识点!
如何获取ng-zorro菜单中被点击项的特定信息?
- 上一篇
- 如何获取ng-zorro菜单中被点击项的特定信息?
- 下一篇
- MySQL 删除数据时何时会走联合索引?
-
- 文章 · 前端 | 3小时前 |
- CSS网格嵌套错位怎么解决?grid-template-areas轻松管理
- 486浏览 收藏
-
- 文章 · 前端 | 3小时前 |
- CSSFlexbox布局教程与实战技巧
- 365浏览 收藏
-
- 文章 · 前端 | 3小时前 |
- Firebase异步数据获取与Promise应用技巧
- 408浏览 收藏
-
- 文章 · 前端 | 3小时前 |
- CSS表格间距太大怎么调?调整border-spacing属性
- 229浏览 收藏
-
- 文章 · 前端 | 3小时前 | HTML编辑器
- HTML编辑器括号自动匹配技巧与错误预防方法
- 119浏览 收藏
-
- 文章 · 前端 | 3小时前 |
- React实现维基引用链接技巧
- 466浏览 收藏
-
- 文章 · 前端 | 3小时前 |
- WebComponents自定义元素开发教程
- 382浏览 收藏
-
- 文章 · 前端 | 3小时前 |
- ServiceWorker预加载取消优化技巧
- 304浏览 收藏
-
- 文章 · 前端 | 3小时前 | java 编程
- RAF是什么?requestAnimationFrame使用解析
- 462浏览 收藏
-
- 文章 · 前端 | 3小时前 |
- async函数返回值类型怎么选?
- 351浏览 收藏
-
- 文章 · 前端 | 3小时前 |
- 模块联邦揭秘:微前端原理全解析
- 256浏览 收藏
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 543次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 516次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 500次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 485次学习
-
- ChatExcel酷表
- ChatExcel酷表是由北京大学团队打造的Excel聊天机器人,用自然语言操控表格,简化数据处理,告别繁琐操作,提升工作效率!适用于学生、上班族及政府人员。
- 3356次使用
-
- Any绘本
- 探索Any绘本(anypicturebook.com/zh),一款开源免费的AI绘本创作工具,基于Google Gemini与Flux AI模型,让您轻松创作个性化绘本。适用于家庭、教育、创作等多种场景,零门槛,高自由度,技术透明,本地可控。
- 3567次使用
-
- 可赞AI
- 可赞AI,AI驱动的办公可视化智能工具,助您轻松实现文本与可视化元素高效转化。无论是智能文档生成、多格式文本解析,还是一键生成专业图表、脑图、知识卡片,可赞AI都能让信息处理更清晰高效。覆盖数据汇报、会议纪要、内容营销等全场景,大幅提升办公效率,降低专业门槛,是您提升工作效率的得力助手。
- 3598次使用
-
- 星月写作
- 星月写作是国内首款聚焦中文网络小说创作的AI辅助工具,解决网文作者从构思到变现的全流程痛点。AI扫榜、专属模板、全链路适配,助力新人快速上手,资深作者效率倍增。
- 4723次使用
-
- MagicLight
- MagicLight.ai是全球首款叙事驱动型AI动画视频创作平台,专注于解决从故事想法到完整动画的全流程痛点。它通过自研AI模型,保障角色、风格、场景高度一致性,让零动画经验者也能高效产出专业级叙事内容。广泛适用于独立创作者、动画工作室、教育机构及企业营销,助您轻松实现创意落地与商业化。
- 3972次使用
-
- JavaScript函数定义及示例详解
- 2025-05-11 502浏览
-
- 优化用户界面体验的秘密武器:CSS开发项目经验大揭秘
- 2023-11-03 501浏览
-
- 使用微信小程序实现图片轮播特效
- 2023-11-21 501浏览
-
- 解析sessionStorage的存储能力与限制
- 2024-01-11 501浏览
-
- 探索冒泡活动对于团队合作的推动力
- 2024-01-13 501浏览

