在Google Cloud Storage上将PDF转换为PNG

编程入门 行业动态 更新时间:2024-10-10 15:19:01
本文介绍了在Google Cloud Storage上将PDF转换为PNG的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想从上传到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

本文发布于:2023-10-31 10:39:22,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1545835.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:上将   转换为   Cloud   Google   Storage

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!