I'm trying render a html template as a PDF using EJS, however the images are not appearing. My project structure:
- public
- images
image.jpg
- routes
documentsRoute.js
- services
documentsService.js
- views
document-template.ejs
server.js
I am setting the public folder as a static folder in my server.js like so:
...
const app = express()
app.use(express.static('public'))
...
In my template file I'm using this as my src for the image
<img src="images/image.jpg" alt="my_image">
I'm rendering the file from my document service like so:
ejs.renderFile('views/document-template.ejs', inputs, (err, data) => {
if (err){
throw err;
}
let options = {
"format": "A4",
"header": {
"height": "20mm"
},
"footer": {
"height": "20mm"
}
};
pdf.create(data, options).toFile('test.pdf', (err, res) => {
if(err){
throw err;
}
});
})
The rest of the template is rendered correctly, just not the image, instead it shows the alt text. Does anyone know how I could fix this?
CodePudding user response:
You need to set the view directory correctly in your server file.
So instead of app.use(express.static('public'))
try
app.use(express.static( path.join(__dirname, './public')))
CodePudding user response:
it's rather pdf
having trouble with the path. try using absolute path
add full path in the base
property of pdf
options:
let options = {
"format": "A4",
//...
base: `${req.protocol}://${req.headers.host}`
};