You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Next.js中如何在LangChain的WebPDFLoader中配置PDF URL?

解决Next.js中LangChain WebPDFLoader加载URL PDF的问题

你当前代码的核心问题是错误使用空Blob初始化WebPDFLoader,且没有正确处理异步加载逻辑。以下是修正后的实现方案:

核心修正点

  • WebPDFLoader支持直接传入PDF URL字符串,无需手动创建空Blob
  • loader.load()是异步方法,必须用async/await处理,不能同步赋值
  • 需用React状态管理保存加载结果,实现组件响应式更新

修正后的完整代码

"use client";
import React, { useEffect, useState } from "react";
import { WebPDFLoader } from "langchain/document_loaders/web/pdf";
import { guestPdfId } from "@/components/Hero";

const bucketId = process.env.NEXT_PUBLIC_APPWRITE_BUCKET_ID!;
const fileId = guestPdfId;
const projectId = process.env.NEXT_PUBLIC_APPWRITE_PROJECT_ID!;

const pdfUrl = `https://cloud.appwrite.io/v1/storage/buckets/${bucketId}/files/${fileId}/view?project=${projectId}&mode=admin`;

const ProcessPdf = () => {
  const [documentCount, setDocumentCount] = useState<number>(0);
  const [loading, setLoading] = useState<boolean>(false);

  // 加载PDF并处理文档
  const loadAndProcessPdf = async () => {
    setLoading(true);
    try {
      // 直接传入PDF URL初始化WebPDFLoader
      const loader = new WebPDFLoader(pdfUrl, {
        pdfjs: () => import("pdfjs-dist/legacy/build/pdf.js"),
      });
      // 异步加载文档
      const docs = await loader.load();
      setDocumentCount(docs.length);
    } catch (error) {
      console.error("加载PDF失败:", error);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div>
      <button onClick={loadAndProcessPdf} disabled={loading}>
        {loading ? "加载中..." : "获取PDF文档数量"}
      </button>
      {documentCount > 0 && (
        <p>PDF解析出的文档片段数量:{documentCount}</p>
      )}
    </div>
  );
};

export default ProcessPdf;

关键细节说明

  1. WebPDFLoader初始化:直接将pdfUrl传入构造函数,LangChain会自动处理URL的PDF加载逻辑
  2. 异步处理:用async/await包裹loader.load(),确保等待PDF加载完成后再处理结果
  3. 状态管理:用useState维护加载状态和文档数量,避免同步代码的逻辑错误
  4. 错误处理:添加try/catch捕获加载过程中的异常,避免页面崩溃

额外注意事项

  • 确保AppWrite存储桶的CORS配置允许你的Next.js域名访问,否则会出现跨域错误
  • 如果PDF需要权限验证,可先通过fetch获取Blob再传入WebPDFLoader:
// 带权限验证的Blob获取方式
const response = await fetch(pdfUrl, {
  headers: {
    "Authorization": `Bearer ${yourAuthToken}`
  }
});
const blob = await response.blob();
const loader = new WebPDFLoader(blob, { /* 配置项 */ });

内容的提问来源于stack exchange,提问作者Favour Onyido

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 04:26:25