欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 科技 > 名人名企 > nodejs将pdf转换成图片并提取图片内容

nodejs将pdf转换成图片并提取图片内容

2025/4/2 16:56:49 来源:https://blog.csdn.net/qq_35496811/article/details/145904227  浏览:    关键词:nodejs将pdf转换成图片并提取图片内容

pdf2pic 安装方法

安装文档地址:https://github.com/yakovmeister/pdf2image/blob/HEAD/docs/gm-installation.md

Windows下载下面两个文件,安装时没有自动设置环境变量,要分别设置到环境变量

  • Download Ghostscript Windows: https://github.com/ArtifexSoftware/ghostpdl-downloads/releases/tag/gs952
  • Download GraphicsMagick for Windows: https://sourceforge.net/projects/graphicsmagick/files/graphicsmagick-binaries/

示例代码

实现RAG将pdf文档内容添加到向量数据库进行向量检索时,表格等数据无法识别,可以先用多模态模型对数据进行提取,然后再添加到向量数据中。这样做查询时用文本向量模型就够了。

 对pdf中所有页面进行截图,手动指定了一张图片,对这个图片中数据进行了提取。

import { fromPath } from 'pdf2pic';
import * as pdfjsLib from 'pdfjs-dist';
import OpenAI from 'openai';
import fs from 'fs';
import process from "node:process";
import 'dotenv/config';const filename = 't';
const filePath = `./${filename}.pdf`;const options = {density: 100,saveFilename: filename,savePath: "./images",format: "png",width: 600,height: 600
};const convert = fromPath(filePath, options);// 加载 PDF 文件
const loadingTask = pdfjsLib.getDocument(filePath);
const pdfDocument = await loadingTask.promise;// 获取总页数
const totalPages = pdfDocument.numPages;await Promise.all(new Array(totalPages).fill(0).map(async (_, index) => {await convert(index + 1, { responseType: "image" });console.log(`Page ${index + 1} is now converted as image`);})
);try {// 1. 读取本地图片并转换为 Base64const imagePath = "./images/t.6.png";const imageFile = fs.readFileSync(imagePath);const base64Image = imageFile.toString("base64");const openai = new OpenAI({// apiKey: process.env.DASHSCOPE_API_KEY,apiKey: process.env.OPENAI_API_KEY,baseURL: process.env.OPENAI_BASE_URL});// 2. 构建请求参数const response = await openai.chat.completions.create({// model:'deepseek-r1',model: process.env.OPENAI_MODEL_Multi_Mode,messages: [{role: "user",content: [{type: "text",text: `提取图片中所有信息,根据下面不同情况分别提取对应信息:1、全部使用markdown格式2、使用图片上的原本语言,不能修改图片中文字内容,不能自动翻译成或使用其他语言3、段落文字正常提取,不做处理4、图片中表格使用markdown格式提取5、图片中统计图等其他图片,使用文字描述,描述开始和结束标明是在描述图片`},{type: "image_url",image_url: {url: `data:image/png;base64,${base64Image}`,detail: "high",},},],},],temperature: 0,max_tokens: 2048,});// 3. 输出结果console.log(response.choices[0].message.content);
} catch (error) {console.error("Error:", error);
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词