我在将一些pdf文件转换为png缩略图时遇到了一些麻烦。
const outputStream = gm(Buffer.from(path, 'base64'))
.selectFrame(0)
.noProfile()
.quality(60)
.density(200)
.background('white')
.resize(600, 600)
.setFormat('png');
有什么方法可以解决这个错误或者有其他方法可以得到pdf缩略图吗?
Flag -flatten解决了我的问题:)
在某些文件格式中(例如Photoshop的PSD),复杂的图像可能由 "图层"(独立的图像)来表示,这些图层必须进行合成才能获得最终的效果。缩放选项可以完成这种合成。在尊重合成运算符和页面偏移的情况下,图像序列被依次合成每个图像而创建的单一图像所取代。虽然-flatten对于消除图层非常有用,但它也是一个通用的合成工具。
所以我只需生成扁平化的pdf,然后将其转换为图像即可。
希望能帮到大家
const flattenPDFStream = gm(Buffer.from(path, 'base64'))
.define('pdf:use-cropbox=true')
.selectFrame(0)
.flatten();
const flattenPDF = await gmToBuffer(flattenPDFStream);
const outputStream = gm(flattenPDF)
.selectFrame(0)
.noProfile()
.quality(90)
.background('white')
.resize(400, 400)
.setFormat('png');
全球机制的缓冲功能。
function gmToBuffer(data) {
return new Promise((resolve, reject) => {
data.stream((err, stdout, stderr) => {
if (err) { return reject(err); }
const chunks = [];
stdout.on('data', chunk => {
// Not best solution, but i need to control error message will not appear in pdf
if (!chunk.includes('Error')) {
chunks.push(chunk);
} else {
console.log(chunk.toString());
}
});
// these are 'once' because they can and do fire multiple times for multiple errors,
// but this is a promise so you'll have to deal with them one at a time
stdout.once('end', () => { resolve(Buffer.concat(chunks)); });
stderr.once('data', data => { reject(String(data)); });
});
});
}