I'm new to Next.js, and I'm trying to use wkhtmltoimage but I can't seem to send the generated image stream as a response in my Next.js API.
const fs = require('fs')
const wkhtmltoimage = require('wkhtmltoimage').setCommand(__dirname + '/bin/wkhtmltoimage');
export default async function handler(req, res) {
try {
await wkhtmltoimage.generate('<h1>Hello world</h1>').pipe(res);
res.status(200).send(res)
} catch (err) {
res.status(500).send({ error: 'failed to fetch data' })
}
}
I know I'm doing plenty of stuff wrong here, can anyone point me to the right direction?
Since you're concatenating
__dirname
and/bin/wkhtmltoimage
together, that would mean you've installed the wkhtmltoimage executable to./pages/api/bin
which is probably not a good idea since thepages
directory is special to Next.js.We'll assume you've installed the executable in a different location on your filesystem/server instead (e.g., your home directory). It looks like the
pipe
function already sends the response, so theres.status(200).send(res)
line will cause problems and can be removed. So the following should work: