使用JavaScript从PDF文件中提取图像 [英] Extract images from PDF file with JavaScript
问题描述
我想编写JavaScript代码来从PDF文件中提取所有图像文件,或者将它们作为JPG或其他图像格式获取。已经有一些JavaScript代码用于读取PDF文件,例如在PDF查看器中 pdf-js 。
I want to write JavaScript code to extract all image files from a PDF file, perhaps getting them as JPG or some other image format. There is already some JavaScript code for reading a PDF file, for example in the PDF viewer pdf-js.
window.addEventListener('change', function webViewerChange(evt) {
var files = evt.target.files;
if (!files || files.length === 0)
return;
// Read the local file into a Uint8Array.
var fileReader = new FileReader();
fileReader.onload = function webViewerChangeFileReaderOnload(evt) {
var buffer = evt.target.result;
var uint8Array = new Uint8Array(buffer);
PDFView.open(uint8Array, 0);
};
var file = files[0];
fileReader.readAsArrayBuffer(file);
PDFView.setTitleUsingUrl(file.name);
........
我可以使用此代码来帮助读取和提取图像文件吗?
Can I use this code to help read and extract the image files?
推荐答案
如果您打开一个页面同 pdf.js
,例如
If you open a page with pdf.js
, for example
PDFJS.getDocument({url: <pdf file>}).then(function (doc) {
doc.getPage(1).then(function (page) {
window.page = page;
})
})
然后你可以使用 getOperatorList
搜索 paintJpegXObject
对象并获取资源。
you can then use getOperatorList
to search for paintJpegXObject
objects and grab the resources.
window.objs = []
page.getOperatorList().then(function (ops) {
for (var i=0; i < ops.fnArray.length; i++) {
if (ops.fnArray[i] == PDFJS.OPS.paintJpegXObject) {
window.objs.push(ops.argsArray[i][0])
}
}
})
现在 args
将包含您需要获取的该页面的资源列表。
Now args
will have a list of the resources from that page that you need to fetch.
console.log(window.args.map(function (a) { page.objs.get(a) }))
应打印在控制台上有一堆< img />
对象,其中包含data-uri src =
属性。这些可以直接插入页面,或者你可以做更多的脚本来获取原始数据。
should print to the console a bunch of <img />
objects with data-uri src=
attributes. These can be directly inserted into the page, or you can do more scripting to get at the raw data.
它只适用于嵌入式JPEG对象,但它是一个开始!
It only works for embedded JPEG objects, but it's a start!
这篇关于使用JavaScript从PDF文件中提取图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!