Zain Chris
Zain Chris

Reputation: 31

pdfmake is returning undefined

I am using the pdfmake package to generate PDFs, but when I test on Postman, it returns undefined.

My app.js:

const express = require('express');
const bodyParser = require('body-parser');
const path = require('path');

const port = 9003;

const app = express();

//set the public folder app.use(express.static(path.join(__dirname, 'public')))

//body parser middle ware app.use(bodyParser.urlencoded({ extended: true }))

//Index Route app.get('/', (req, res) => { //res.send('Hello World'); res.sendfile('index.html') })

const pdfRoute = require('./routes/pdfmake');
app.use('/pdfMake', pdfRoute);

app.listen(port, () => {
  console.log(`Server running at http://localhost:${port}/`);
});

My pdfmke.js:

const express = require('express');
const router = express.Router();
const fs = require('fs');

const pdfMake = require('pdfmake/build/pdfmake');
const pdfFonts = require('pdfmake/build/vfs_fonts');
pdfMake.vfs = pdfFonts.pdfMake.vfs;

router.post('/pdf', (req, res, next) => {
  const fname = req.body.fname;
  const lname = req.body.lname;

  var documentDefinition = { content: [`Hello ${fname} ${lname}, 'Nice to meet you!'`] };

  const pdfDoc = pdfMake.createPdf(documentDefinition);
  pdfDoc.getBase64((data) => {
    res.writeHead(200, {
      'Content-Type': 'application/pdf',
      'Content-Disposition': 'attachment;filename="filename.pdf"'
    });

    const download = Buffer.from(data.toString('utf-8'), 'base64');
    res.end(download);
  });
});

on my postman - when I am adding body - raw-json :

{ "fname": "test", "lname":"run" }

It returns:

"Hello undefined undefinedNice to meet you!"

Upvotes: 1

Views: 490

Answers (1)

biggs50
biggs50

Reputation: 31

Have you tried enclosing the variables using the backtick?

var documentDefinition = { content: [Hello \`${fname}\` \`${lname}\`, 'Nice to meet you!'], }

Upvotes: 0

Related Questions