Try to search your question here, if you can't find : Ask Any Question Now ?

wkhtmltopdf response in a buffer

HomeCategory: stackoverflowwkhtmltopdf response in a buffer
Avatarrupesh asked 5 days ago

So, I have written a small code to convert the html string in to pdf using the library called Wkhtmltopdf

Here is the code I have written:

index.js

const express = require('express')
const app = express()
app.use(express.json())
const port = 3000
const compiledHtml = '<h1> This is testing </h1>'
app.post('/gc', async (req, res) => {
   wkhtmltopdf(compiledHtml, {
      pageSize: 'A4',
      orientation: 'Landscape',
      marginLeft: '1mm',
      marginTop: '1mm'
   }).pipe(fs.createWriteStream('out.pdf')) //--->(A)
   console.log('All done')
   res.send(compiledHtml)
})
app.listen(port, () => console.log(`Example app listening on port ${port}!`))

In this code, I have created REST call, POST in nature that generates the pdf and saves in a file named out.pdf (equation (A), above) in the same folder where the script is running.

But in reality I want to generate the pdf in memory, gets the buffer of the same and return the buffer back to the client so that the browser start downloading the file, I have a code as well for that, here is the code to return the buffer in response in express

snippet

......
......
res.writeHead(200, {
  'Content-Type': 'application/pdf',
  'Content-disposition': 'attachment;filename=certificate.pdf',
  'Content-Length': buffer.length,
})
res.end(buffer)
......
......

Via above code we can written the binary data back to the client, which he can save it where-ever he wants to.

But the main problem is how do I get the buffer of the file being generated.

Please shed some light, happy coding 🙂

1 Answers
Best Answer
AvatarArben answered 5 days ago
Your Answer

11 + 8 =

Popular Tags

WP Facebook Auto Publish Powered By : XYZScripts.com