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中所有页面进行截图,手动指定了一张图片,对这个图片中数据进行了提取。
javascript">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);
}