如何使用NodeJS imagemagick库将PDF的首页转换为JPG? [英] How can I convert the first page of a PDF to a JPG using the NodeJS imagemagick library?
问题描述
我正在尝试将pdf文件转换为预览图标jpg 对NodeJS使用imagemagick库.我在尝试着 仅生成首页(用于多页pdf)的预览.
I am attempting to convert pdf files into a preview icon jpg using the imagemagick library for NodeJS. I am trying to generate a preview of only the first page (for multi-page pdfs).
在普通的命令行imagemagick程序中,这可以是
只需说出转换file.pdf [0] file.jpg"
[0]告诉它仅转换第一页.
In the normal command line imagemagick program this can be
done easily by saying "convert file.pdf[0] file.jpg"
where the [0] tells it to only convert the first page.
但是,我不确定如何使用此库. 我尝试将[0]连接到文件名,但这只是 读取它作为真实文件名的一部分.任何人都知道 使用此库解决此问题的方法?
However I am not sure how to do that with this library. I tried concatenating [0] to the filename, but it just reads it as part of the real file name. Anyone know of a way around this using this library?
我环顾了一会儿,发现了这个,但是 他们没有使用这个库. 将PDF转换为PNG Node.JS
I had a look around for a while and found this, but they are not using this library. Convert PDF to PNG Node.JS
我正在使用的特定库位于: https://www.npmjs.com/package /imagemagick
The specific library I am using is located here: https://www.npmjs.com/package/imagemagick
我正在使用的代码如下:
The code I am working with is below:
let path = '/tmp/';
let pageNumber = '[0]';
let filePath = path + fileId + fileName + pageNumber;
let imgFilePath = path + fileId + '.jpg';
let writeStream = fs.createWriteStream(filePath);
writeStream.on('error',err => {
reject(err);
});
stream.pipe(writeStream);
im.convert([
filePath,
'-background','white',
'-alpha','remove',
'-resize','192x192',
'-quality','100',
imgFilePath
],
推荐答案
问题是在进行转换之前,您将 [0] 部分连接到了文件名上.您应该在转换函数的范围内将 [0] 连接起来,如下所示:
The problem is that you are concatenating the [0] part onto the filename before you do the conversion. You should concatenate the [0] within the scope of the convert function like this:
let path = '/tmp/';
let filePath = path + fileId + fileName;
let imgFilePath = path + fileId + '.jpg';
let writeStream = fs.createWriteStream(filePath);
writeStream.on('error',err => {
reject(err);
});
stream.pipe(writeStream);
im.convert([
filePath + '[0]',
'-background','white',
'-alpha','remove',
'-resize','192x192',
'-quality','100',
imgFilePath
],
此解决方案经过测试可正常工作.
This solution is tested working.
这篇关于如何使用NodeJS imagemagick库将PDF的首页转换为JPG?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!