Firebase Cloud Function & ImageMagick "convert-im6.q16: not authorized" Error



我有一个在Google/Firebase云环境中运行的云函数,它监听要添加到存储桶中的文件,在尝试将所有页面转换为单独的PNG文件以上传回存储桶以在整个应用程序中使用之前,检查它是否为PDF格式。

为了实现这一点,我使用了已经在这里提到的环境中预装的ImageMagick库。

我导入了这样的库:

import * as gm from "gm";
const im = gm.subClass({ imageMagick: true });

然后我将pdf文件从存储桶下载到本地目录:

const tempFilePath = path.join(os.tmpdir(), `${fileName}.pdf`);
const bucket = admin.storage().bucket();
return bucket.file(filePath).download({
destination: tempFilePath
}).then(async () => {
... code to continue in a moment ...

使用本地下载的PDF文件,然后我尝试通过使用ImageMagick库将文件的第一页转换为PNG文件:

const newName = path.basename(filePath, ".pdf") + "_PAGE_0.png";

const tempNewPath = path.join(os.tmpdir(), newName);
im(`${tempFilePath}[0]`)
.setFormat("png")
.write(tempNewPath, (error) => {
if (!error) {
console.log("Finished saving PNG");
return bucket.upload(tempNewPath, { destination: storagePath });
} else {
console.log(error);
return false;
}
});

当函数运行时,我会将以下错误打印到日志中:

Command failed: convert-im6.q16: unable to open image `/tmp/r4dTjOTUz6b92pm8arnu.pdf': No such file or directory    
convert-im6.q16: not authorized `/tmp/r4dTjOTUz6b92pm8arnu.pdf'

从网上看,我遇到了其他几个类似问题的帖子:

  • https://askubuntu.com/questions/1081895/trouble-with-batch-conversion-of-png-to-pdf-using-convert这篇文章提到了更改ImageMagick policy.xml文件,我认为我无法通过Firebase访问该文件
  • 无法获取此';转换';cloudfunctions命令在这里他们提到在cloudfunctions目录中安装Ghostscript。我已经这么做了,但还是无济于事

在这一点上提供任何帮助都将是非常棒的。这个函数的主要目的是获取多页PDF,将每个页面转换为PNG图像,然后将这些图像与原始PDF文件一起存储在同一个存储桶中。

我遇到了类似的问题(我花了几个小时才找到解决方案(。如果有人在2023年遇到这个问题,下面是如何解决的。

注意:OP的问题是将PDF转换为jpeg。

使用PDF到PNG转换器将PDF缓冲区或文件转换为PNG。该库使用服务器端nodejs画布库将PDF转换为PNG,而不需要任何操作系统依赖项。

一旦您的文件为PNG,您就可以使用imagemaigck将其转换为JPEG或执行其他图像处理。

使用PDF缓冲区的示例

import { pdfToPng, PngPageOutput } from 'pdf-to-png-converter'
// rest of your existing code
// ....
const pngPages: PngPageOutput[] = await pdfToPng(pdfBuffer)
const pngBuffer = Buffer.concat(pngPages.map((page) => page.content))
// you can write the buffer to a file or just pass it to imagemagick for 
// subsequent conversion
fs.writeFileSync('hello.png', pngBuffer)

相关内容

最新更新