在Google Cloud Storage上将PDF转换为PNG [英] Convert PDF to PNG on Google Cloud Storage
问题描述
我想从上传到Google存储桶中的不同文件创建PNG缩略图.目前,我的目标是图像和PDF.对于图像,功能正常,但是对于PDF,我无法使其正常工作. 想法是从存储桶中下载文件,执行该工作,然后将新文件(PNG缩略图)上传到存储桶.
I want to create a PNG thumbnail from different files which are uploaded on a Google Storage bucket. For the moment, I am targeting images and PDFs. For images the functions works fine, but for PDFs I cannot make it work. The idea is to download the file from the bucket, do the job and then upload the new file (the PNG thumbnail) to the bucket.
因此,我正在检查上传文件的类型,如果文件是图像,则使用createImageFromImage
函数进行转换,如果是PDF,则使用createImageFromPDF
.
So I am doing a check to see the type of the uploaded file and if the file is an image I am doing the conversion with the createImageFromImage
function and if it's PDF, I am using createImageFromPDF
.
主要功能:
const gm = require('gm').subClass({imageMagick: true});
const fs = require('fs');
const path = require('path');
const {Storage} = require('@google-cloud/storage');
const storage = new Storage();
const im = require('imagemagick');
exports.generatePreviewImage = event => {
const object = event.data || event; // Node 6: event.data === Node 8+: event
const file = storage.bucket(object.bucket).file(object.name);
const filePath = `gs://${object.bucket}/${object.name}`;
// Ignore already-resized files (to prevent re-invoking this function)
if (file.name.endsWith('-thumb.png')) {
console.log(`The image ${file.name} is already resized.`);
return;
} else {
console.log(`Analyzing ${file.name}.`);
// Check the file extension
if(object.contentType.startsWith('image/')) { // It's an image
console.log("This is an image!")
return createImageFromImage(file);
} else if (object.contentType === 'application/pdf') { // It's a PDF
console.log("This is a PDF file!")
return createImageFromPDF(file);
} else {
return;
}
}
};
createImageFromImage(file)-起作用
createImageFromImage(file) - which works
function createImageFromImage(file) {
const tempLocalPath = `/tmp/${path.parse(file.name).base}`;
// Download file from bucket.
return file
.download({destination: tempLocalPath})
.catch(err => {
console.error('Failed to download file.', err);
return Promise.reject(err);
})
.then(() => {
console.log(
`Image ${file.name} has been downloaded to ${tempLocalPath}.`
);
// Resize the image using ImageMagick.
return new Promise((resolve, reject) => {
gm(tempLocalPath)
.resize(250)
.setFormat('png')
.write(tempLocalPath, (err, stdout) => {
if (err) {
console.error('Failed to resize the image.', err);
reject(err);
} else {
resolve(stdout);
}
});
});
})
.then(() => {
console.log(`Image ${file.name} has been resized.`);
// Get the name of the file without the file extension and mark the result as resized, to avoid re-triggering this function.
const newName = `${path.parse(file.name).name}-thumb.png`;
// Upload the Blurred image back into the bucket.
return file.bucket
.upload(tempLocalPath, {destination: newName})
.catch(err => {
console.error('Failed to upload resized image.', err);
return Promise.reject(err);
});
})
.then(() => {
console.log(`Resized image has been uploaded to ${file.name}.`);
// Delete the temporary file.
return new Promise((resolve, reject) => {
fs.unlink(tempLocalPath, err => {
if (err) {
reject(err);
} else {
resolve();
}
});
});
});
}
createImageFromPDF(file)-不起作用
createImageFromPDF(file) - which doesn't work
function createImageFromPDF(file) {
const tempLocalPath = `/tmp/${path.parse(file.name).base}`;
return file
.download({destination: tempLocalPath}) // Download file from bucket.
.catch(err => {
console.error('Failed to download file.', err);
return Promise.reject(err);
})
.then(() => { // Convert the file to PDF.
console.log(`File ${file.name} has been downloaded to ${tempLocalPath}.`);
return new Promise((resolve, reject) => {
im.convert([tempLocalPath, '-resize', '250x250', `${path.parse(file.name).name}-thumb.png`],
function(err, stdout) {
if (err) {
reject(err);
} else {
resolve(stdout);
}
});
});
})
.then(() => { // Upload the new image to the bucket
console.log(`File ${file.name} has been resized.`);
// Get the name of the file without the file extension and mark the result as resized, to avoid re-triggering this function.
const newName = `${path.parse(file.name).name}-thumb.png`;
// Upload the Blurred image back into the bucket.
return file.bucket
.upload(tempLocalPath, {destination: newName})
.catch(err => {
console.error('Failed to upload resized image.', err);
return Promise.reject(err);
});
})
.then(() => { // Delete the temporary file.
console.log(`Resized image has been uploaded to ${file.name}.`);
return new Promise((resolve, reject) => {
fs.unlink(tempLocalPath, err => {
if (err) {
reject(err);
} else {
resolve();
}
});
});
});
}
我从im.convert
收到一条错误消息:
Command failed: convert: no images defined 'test1-thumb.png' @ error/convert.c/ConvertImageCommand/3210.
我不确定这是否是从PDF文件创建PNG缩略图的正确方法,但我尝试了其他解决方案,但均未成功.请告知我我做错了.谢谢!
I get an error from im.convert
which says:
Command failed: convert: no images defined 'test1-thumb.png' @ error/convert.c/ConvertImageCommand/3210.
I am not sure if this is the right way to create a PNG thumbnail from a PDF file, I tried other solutions without success. Please advise what I am doing wrong. Thanks!
推荐答案
我刚刚意识到gm
可以处理ImageMagick,而您已经做到了(使用.subClass({imageMagick: true})
),那么为什么还要麻烦另一个包装器呢?
I just realized gm
can handle ImageMagick, and you already do it (using .subClass({imageMagick: true})
), so why bother with another wrapper?
无论如何,我只是尝试了这一点:
Anyway, I just tried this:
const gm = require('gm').subClass({imageMagick: true});
const file = './test.pdf';
gm(file)
.resize(250, 250)
.setFormat('png')
.write(file, (err) => {
if (err) console.log('FAILED', err);
else console.log('SUCCESS');
});
它指出了一些未授权"错误,因为最初禁用了PDF处理-请参见此-但在我完成之后根据建议编辑了/etc/ImageMagick*/policy.xml
,效果很好.
It stated some "not authorized" error because PDF processing is originally disabled - see this - but after I've edited /etc/ImageMagick*/policy.xml
as suggested, it worked perfectly.
这篇关于在Google Cloud Storage上将PDF转换为PNG的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!