0

I am working on a functionality in a Vuejs project, by which by clicking on a button, the user can export a pdf which will contain certain Vuejs components. All went smooth up to a point. I npm installed the 2 packages, jsPDF and html2canvas (which is a dependency). I added jsPDF to the component like so:

import jsPDF from 'jspdf'

The function that gets triggered on button click is:

exportpdf() {
    let pdf = new jsPDF('p', 'px', 'a4')
    pdf.addHTML(this.$refs.userinfo, function() {
         pdf.save('web.pdf')
    })
}

When the function was triggered on button click, I got the following error:

Uncaught (in promise) Error: You need either https://github.com/niklasvh/html2canvas or https://github.com/cburgmer/rasterizeHTML.js...

And so, I got to this issue here: Using jsPDF and html2canvas with es6 which explains that jsPDF requires html2canvas to be on the window. But this is just a huge no no in Vuejs (see article here): https://vuejsdevelopers.com/2017/04/22/vue-js-libraries-plugins/

So, inspired by this article, I added the html2canvas package to main.js:

import html2canvas from 'html2canvas'
...
Vue.use(html2canvas)

Now, when the function is triggered I get this:

Uncaught (in promise) Provided element is not within a Document

I also tried with document.querySelector('#userinfo') - same result. So now I consider myself officially stuck - any help is greatly appreciated.

1 Answer 1

1

html2canvas is not a Vue plugin, so you cannot call use(...) on it.

You can make your own plugin though.

import html2canvas from 'html2canvas'

let MyPlugin = {
  install(Vue, options) {
    window.html2canvas = html2canvas
  }
}

// ...
Vue.use(MyPlugin)

I am not really sure why you are opposed to window.html2canvas = html2canvas if another library needs it.

Sign up to request clarification or add additional context in comments.

2 Comments

OK, I understand and indeed, I cannot use it (I'm new to Vuejs). But the whole idea here was to avoid assigning html2canvas to the window object. I don't see how this solves the issue, only that it wraps the assignment in a plugin.
You seemed to want to 'encapsulate the fix' code in a plugin per your example and external reference... If jsPDF expects a global window object, there is nothing wrong with assigning it. This is not a 'Vue' issue at all.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.