Search code examples
javascriptgoogle-cloud-functionsnode-pdfkit

Getting Image from Firebase Storage and placing into PDF


So i'm new to PDF kit and have a basic understanding of Javascript but i can't seem for the life of me to figure out how to place an image from Firebase Storage into the PDF or if there is a way to use GCF to store that image and place it into the PDF. I'm generating the PDF using Google Cloud Functions and Node.js Below is what i have so far:

exports.pdf = functions.https.onRequest((request,response)=>{
    //Create a document
    const PDFDocument = require('pdfkit');
    const doc = new PDFDocument();
    const storageBucket = admin.storage().bucket();
    const logo = g
    generateHeader(doc);
    // Pipe its output somewhere, like to a file or HTTP response
    // See below for browser usage

    // Embed a font, set the font size, and render some text
    doc.font('Courier')
       .fontSize(15)
       .text('Some text with an embedded font!', 100, 100);

    // Add an image, constrain it to a given size, and center it vertically and horizontally
    // doc.image('https://firebasestorage.googleapis.com/v0/b/redog-bf9c8.appspot.com/o/pdfresource%2Fsplash.png?alt=media&token=25028ea2-5085-4782-9038-88b694b69f50', {
    //    fit: [250, 300],
    //    align: 'center',
    //    valign: 'center'
    // });

    // Add another page
    doc.addPage()
       .fontSize(25)
       .text('Here is some vector graphics...', 100, 100);

    // Draw a triangle
    doc.save()
       .moveTo(100, 150)
       .lineTo(100, 250)
       .lineTo(200, 250)
       .fill("#FF3300");

    // Apply some transforms and render an SVG path with the 'even-odd' fill rule
    doc.scale(0.6)
       .translate(470, -380)
       .path('M 250,75 L 323,301 131,161 369,161 177,301 z')
       .fill('red', 'even-odd')
       .restore();

    // Add some text with annotations
    doc.addPage()
       .fillColor("blue")
       .text('Here is a link!', 100, 100)
       .underline(100, 100, 160, 27, {color: "#0000FF"})
       .link(100, 100, 160, 27, 'http://google.com/');

    // Finalize PDF file
    const myPdfFile = admin.storage().bucket().file('/test/Arbeitsvertrag.pdf');
const stream = doc.pipe(myPdfFile.createWriteStream());
    doc.end();
    });

    function generateHeader(doc) {
        doc
          .image("storage/pdfresource/splash.png", 50, 45, { width: 50 })
          .fillColor("#444444")
          .fontSize(20)
          .text("ACME Inc.", 110, 57)
          .fontSize(10)
          .text("123 Main Street", 200, 65, { align: "right" })
          .text("New York, NY, 10025", 200, 80, { align: "right" })
          .moveDown();
      }

The issue i have is within the GenerateHeader function...it's staying it can't find the file...does anyone have any idea how i can point it in the right direction?


Solution

  • The solution here was to put the download url into a separate function:

      function toBase64(url) {
                    return new Promise(async (resolve, reject)=>{
                        var https = require('https');
                        var req = await https.get(url, (res) => {
                            res.setEncoding('base64');
                            let body = "data:" + res.headers["content-type"] + ";base64,";
                            console.log("BODY", body)
                            res.on('data', (d) => {
                                body += d;
                            });
                            res.on('end', () => {
                                console.log("END", body)
    
                                resolve(body);
                            });
                        });
                        req.on('error', err => {
                            console.error('error!',err);
                            reject(err);
                        });
    
                    });
    
                }
    

    and then place it into your doc like so:

    return Promise.all([toBase64(url)]).then(([base64])=>{
    doc.image(base64,{width:50});
    })