I have a cloud function that runs in the Google/Firebase cloud environment that listens for a file to be added to a storage bucket, checks to see if it's of PDF
format before attempting to convert all the pages to individual PNG
files for uploading back into the bucket for use across the app.
In order to achieve this I am making use of the ImageMagick library already pre-installed in the environment as mentioned here.
I've imported the libary like so:
import * as gm from "gm";
const im = gm.subClass({ imageMagick: true });
I then download the pdf file from the storage bucket to the local directory:
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 ...
With the PDF
file downloaded locally, I then attempt to covert the first page of the file into a PNG
file via the use of the ImageMagick library:
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;
}
});
When the function runs, I get the following error printed into the logs:
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'
From looking about online, there are a couple of other posts I have come across with similar problems:
- https://askubuntu.com/questions/1081895/trouble-with-batch-conversion-of-png-to-pdf-using-convert This post mentioned changing out the ImageMagick policy.xml file, of which I don't believe I have access to through Firebase?
- cannot get this 'convert' cloud functions command to run Here they mention installing Ghostscript in the cloud functions directory. I've done this but still to no avail
Any help at this point would be great. The main aim of this function like mentioned at the top of the question is to take a multi-page PDF
, convert each page to a PNG
image and then store those in the same bucket alongside the original PDF
file.