Search code examples
node.jsfirebasegoogle-cloud-functionsgoogle-cloud-storagepdfkit

Firebase Storage and PDFkit. How specify MIME type?


I am trying to create a PDF file using Firebase Functions and save it to Firebase Storage. I used the code I found in this answers.

const functions = require('firebase-functions');
const admin = require('firebase-admin');
const pdfkit = require('pdfkit');

admin.initializeApp(functions.config().firebase);

exports.createPDF = functions.https.onRequest((req, res) => {
    const myPdfFile = admin.storage().bucket("gs://MYBUCKETNAME.appspot.com/").file('test.pdf');
    const doc = new pdfkit();
    const stream = doc.pipe(myPdfFile.createWriteStream());
    doc.fontSize(25).text('Hello World!', 100, 100);
    doc.end();

    stream.on('finish', function () {
        res.status(200).send({status: "ok"});
    });
});

The problem:

The code is working and the file is generated. The problem is that the file is of MIME type application/octet-stream. So I can't download it or open it. enter image description here

How can I save the pdf file and specify the MIME type? Or change it after creation?


Solution

  • Is necessary to define the metadata of the content type for your file "contentType: 'application/pdf'"

    For example:

    const stream = doc.pipe(myPdfFile.createWriteStream( 
    {metadata: { contentType: 'application/pdf'}));