Node-html-pdf: Generate a PDF using VueJS

Created on 7 Mar 2017  路  3Comments  路  Source: marcbachmann/node-html-pdf

First of all this is not an issue and I don't know where to ask questions.

In the documentation, the simplest way to do this is:

var html = fs.readFileSync('./test/somefile.html', 'utf8');
var options = { format: 'Letter' };

But what if i want it to have a data coming from my database? I am using vuejs and planning on passing some data to it. Is it possible?

Any suggestion would be much appreciated.

Most helpful comment

the same question , how to use it in vue project , did you solve it?

All 3 comments

app.render('orderInvoiceTemplate', {order:order, layout:false}, function (err, html) { pdf.create(html).toStream(function (err, stream) { if (err) { console.log(err); return res.send(err); } res.type('pdf'); stream.pipe(res); }); });

I'm doing this when using express-handlebars. You will have to look for something in the lines of this: "vuejs render to string/variable" etc. or look for som way to use phantomjs to save rendered html with js

the same question , how to use it in vue project , did you solve it?

I'm not a pro. But this is how i solved it.

import { Router } from 'express'
import fs from 'fs'
import pdf from 'html-pdf'
import Vue from 'vue'

import { createRenderer } from 'vue-server-renderer'

const router = Router()

router.get('/pdf', async function(req, res, next) {
  const options = { format: 'A4' }

  try {
    const renderer = createRenderer({ template: require('fs').readFileSync('src/rest/index.template.html', 'utf-8') })
    const template = fs.readFileSync('src/rest/template.html', 'utf8')

    const vm = new Vue({
      data() {
        return {
          hello: 'world',
          persons: [{ name: 'slavi' }, { name: 'chris' }],
        }
      },
      template,
    })
    const html = await renderer.renderToString(vm, {})

    pdf.create(html, options).toBuffer(function(err, buffer) {
      if (err) return console.log(err)

      res.contentType('application/pdf')
      res.send(buffer)
    })
  } catch (error) {
    console.log(error)
  }
})

export default router

My template.html:

<div>
  <div>{{ hello }}</div>

  <ul>
  <li v-for="person in persons">{{ person.name }}</li>
  </ul>
</div>
Was this page helpful?
0 / 5 - 0 ratings

Related issues

jimit-hothi picture jimit-hothi  路  4Comments

B-StS picture B-StS  路  5Comments

cmoulliard picture cmoulliard  路  3Comments

aminjoharinia picture aminjoharinia  路  4Comments

antiframes picture antiframes  路  4Comments