{"id":2059,"date":"2024-11-10T16:27:03","date_gmt":"2024-11-10T08:27:03","guid":{"rendered":"https:\/\/fwq.ai\/blog\/2059\/"},"modified":"2024-11-10T16:27:03","modified_gmt":"2024-11-10T08:27:03","slug":"%e5%a6%82%e4%bd%95%e4%bd%bf%e7%94%a8-nextjs-%e5%92%8c-puppeteer-%e6%8d%95%e8%8e%b7%e7%bd%91%e9%a1%b5%e5%b1%8f%e5%b9%95%e6%88%aa%e5%9b%be","status":"publish","type":"post","link":"https:\/\/fwq.ai\/blog\/2059\/","title":{"rendered":"\u5982\u4f55\u4f7f\u7528 Nextjs \u548c Puppeteer \u6355\u83b7\u7f51\u9875\u5c4f\u5e55\u622a\u56fe"},"content":{"rendered":"<p><img decoding=\"async\" src=\"https:\/\/img.php.cn\/upload\/article\/001\/246\/273\/173063538441043.jpg\" class=\"aligncenter\" title=\"\u5982\u4f55\u4f7f\u7528 Nextjs \u548c Puppeteer \u6355\u83b7\u7f51\u9875\u5c4f\u5e55\u622a\u56fe\u63d2\u56fe\" alt=\"\u5982\u4f55\u4f7f\u7528 Nextjs \u548c Puppeteer \u6355\u83b7\u7f51\u9875\u5c4f\u5e55\u622a\u56fe\u63d2\u56fe\" \/><\/p>\n<p>\u4ee5\u7f16\u7a0b\u65b9\u5f0f\u6355\u83b7\u7f51\u9875\u5c4f\u5e55\u622a\u56fe\u5bf9\u4e8e\u751f\u6210\u9884\u89c8\u3001\u521b\u5efa\u57fa\u4e8e\u56fe\u50cf\u7684\u62a5\u544a\u7b49\u975e\u5e38\u6709\u7528\u3002\u5728\u672c\u6307\u5357\u4e2d\uff0c\u6211\u4eec\u5c06\u6784\u5efa\u4e00\u4e2a next.js api \u8def\u7531\uff0c\u8be5\u8def\u7531\u91c7\u7528 url \u5e76\u751f\u6210 png \u5c4f\u5e55\u622a\u56fe\u3002\u6211\u4eec\u7684\u8bbe\u7f6e\u4f7f\u7528 puppeteer \u548c chrome-aws-lambda \u6765\u5229\u7528\u65e0\u5934 chrome \u6d4f\u89c8\u5668\uff0c\u4f7f\u5176\u591a\u529f\u80fd\u4e14\u53ef\u7528\u4e8e\u751f\u4ea7\u3002<\/p>\n<p>\u6211\u4eec\u5c06\u9996\u5148\u8bbe\u7f6e\u4e00\u4e2a\u65b0\u7684 next.js \u9879\u76ee\uff0c\u5e76\u9010\u6b65\u6d4f\u89c8\u4ee3\u7801\u4ee5\u4e86\u89e3 api \u5982\u4f55\u6355\u83b7\u5c4f\u5e55\u622a\u56fe\u3002<\/p>\n<p>\u5148\u51b3\u6761\u4ef6<\/p>\n<ul>\n<li>\u8bbe\u7f6e next.js \u5e94\u7528<\/li>\n<li>\u4f7f\u7528 puppeteer \u914d\u7f6e api \u8def\u7531<\/li>\n<li>\u4e3a\u6355\u83b7\u63a5\u53e3\u521b\u5efareact\u7ec4\u4ef6<\/li>\n<li>puppeteer \u7684\u672c\u5730\u4e0e\u90e8\u7f72\u914d\u7f6e\u8bf4\u660e<\/li>\n<\/ul>\n<p><strong>\u5f00\u59cb\u65b0\u7684 next.js \u9879\u76ee<\/strong><\/p>\n<ol>\n<li>\u521b\u5efa\u4e00\u4e2a\u65b0\u7684 next.js \u5e94\u7528\u7a0b\u5e8f\uff1a <\/li>\n<\/ol>\n<pre>npx create-next-app@latest capture-image-app\ncd capture-image-app\n<\/pre>\n<p>  \u767b\u5f55\u540e\u590d\u5236   <\/p>\n<ol>\n<li>\u5b89\u88c5\u5fc5\u8981\u7684\u4f9d\u8d56\u9879\uff1a <\/li>\n<\/ol>\n<pre>npm install puppeteer puppeteer-core chrome-aws-lambda busboy\n<\/pre>\n<p>  \u767b\u5f55\u540e\u590d\u5236   <\/p>\n<p><strong>\u7b2c2\u6b65\uff1a\u521b\u5efa\u751f\u6210\u5c4f\u5e55\u622a\u56fe\u7684api\u8def\u7531<\/strong><\/p>\n<p>\u73b0\u5728\uff0c\u6211\u4eec\u5c06\u8bbe\u7f6e\u4e00\u4e2a api \u7aef\u70b9\u6765\u6839\u636e\u63d0\u4f9b\u7684 url \u6355\u83b7\u5e76\u8fd4\u56de\u5c4f\u5e55\u622a\u56fe\u3002<\/p>\n<p>\u5728pages\/api\u6587\u4ef6\u5939\u4e2d\uff0c\u521b\u5efa\u4e00\u4e2a\u540d\u4e3agenerate-png.ts\u7684\u65b0\u6587\u4ef6\u5e76\u6dfb\u52a0\u4ee5\u4e0b\u4ee3\u7801\uff1a<\/p>\n<pre>import { nextapirequest, nextapiresponse } from \"next\";\nimport busboy, { busboy } from \"busboy\"; \/\/ use busboy for multipart parsing\nimport chromium from \"chrome-aws-lambda\";\nimport puppeteercore from \"puppeteer-core\"; \/\/ import puppeteer-core directly\nimport puppeteer from \"puppeteer\"; \/\/ import puppeteer directly\n\n\/\/ conditional import for puppeteer based on the environment\nconst puppeteermodule = process.env.node_env === \"production\" ? puppeteercore : puppeteer;\n\nexport const config = {\n  api: {\n    bodyparser: false, \/\/ disable default body parsing to handle raw binary data (blob)\n  },\n};\n\nconst delay = (ms: number): promise&lt;void&gt; =&gt; new promise((resolve) =&gt; settimeout(resolve, ms));\n\nexport default async function handler(\n  req: nextapirequest,\n  res: nextapiresponse\n): promise&lt;void&gt; {\n  try {\n    if (req.method === \"post\") {\n      const bb: busboy = busboy({ headers: req.headers });\n      let width: number = 1920; \/\/ default width\n      let height: number = 0; \/\/ default height\n      let delaytime: number = 6000;\n      const buffers: buffer[] = [];\n\n      bb.on(\"file\", (_name: string, file: nodejs.readablestream) =&gt; {\n        file.on(\"data\", (data: buffer) =&gt; buffers.push(data));\n      });\n\n      bb.on(\"field\", (name: string, value: string) =&gt; {\n        if (name === \"width\") width = parseint(value, 10) || 1920;\n        if (name === \"height\") height = parseint(value, 10) || 0;\n        if (name === \"delay\") delaytime = parseint(value, 10) || 6000;\n      });\n\n      bb.on(\"finish\", async () =&gt; {\n        const blobbuffer: buffer = buffer.concat(buffers);\n        const htmlcontent: string = blobbuffer.tostring(\"utf-8\");\n\n        const browser = await puppeteermodule.launch({\n          args: [\"--start-maximized\"],\n          executablepath: process.env.node_env === \"production\"\n            ? await chromium.executablepath || \"\/usr\/bin\/chromium-browser\"\n            : undefined,  \/\/ no custom executable path needed for local\n          headless: true,\n        });\n\n        const page = await browser.newpage();\n\n        \/\/ load the html content directly\n        await page.setcontent(htmlcontent, { waituntil: \"networkidle0\" });\n\n        \/\/@ts-expect-error todo\n        const bodyheight = await page.evaluate(() =&gt; {\n          return document.body.scrollheight; \/\/ get the full scrollable height of the body\n        });\n\n        await page.setviewport({\n          width: number(width),\n          height: height || bodyheight, \/\/ use the provided height or fallback to the full body height\n          devicescalefactor: 2,\n        });\n\n        await delay(delaytime);\n\n        const screenshotbuffer = await page.screenshot({\n          fullpage: !height,\n          type: \"png\",\n          omitbackground: false,\n        });\n\n        await browser.close();\n\n        res.setheader(\"content-type\", \"image\/png\");\n        res.setheader(\n          \"content-disposition\",\n          \"attachment; filename=screenshot.png\"\n        );\n        res.status(200).end(screenshotbuffer);\n      });\n\n      req.pipe(bb); \/\/ pipe the request stream to busboy\n    } else {\n      res.setheader(\"allow\", [\"post\"]);\n      res.status(405).end(`method ${req.method} not allowed`);\n    }\n  } catch (error) {\n    console.error(\"error\", error);\n    res.status(500).end(\"internal server error\");\n  }\n}\n\n\n<\/pre>\n<p>  \u767b\u5f55\u540e\u590d\u5236   <\/p>\n<p>*<em>\u8bf4\u660e\uff1a\u4e3a\u672c\u5730\u73af\u5883\u548c\u751f\u4ea7\u73af\u5883\u9009\u62e9 puppeteer<br \/> *<\/em><br \/> \u5728\u6b64\u4ee3\u7801\u4e2d\uff0c\u6211\u4eec\u4e3a puppeteer \u8bbe\u7f6e\u4e86\u52a8\u6001\u5bfc\u5165\uff1a<\/p>\n<ul>\n<li>\n<p>\u672c\u5730\u5f00\u53d1\uff1a\u5982\u679c node_env \u4e0d\u662f\u751f\u4ea7\u73af\u5883\uff0c\u5b83\u4f1a\u4f7f\u7528 puppeteer\uff0c\u5b83\u8bbe\u7f6e\u8d77\u6765\u66f4\u7b80\u5355\uff0c\u5e76\u4e14\u4e0d\u9700\u8981 chrome-aws-lambda\u3002<\/p>\n<\/li>\n<li>\n<p>\u751f\u4ea7\uff1a\u5bf9\u4e8e\u65e0\u670d\u52a1\u5668\u90e8\u7f72\uff0c\u73af\u5883\u5c06\u68c0\u6d4b node_env \u4f5c\u4e3a\u751f\u4ea7\u5e76\u52a0\u8f7d puppeteer-core \u4ee5\u53ca chrome-aws-lambda\uff0c\u8fd9\u4f7f\u5f97\u5b83\u53ef\u4ee5\u5728 aws lambda \u548c\u5176\u4ed6\u7c7b\u4f3c\u73af\u5883\u4e2d\u5de5\u4f5c\u3002\u5728\u6b64\u8bbe\u7f6e\u4e2d\uff0cchrome-aws-lambda \u63d0\u4f9b\u6b63\u786e\u7684 chromium \u8def\u5f84\uff0c\u786e\u4fdd\u4e0e\u65e0\u670d\u52a1\u5668\u63d0\u4f9b\u5546\u7684\u517c\u5bb9\u6027\u3002<\/p>\n<\/li>\n<\/ul>\n<p><strong>\u7b2c 3 \u6b65\uff1a\u4e3a ui \u521b\u5efa\u4e00\u4e2a\u7b80\u5355\u7684 react \u7ec4\u4ef6<\/strong><\/p>\n<p>\u5728\u8fd9\u91cc\uff0c\u6211\u4eec\u5c06\u521b\u5efa\u4e00\u4e2a\u7b80\u5355\u7684\u8868\u5355\uff0c\u8ba9\u7528\u6237\u8f93\u5165\u7f51\u9875\u6355\u83b7\u7684\u503c\u3002\u6b64\u8868\u5355\u5c06\u89e6\u53d1\u751f\u6210\u529f\u80fd\u4ee5\u6355\u83b7\u5e76\u4e0b\u8f7d pdf \u683c\u5f0f\u7684\u5c4f\u5e55\u622a\u56fe\u3002<\/p>\n<pre>import { useState } from \"react\";\n\nexport default function ScreenCaptureComponent() {\n  const [isProcessing, setProcessing] = useState(false);\n  const [width, setWidth] = useState&lt;string&gt;(\"1920\");\n  const [height, setHeight] = useState&lt;string&gt;(\"1000\");\n  const [delay, setDelay] = useState&lt;string&gt;(\"6000\");\n\n  \/\/ Function to clone HTML and prepare for capture\n  function takeScreenshot() {\n    const clonedElement = document.body.cloneNode(true) as HTMLElement;\n    const blob = new Blob([clonedElement.outerHTML], { type: \"text\/html\" });\n    return blob;\n  }\n\n  \/\/ Function to capture screenshot by sending cloned HTML to API\n  async function generateCapture() {\n    setProcessing(true);\n\n    const htmlBlob = takeScreenshot();\n\n    if (!htmlBlob) {\n      setProcessing(false);\n      return;\n    }\n\n    try {\n      const formData = new FormData();\n      formData.append(\"file\", htmlBlob);\n      formData.append(\"width\", width);\n      formData.append(\"height\", height);\n      formData.append(\"delay\", delay);\n      const response = await fetch(\"\/api\/generate-png\", {\n        method: \"POST\",\n        body: formData,\n      });\n\n      if (!response.ok) throw new Error(\"Capture failed\");\n\n      const blob = await response.blob();\n      const downloadUrl = URL.createObjectURL(blob);\n      const link = document.createElement(\"a\");\n      link.href = downloadUrl;\n      link.download = \"capture.png\";\n      link.click();\n      URL.revokeObjectURL(downloadUrl);\n    } catch (error) {\n      console.error(\"Failed to capture screenshot\", error);\n    } finally {\n      setProcessing(false);\n    }\n  }\n\n  return (\n    &lt;div\n      style={{\n        maxWidth: \"400px\",\n        margin: \"50px auto\",\n        padding: \"24px\",\n        backgroundColor: \"white\",\n        borderRadius: \"8px\",\n        width: \"100%\",\n        boxShadow: \"0 4px 6px rgba(0, 0, 0, 0.1)\",\n      }}\n    &gt;\n      &lt;h2\n        style={{\n          fontSize: \"24px\",\n          fontWeight: \"600\",\n          textAlign: \"center\",\n          marginBottom: \"16px\",\n        }}\n      &gt;\n        Webpage Screenshot Capture\n      &lt;\/h2&gt;\n      &lt;form\n        onSubmit={(e) =&gt; {\n          e.preventDefault();\n          generateCapture();\n        }}\n        style={{\n          display: \"flex\",\n          flexDirection: \"column\",\n          alignItems: \"center\",\n          marginBottom: \"16px\",\n        }}\n      &gt;\n        &lt;label\n          style={{ marginBottom: \"8px\", fontWeight: \"500\" }}\n          htmlFor=\"width\"\n        &gt;\n          Width (px)\n        &lt;\/label&gt;\n        &lt;select\n          id=\"width\"\n          value={width}\n          onChange={(e) =&gt; setWidth(e.target.value)}\n          style={{\n            width: \"100%\",\n            padding: \"8px\",\n            marginBottom: \"16px\",\n            borderRadius: \"4px\",\n            border: \"1px solid #ccc\",\n            outline: \"none\",\n          }}\n        &gt;\n          &lt;option value=\"1920\"&gt;1920 (Full HD)&lt;\/option&gt;\n          &lt;option value=\"1366\"&gt;1366 (Laptop)&lt;\/option&gt;\n          &lt;option value=\"1280\"&gt;1280 (Desktop)&lt;\/option&gt;\n          &lt;option value=\"1024\"&gt;1024 (Tablet Landscape)&lt;\/option&gt;\n          &lt;option value=\"768\"&gt;768 (Tablet Portrait)&lt;\/option&gt;\n          &lt;option value=\"375\"&gt;375 (Mobile)&lt;\/option&gt;\n        &lt;\/select&gt;\n\n        &lt;label\n          style={{ marginBottom: \"8px\", fontWeight: \"500\" }}\n          htmlFor=\"height\"\n        &gt;\n          Height (px)\n        &lt;\/label&gt;\n        &lt;input\n          type=\"number\"\n          id=\"height\"\n          value={height}\n          onChange={(e) =&gt; setHeight(e.target.value)}\n          required\n          style={{\n            width: \"100%\",\n            padding: \"8px\",\n            marginBottom: \"16px\",\n            borderRadius: \"4px\",\n            border: \"1px solid #ccc\",\n            outline: \"none\",\n          }}\n        \/&gt;\n\n        &lt;label\n          style={{ marginBottom: \"8px\", fontWeight: \"500\" }}\n          htmlFor=\"delay\"\n        &gt;\n          Delay (ms)\n        &lt;\/label&gt;\n        &lt;input\n          type=\"number\"\n          id=\"delay\"\n          value={delay}\n          onChange={(e) =&gt; setDelay(e.target.value)}\n          required\n          style={{\n            width: \"100%\",\n            padding: \"8px\",\n            marginBottom: \"16px\",\n            borderRadius: \"4px\",\n            border: \"1px solid #ccc\",\n            outline: \"none\",\n          }}\n        \/&gt;\n\n        &lt;button\n          type=\"submit\"\n          disabled={isProcessing}\n          style={{\n            padding: \"8px 16px\",\n            color: \"white\",\n            borderRadius: \"4px\",\n            transition: \"background-color 0.3s\",\n            backgroundColor: isProcessing ? \"#b0bec5\" : \"#2196F3\",\n            cursor: isProcessing ? \"not-allowed\" : \"pointer\",\n          }}\n        &gt;\n          {isProcessing ? \"Capturing...\" : \"Capture Screenshot\"}\n        &lt;\/button&gt;\n      &lt;\/form&gt;\n\n      {\/* Example HTML Element to Capture *\/}\n      &lt;div id=\"capture-area\" style={{ display: \"none\" }}&gt;\n        &lt;h3\n          style={{\n            fontSize: \"20px\",\n            fontWeight: \"600\",\n          }}\n        &gt;\n          Content to Capture\n        &lt;\/h3&gt;\n        &lt;p&gt;This is an example of the HTML content that will be captured.&lt;\/p&gt;\n      &lt;\/div&gt;\n    &lt;\/div&gt;\n  );\n}\n<\/pre>\n<p>  \u767b\u5f55\u540e\u590d\u5236   <\/p>\n<p><strong>\u7ed3\u8bba<\/strong><\/p>\n<p>\u672c\u6559\u7a0b\u6db5\u76d6\u5728 next.js \u4e2d\u8bbe\u7f6e\u7f51\u9875\u6355\u83b7\u5de5\u5177\u3001\u4f7f\u7528 puppeteer \u5904\u7406\u5c4f\u5e55\u622a\u56fe\u4ee5\u53ca\u521b\u5efa\u4ea4\u4e92\u5f0f\u524d\u7aef\u7ec4\u4ef6\u3002\u8bf7\u8bb0\u4f4f\u5728\u672c\u5730\u4f7f\u7528 puppeteer \u5e76\u5728\u751f\u4ea7\u4e2d\u5207\u6362\u5230 puppeteer-core\uff0c\u4ee5\u51cf\u5c11\u6346\u7ed1\u5305\u5927\u5c0f\u5e76\u4f18\u5316\u65e0\u670d\u52a1\u5668\u73af\u5883\u3002\u5feb\u4e50\u7f16\u7801\uff01<\/p>\n<p>\u4ee5\u4e0a\u5c31\u662f\u5982\u4f55\u4f7f\u7528 Nextjs \u548c Puppeteer \u6355\u83b7\u7f51\u9875\u5c4f\u5e55\u622a\u56fe\u7684\u8be6\u7ec6\u5185\u5bb9\uff0c\u66f4\u591a\u8bf7\u5173\u6ce8\u7c73\u4e91\u5176\u5b83\u76f8\u5173\u6587\u7ae0\uff01<\/p>\n","protected":false},"excerpt":{"rendered":"<p>\u4ee5\u7f16\u7a0b\u65b9\u5f0f\u6355\u83b7\u7f51\u9875\u5c4f\u5e55\u622a\u56fe\u5bf9\u4e8e\u751f\u6210\u9884\u89c8\u3001\u521b\u5efa\u57fa\u4e8e\u56fe\u50cf\u7684\u62a5\u544a\u7b49\u975e\u5e38\u6709\u7528\u3002\u5728\u672c\u6307\u5357\u4e2d\uff0c\u6211\u4eec\u5c06\u6784\u5efa\u4e00\u4e2a next.js api \u8def\u7531\uff0c\u8be5\u8def\u7531\u91c7\u7528 url \u5e76\u751f\u6210 png \u5c4f\u5e55\u622a\u56fe\u3002\u6211\u4eec\u7684\u8bbe\u7f6e\u4f7f\u7528 puppeteer \u548c chrome-aws-lambda \u6765\u5229\u7528\u65e0\u5934 chrome \u6d4f\u89c8\u5668\uff0c\u4f7f\u5176\u591a\u529f\u80fd\u4e14\u53ef\u7528\u4e8e\u751f\u4ea7\u3002 \u6211\u4eec\u5c06\u9996\u5148\u8bbe\u7f6e\u4e00\u4e2a\u65b0\u7684 next.js \u9879\u76ee\uff0c\u5e76\u9010\u6b65\u6d4f\u89c8\u4ee3\u7801\u4ee5\u4e86\u89e3 api \u5982\u4f55\u6355\u83b7\u5c4f\u5e55\u622a\u56fe\u3002 \u5148\u51b3\u6761\u4ef6 \u8bbe\u7f6e next.js \u5e94\u7528 \u4f7f\u7528 puppeteer \u914d\u7f6e api \u8def\u7531 \u4e3a\u6355\u83b7\u63a5\u53e3\u521b\u5efareact\u7ec4\u4ef6 puppeteer \u7684\u672c\u5730\u4e0e\u90e8\u7f72\u914d\u7f6e\u8bf4\u660e \u5f00\u59cb\u65b0\u7684 next.js \u9879\u76ee \u521b\u5efa\u4e00\u4e2a\u65b0\u7684 next.js \u5e94\u7528\u7a0b\u5e8f\uff1a npx create-next-app@latest capture-image-app cd capture-image-app \u767b\u5f55\u540e\u590d\u5236 \u5b89\u88c5\u5fc5\u8981\u7684\u4f9d\u8d56\u9879\uff1a npm install puppeteer puppeteer-core chrome-aws-lambda busboy \u767b\u5f55\u540e\u590d\u5236 \u7b2c2\u6b65\uff1a\u521b\u5efa\u751f\u6210\u5c4f\u5e55\u622a\u56fe\u7684api\u8def\u7531 \u73b0\u5728\uff0c\u6211\u4eec\u5c06\u8bbe\u7f6e\u4e00\u4e2a api \u7aef\u70b9\u6765\u6839\u636e\u63d0\u4f9b\u7684 [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[16],"tags":[],"class_list":["post-2059","post","type-post","status-publish","format-standard","hentry","category-16"],"_links":{"self":[{"href":"https:\/\/fwq.ai\/blog\/wp-json\/wp\/v2\/posts\/2059","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/fwq.ai\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/fwq.ai\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/fwq.ai\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/fwq.ai\/blog\/wp-json\/wp\/v2\/comments?post=2059"}],"version-history":[{"count":0,"href":"https:\/\/fwq.ai\/blog\/wp-json\/wp\/v2\/posts\/2059\/revisions"}],"wp:attachment":[{"href":"https:\/\/fwq.ai\/blog\/wp-json\/wp\/v2\/media?parent=2059"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/fwq.ai\/blog\/wp-json\/wp\/v2\/categories?post=2059"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/fwq.ai\/blog\/wp-json\/wp\/v2\/tags?post=2059"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}