JavaScript 使用 pdf.js 提取 PDF 文字与图片
本文介绍如何利用 JavaScript 和 pdf.js 库在 Web 端提取 PDF 文档中的文字与图片。通过调用 pdfjsLib 相关 API,可实现页面文本获取及图像对象解析,为 PDF 转 Word 等文档处理提供基础思路。
本系列文章聚焦于 JavaScript 文件处理,此前已介绍过相关基础。本文在此基础上,补充讲解如何在 JS 环境中提取 PDF 文件内的文字与图片内容。
从 PDF 中提取文字 - 核心代码
实现该功能的核心在于使用 pdf.js 库。该库在前文已有提及,主要用于实现 PDF 在 Web 端的预览功能。
相关文档地址:mozilla.github.io/pdf.js/api/draft/module-pdfjsLib-PDFPageProxy.html
/**
* Retrieves the text of a specif page within a PDF Document obtained through pdf.js
*
* @param {Integer} pageNum Specifies the number of the page
* @param {PDFDocument} PDFDocumentInstance The PDF document obtained
**/
function getPageText(pageNum, PDFDocumentInstance) {
// Return a Promise that is solved once the text of the page is retrieven
return new Promise(function (resolve, reject) {
PDFDocumentInstance.getPage(pageNum).then(function (pdfPage) {
// The main trick to obtain the text of the PDF page, use the getTextContent method
pdfPage.getTextContent().then(function (textContent) {
var textItems = textContent.items;
var finalString = '';
// Concatenate the string of the item to the final string
for (var i = 0; i < textItems.length; i++) {
var item = textItems[i];
finalString += item.str + ' ';
}
// Solve promise with the text retrieven from the page
resolve(finalString);
});
});
});
}
从 PDF 中提取图片
提取图片的核心代码如下:
// first here I open the document
pdf.getDocument('haorooms.pdf').promise.then(async function (pdfObj) {
// because I am testing, I just wanted to get page 7
const page = await pdfObj.getPage(7);
// now I need to get the image information and for that I get the operator list
const operators = await page.getOperatorList();
// this is for the paintImageXObject one, there are other ones, like the paintJpegImage which I assume should work the same way, this gives me the whole list of indexes of where an img was inserted
const rawImgOperator = operators.fnArray
.map((f, index) => (f === pdf.OPS.paintImageXObject ? index : null))
.filter((n) => n !== null);
// now you need the filename, in this example I just picked the first one from my array, your array may be empty, but I knew for sure in page 7 there was an image... in your actual code you would use loops, such info is in the argsArray, the first arg is the filename, second arg is the width and height, but the filename will suffice here
const filename = operators.argsArray[rawImgOperator[0]][0];
// now we get the object itself from page.objs using the filename
page.objs.get(filename, async (arg) => {
// and here is where we need the canvas, the object contains information such as width and height
const canvas = ccc.createCanvas(arg.width, arg.height);
const ctx = canvas.getContext('2d');
// now you need a new clamped array because the original one, may not contain rgba data, and when you insert you want to do so in rgba form, I think that a simple check of the size of the clamped array should work, if it's 3 times the size aka width*height*3 then it's rgb and shall be converted, if it's 4 times, then it's rgba and can be used as it is; in my case it had to be converted, and I think it will be the most common case
const data = new Uint8ClampedArray(arg.width * arg.height * 4);
let k = 0;
let i = 0;
while (i < arg.data.length) {
data[k] = arg.data[i]; // r
data[k + 1] = arg.data[i + 1]; // g
data[k + 2] = arg.data[i + 2]; // b
data[k + 3] = 255; // a
i += 3;
k += 4;
}
// now here I create the image data context
const imgData = ctx.createImageData(arg.width, arg.height);
imgData.data.set(data);
ctx.putImageData(imgData, 0, 0);
// get myself a buffer
const buff = canvas.toBuffer();
// and I wrote the file, worked like charm, but this buffer encodes for a png image, which can be rather large, with an image conversion utility like sharp.js you may get better results by compressing the thing.
fs.writeFile('test', buff);
});
});
小结
本文主要介绍了在 JS 中获取 PDF 文本和图片的方法。其实,PDF 转 Word 的大致思路与此类似,即分别获取文本和图片,然后写入 Word 文档。本文主要利用了 pdfjs 库,并参考了 GitHub 上的 issue:github.com/mozilla/pdf.js/issues/13541。
以上就是 JavaScript 如何提取 PDF 中的图片和文字的详细内容,更多关于 JavaScript 提取 PDF 图片和文字的资料请关注本站其它相关文章!
ES6模块化中js文件怎么用import和export交互
2026-11-05 17:00:48
JS读取本地文件时报错或无响应的常见原因
2026-11-05 16:32:31
let、const与var的区别:JavaScript变量声明最佳实践
2026-11-05 14:16:38
JS中直接定义静态二维数组的字面量写法
2026-11-05 14:16:08
JS 怎么查找字符串中所有匹配项的位置
2026-11-05 14:15:53
