0

0

如何使用 Nextjs 和 Puppeteer 捕获网页屏幕截图

碧海醫心

碧海醫心

发布时间:2024-11-03 20:03:02

|

459人浏览过

|

来源于dev.to

转载

如何使用 nextjs 和 puppeteer 捕获网页屏幕截图

以编程方式捕获网页屏幕截图对于生成预览、创建基于图像的报告等非常有用。在本指南中,我们将构建一个 next.js api 路由,该路由采用 url 并生成 png 屏幕截图。我们的设置使用 puppeteer 和 chrome-aws-lambda 来利用无头 chrome 浏览器,使其多功能且可用于生产。

我们将首先设置一个新的 next.js 项目,并逐步浏览代码以了解 api 如何捕获屏幕截图。

先决条件

  • 设置 next.js 应用
  • 使用 puppeteer 配置 api 路由
  • 为捕获接口创建react组件
  • puppeteer 的本地与部署配置说明

开始新的 next.js 项目

  1. 创建一个新的 next.js 应用程序:
npx create-next-app@latest capture-image-app
cd capture-image-app
  1. 安装必要的依赖项:
npm install puppeteer puppeteer-core chrome-aws-lambda busboy

第2步:创建生成屏幕截图的api路由

现在,我们将设置一个 api 端点来根据提供的 url 捕获并返回屏幕截图。

在pages/api文件夹中,创建一个名为generate-png.ts的新文件并添加以下代码:

Khroma
Khroma

AI调色盘生成工具

下载
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,以减少捆绑包大小并优化无服务器环境。快乐编码!

热门AI工具

更多
DeepSeek
DeepSeek

幻方量化公司旗下的开源大模型平台

豆包大模型
豆包大模型

字节跳动自主研发的一系列大型语言模型

WorkBuddy
WorkBuddy

腾讯云推出的AI原生桌面智能体工作台

腾讯元宝
腾讯元宝

腾讯混元平台推出的AI助手

文心一言
文心一言

文心一言是百度开发的AI聊天机器人,通过对话可以生成各种形式的内容。

讯飞写作
讯飞写作

基于讯飞星火大模型的AI写作工具,可以快速生成新闻稿件、品宣文案、工作总结、心得体会等各种文文稿

即梦AI
即梦AI

一站式AI创作平台,免费AI图片和视频生成。

ChatGPT
ChatGPT

最最强大的AI聊天机器人程序,ChatGPT不单是聊天机器人,还能进行撰写邮件、视频脚本、文案、翻译、代码等任务。

相关专题

更多
chrome什么意思
chrome什么意思

chrome是浏览器的意思,由Google开发的网络浏览器,它在2008年首次发布,并迅速成为全球最受欢迎的浏览器之一。本专题为大家提供chrome相关的文章、下载、课程内容,供大家免费下载体验。

1068

2023.08.11

chrome无法加载插件怎么办
chrome无法加载插件怎么办

chrome无法加载插件可以通过检查插件是否已正确安装、禁用和启用插件、清除插件缓存、更新浏览器和插件、检查网络连接和尝试在隐身模式下加载插件方法解决。更多关于chrome相关问题,详情请看本专题下面的文章。php中文网欢迎大家前来学习。

846

2023.11.06

lambda表达式
lambda表达式

Lambda表达式是一种匿名函数的简洁表示方式,它可以在需要函数作为参数的地方使用,并提供了一种更简洁、更灵活的编码方式,其语法为“lambda 参数列表: 表达式”,参数列表是函数的参数,可以包含一个或多个参数,用逗号分隔,表达式是函数的执行体,用于定义函数的具体操作。本专题为大家提供lambda表达式相关的文章、下载、课程内容,供大家免费下载体验。

215

2023.09.15

python lambda函数
python lambda函数

本专题整合了python lambda函数用法详解,阅读专题下面的文章了解更多详细内容。

193

2025.11.08

Python lambda详解
Python lambda详解

本专题整合了Python lambda函数相关教程,阅读下面的文章了解更多详细内容。

61

2026.01.05

硬盘接口类型介绍
硬盘接口类型介绍

硬盘接口类型有IDE、SATA、SCSI、Fibre Channel、USB、eSATA、mSATA、PCIe等等。详细介绍:1、IDE接口是一种并行接口,主要用于连接硬盘和光驱等设备,它主要有两种类型:ATA和ATAPI,IDE接口已经逐渐被SATA接口;2、SATA接口是一种串行接口,相较于IDE接口,它具有更高的传输速度、更低的功耗和更小的体积;3、SCSI接口等等。

1962

2023.10.19

PHP接口编写教程
PHP接口编写教程

本专题整合了PHP接口编写教程,阅读专题下面的文章了解更多详细内容。

658

2025.10.17

php8.4实现接口限流的教程
php8.4实现接口限流的教程

PHP8.4本身不内置限流功能,需借助Redis(令牌桶)或Swoole(漏桶)实现;文件锁因I/O瓶颈、无跨机共享、秒级精度等缺陷不适用高并发场景。本专题为大家提供相关的文章、下载、课程内容,供大家免费下载体验。

2405

2025.12.29

TypeScript类型系统进阶与大型前端项目实践
TypeScript类型系统进阶与大型前端项目实践

本专题围绕 TypeScript 在大型前端项目中的应用展开,深入讲解类型系统设计与工程化开发方法。内容包括泛型与高级类型、类型推断机制、声明文件编写、模块化结构设计以及代码规范管理。通过真实项目案例分析,帮助开发者构建类型安全、结构清晰、易维护的前端工程体系,提高团队协作效率与代码质量。

49

2026.03.13

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
快速入门Node.JS全套完整版
快速入门Node.JS全套完整版

共83课时 | 9.2万人学习

nodejs开发基础教程
nodejs开发基础教程

共15课时 | 4.6万人学习

JavaScript设计模式视频教程
JavaScript设计模式视频教程

共28课时 | 5.4万人学习

关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号