Giter VIP home page Giter VIP logo

vue-html2pdf's Introduction

VueHTML2PDF Documentation

Package Github:

https://github.com/kempsteven/vue-html2pdf

Please see the demo site and demo github for easier understanding of the usage of the package.

Demo Site:

https://vue-html2pdf-demo.netlify.com/

Demo Github:

https://github.com/kempsteven/vue-html2pdf-demo

vue-html2pdf

vue-html2pdf converts any vue component or element into PDF, vue-html2pdf is basically a vue wrapper only and uses html2pdf.js behind the scenes.

Table of contents

Getting started

NPM

Install vue-html2pdf and its dependencies using NPM with npm i vue-html2pdf

Migrating from 1.7.x to 1.8.x (and so on)

There are a few change in version 1.7x to 1.8.x and so on.

Events

1.7.x 1.8.x (and so on) Description
@hasStartedDownload @startPagination The event "hasStartedDownload" is now changed to "startPagination".
- @hasPaginated The event "hasPaginated" is an event triggered after pagination process is done.
- @beforeDownload The event "beforeDownload" is an event triggered before the PDF generation and downloading. The event arguments contains an object { html2pdf, options, pdfContent }, which can be used to have full control of html2pdf.js like e.g.(Add page count on each PDF page, Full control of jsPDF to design page, etc.), you will have to set the props :enable-download, :preview-modal to false so it will not generate the PDF.
@hasGenerated @hasDownloaded The event "hasGenerated" is now changed to "hasDownloaded".

Usage

import VueHtml2pdf from 'vue-html2pdf'

export default {
    methods: {
        /*
            Generate Report using refs and calling the
            refs function generatePdf()
        */
        generateReport () {
            this.$refs.html2Pdf.generatePdf()
        }
    },

    components: {
        VueHtml2pdf
    }
}

To use it in the template

<template>
   <div>
     <vue-html2pdf
        :show-layout="false"
        :float-layout="true"
        :enable-download="true"
        :preview-modal="true"
        :paginate-elements-by-height="1400"
        filename="hee hee"
        :pdf-quality="2"
        :manual-pagination="false"
        pdf-format="a4"
        pdf-orientation="landscape"
        pdf-content-width="800px"

        @progress="onProgress($event)"
        @hasStartedGeneration="hasStartedGeneration()"
        @hasGenerated="hasGenerated($event)"
        ref="html2Pdf"
    >
        <section slot="pdf-content">
            <!-- PDF Content Here -->
        </section>
    </vue-html2pdf>
   </div>
</template>

Using in Nuxtjs

// plugins/vue-html2pdf.js
import Vue from 'vue'
import VueHtml2pdf from 'vue-html2pdf'
Vue.use(VueHtml2pdf)
// nuxt.config.js
plugins: [
    { src: '@/plugins/vue-html2pdf', mode: 'client' }
],
<!-- on-component-usage.vue -->
<!-- you should add <client-only> tag -->
<!-- more info for client-only tag: https://nuxtjs.org/api/components-client-only/ -->
...
<client-only>
    <vue-html2pdf>
        <section slot="pdf-content">
        </section>
    </vue-html2pdf>
</client-only>
...

Props

This props can seen in the Usage Part

Props Options Description
show-layout true, false Shows the pdf-content slot, using this you can see what contents will be converted to PDF.
float-layout true, false Enabled by default. If the props is set to false The props show-layout will be overridden. The layout will not float and the layout will ALWAYS show.
enable-download true, false Enabled by default. When enabled the pdf will be downloaded and vise-versa.
preview-modal true, false Once you generate the pdf, PDF will be previewed on a modal, PDF will not be downloaded.
paginate-elements-by-height Any Number The number inputed will be used to paginate elements, the number will be in px units only.
manual-pagination true, false When enabled, the package will NOT automatically paginate the elements. Instead the pagination process will rely on the elements with a class "html2pdf__page-break" to know where to page break, which is automatically done by html2pdf.js
filename Any String The number inputed will be used to paginate elements, the number will be in px units only.
pdf-quality 0 - 2 (Can have decimal) 2 is the highest quality and 0.1 is the lowest quality, 0 will make the PDF disappear.
pdf-format a0, a1, a2, a3, a4, letter, legal, a5, a6, a7, a8, a9, a10 This are the PDF formats (Paper Sizes)
pdf-orientation portrait, landscape This are the PDF orientation
pdf-content-width Any css sizes (e.g. "800px", "65vw", "70%") This is the PDF's content width
html-to-pdf-options html-to-pdf-options details here This prop gives a way to configure the whole html2pdf.js options

html-to-pdf-options

Name Type Default Description
margin number or array 0 PDF margin (in jsPDF units). Can be a single number, [vMargin, hMargin], or [top, left, bottom, right].
filename string 'file.pdf' The default filename of the exported PDF.
image object {type: 'jpeg', quality: 0.95} The image type and quality used to generate the PDF. See Image type and quality.
enableLinks boolean false If enabled, PDF hyperlinks are automatically added ontop of all anchor tags.
html2canvas object { } Configuration options sent directly to html2canvas (see here for usage).
jsPDF object { } Configuration options sent directly to jsPDF (see here for usage).

IMPORTANT NOTE:

If you have set a value to this prop, the props below will be overridden:

'filename', 'pdf-quality', 'pdf-format', 'pdf-orientation'

Any value inputed to those props above will have no effect.

Sample Value of html-to-pdf-options

htmlToPdfOptions: {
    margin: 0,

    filename: `hehehe.pdf`,

    image: {
        type: 'jpeg', 
        quality: 0.98
    },

    enableLinks: false,

    html2canvas: {
        scale: 1,
        useCORS: true
    },

    jsPDF: {
        unit: 'in',
        format: 'a4',
        orientation: 'portrait'
    }
}

Events

This events can seen in the Usage Part

Events Description
@progress This will return the progress of the PDF Generation. The event argument contains the progress of the PDF generation process.
@startPagination This will be triggered on start of pagination process.
@hasPaginated This will be triggered after the pagination process.
@beforeDownload This will be triggered before the PDF generation and download. The event arguments contains an object { html2pdf, options, pdfContent }, which can be used to have full control of html2pdf.js like e.g.(Add page count on each PDF page, Full control of jsPDF to design page, etc.), you will have to set the props :enable-download, :preview-modal to false so it will not generate the PDF.
@hasDownloaded This will be triggered after downloading the PDF. The event arguments contains the Blob File of the generated PDF. This will NOT be trigerred if the props enable-download AND preview-modal is set to false.

Sample Use Case of @beforeDownload

This is a sample Use case of @beforeDownload event.

As you can see the event arguments contains a { html2pdf, options, pdfContent } destructured object. The arguments can used to have full control of the html2pdf.js process. See the Docs here

Below is a sample code to add a page number at the lower right on each PDF pages using the jsPDF package integrated in html2pdf.js.

NOTE that you will have to set the props enable-download and preview-modal to false so it will not generate any pdf. You will have to handle the downloading yourself.

Please refer to the html2pdf Docs to know the full details of the usage of html2pdf.js

<vue-html2pdf
    :show-layout="false"
    :float-layout="true"
    :enable-download="false"
    :preview-modal="false"
    filename="hehehe"
    :paginate-elements-by-height="1100"
    :pdf-quality="2"
    pdf-format="a4"
    pdf-orientation="portrait"
    pdf-content-width="800px"
    :manual-pagination="false"

    @progress="onProgress($event)"
    @startPagination="startPagination()"
    @hasPaginated="hasPaginated()"
    @beforeDownload="beforeDownload($event)"
    @hasDownloaded="hasDownloaded($event)"
    ref="html2Pdf"
>
    <pdf-content slot="pdf-content" />
</vue-html2pdf>
<script>
import VueHtml2pdf from 'vue-html2pdf'

export default {
    components: {
    VueHtml2pdf
    },

    methods: {
        async beforeDownload ({ html2pdf, options, pdfContent }) {
            await html2pdf().set(options).from(pdfContent).toPdf().get('pdf').then((pdf) => {
                const totalPages = pdf.internal.getNumberOfPages()
                for (let i = 1; i <= totalPages; i++) {
                    pdf.setPage(i)
                    pdf.setFontSize(10)
                    pdf.setTextColor(150)
                    pdf.text('Page ' + i + ' of ' + totalPages, (pdf.internal.pageSize.getWidth() * 0.88), (pdf.internal.pageSize.getHeight() - 0.3))
                } 
            }).save()
        }
    }
}

Slot

This slot can seen in the Usage Part

Slot Description
pdf-content Use this slot to insert your component or element that will be converted to PDF

Page Break

By adding an element with a class of html2pdf__page-break will add page break after that element.

Usage: This can still be used with the automatic pagination of the package or when the prop manual-pagination is enabled

Sample Usage:

<section slot="pdf-content">

    <section class="pdf-item">
        <h4>
            Title
        </h4>

        <span>
            Value
        </span>
    </section>

    <!--
        After this element below, the page will break and any elements after
        <div class="html2pdf__page-break"/> will go to the next page.
    -->
    <div class="html2pdf__page-break"/>

    <section class="pdf-item">
        <h4>
            Title
        </h4>

        <span>
            Value
        </span>
    </section>
</section>

Guide

The recommended format for the pdf-content

<section slot="pdf-content">
    <!--
        Divide your content into section, this pdf-item will
        be the element that it's content will not be separated
        in the paginating process. ex. <h4> and <span> wont be separated.
    -->
    <section class="pdf-item">
        <h4>
            Title
        </h4>

        <span>
            Value
        </span>
    </section>

    <!--
        All other pdf-item will be separated in the pagination process,
        depending on paginate-elements-by-height prop.
    -->
    <section class="pdf-item">
        <h4>
            Title
        </h4>

        <span>
            Value
        </span>
    </section>

    <!--
        If you have any image with a remote source
        set html2canvas.useCORS to true, although it is set to true by default
        Ex.
        html2canvas: {
            useCORS: true
        }
    -->
    <section class="pdf-item">
        <img :src="remoteImageLink">
    </section>
</section>

Known issues

As you can see on the description this package is mostly just a Vue.js wrapper for html2pdf.js, Below are known issues that comes along with html2pdf.js

  1. Rendering: The rendering engine html2canvas isn't perfect (though it's pretty good!). If html2canvas isn't rendering your content correctly, I can't fix it.

    • You can test this with something like this fiddle, to see if there's a problem in the canvas creation itself.
  2. Node cloning (CSS etc): The way html2pdf.js clones your content before sending to html2canvas is buggy. A fix is currently being developed - try out:

  3. Resizing: Currently, html2pdf.js resizes the root element to fit onto a PDF page (causing internal content to "reflow").

    • This is often desired behaviour, but not always.
    • There are plans to add alternate behaviour (e.g. "shrink-to-page"), but nothing that's ready to test yet.
    • Related project: Feature: Single-page PDFs
  4. Rendered as image: html2pdf.js renders all content into an image, then places that image into a PDF.

    • This means text is not selectable or searchable, and causes large file sizes.
    • This is currently unavoidable, however recent improvements in jsPDF mean that it may soon be possible to render straight into vector graphics.
    • Related project: Feature: New renderer
  5. Promise clashes: html2pdf.js relies on specific Promise behaviour, and can fail when used with custom Promise libraries.

    • In the next release, Promises will be sandboxed in html2pdf.js to remove this issue.
    • Related project: Bugfix: Sandboxed promises
  6. Maximum size: HTML5 canvases have a maximum height/width. Anything larger will fail to render.

    • This is a limitation of HTML5 itself, and results in large PDFs rendering completely blank in html2pdf.js.
    • The jsPDF canvas renderer (mentioned in Known Issue #4) may be able to fix this issue!
    • Related project: Bugfix: Maximum canvas size

License

The MIT License

Copyright (c) 2020 Kemp Sayson

Browser

Package has been tested in these browsers:

Chrome Version 85.0.4183.121 (Official Build) (64-bit)

Mozilla Firefox Version 80.0.1 (64-bit)

Microsoft Edge Version 85.0.564.63 (Official build) (64-bit)

Brave Version 1.14.84 Chromium: 85.0.4183.121 (Official Build) (64-bit)

Show your support

Give a ⭐️ if this project helped you! I get motivated if I get a star.

It's basically just like the stars we get when we were in preschool but for grown ups lol.

vue-html2pdf's People

Contributors

dependabot[bot] avatar kemp12322 avatar kempsteven avatar oppai1232 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

vue-html2pdf's Issues

Filename in preview modal

When viewing preview-modal and downloading from that PDF viewer the filename provided as a prop isn't used.

Is there a way to get the filename to be used when viewing and downloading from the preview modal?

doesn't work with nuxt

plugin:

import Vue from 'vue'
import VueHtml2pdf from 'vue-html2pdf'
Vue.use(VueHtml2pdf)

nuxt.config.js

  plugins: [
    '@/plugins/antd-ui',
    { src: '@/plugins/vue-apexcharts', ssr: false },
    { src: '@/plugins/vue-html2pdf', ssr: false }
  ]

somehow, sometimes works but most of the time the page freezes, and sometimes shows an error: window is not defined, even i use <no-ssr>

How should we use it when we are going to print the paper based on a set of HTML structures

hello vue-html2pdf author

I'm in the application vue-html2pdf plug-in We need to present our exam papers in terms of a set of HTML structures,
How do you move a question that is in the middle of two pages to the next page,
Print our test paper and PDF to make it look better

<vue-html2pdf :show-layout="false" :float-layout="true" :enable-download="true" :preview-modal="true" :paginate-elements-by-height="1400" filename="hee hee" :pdf-quality="2" :manual-pagination="false" pdf-format="a4" pdf-orientation="landscape" pdf-content-width="1140px" ref="html2Pdf" > <paper-show slot="pdf-content"/> </vue-html2pdf>

1111

Situation as above

From a VUE developer in China

jsPDF window is not defined

Hello guys, I have this error while using the package,
I guess this is came from jspdf

Im using nuxt by the way :)

{ ReferenceError: window is not defined
    at ../web/node_modules/jspdf/dist/jspdf.min.js:37:30237
    at module.exports (.../web/node_modules/jspdf/dist/jspdf.min.js:1:124)
    at Object.<anonymous> (.../web/node_modules/jspdf/dist/jspdf.min.js:1:128)
    at Module._compile (internal/modules/cjs/loader.js:701:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:712:10)
    at Module.load (internal/modules/cjs/loader.js:600:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:539:12)
    at Function.Module._load (internal/modules/cjs/loader.js:531:3)
    at Module.require (internal/modules/cjs/loader.js:637:17)
    at require (internal/modules/cjs/helpers.js:22:18)
    at Object.<anonymous> (.../web/node_modules/html2pdf.js/dist/require/html2pdf.cjs.js:10:29)
    at Module._compile (internal/modules/cjs/loader.js:701:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:712:10)
    at Module.load (internal/modules/cjs/loader.js:600:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:539:12)
    at Function.Module._load (internal/modules/cjs/loader.js:531:3) statusCode: 500, name: 'ReferenceError' }

Doesn't support <page> tag

Hi,

It seems the library doesn't support tag.
How can I force a page break please ?

Thanks for your help

Add custom fonts

I'm using the beforeDownload event to create extra pages on top of the document PDF generated by the vue-html2pdf

My issue is that I'm not able to add custom fonts.
I'm importing the file generated by the jsPDF documentation but It's not working.

Anyone made it work?

text based pdf

Hello sir,

Quick question on your library
Does this pdf generator have the ability to keep the text as text or does it turn everything into an image.
I have mostly text-based content I need to generate PDF's from, but I need the PDF's to be searchable after download

Any insight you can offer would be much appreciated.

Internet explorer 11 blank page

Hello, I have an issue loading my nuxt based site in IE11 just after installing and setting up the package.
It seems it won't accept the for...of command in the code...
You can reproduce this bug by using IE11 to visit the demo site.
Can you help me out ?
Thanks

Units passed to jsPDF, seems to have no effect

Describe the bug
When using the html-to-pdf-options prop, the jsPDF units options seems to have no and always assumes pt.

To Reproduce

    const htmlToPdfOptions = {
      jsPDF: {
        unit: "mm", //this seems to not do anything
        format: [86, 54], // this is passed, but assumes units in `pt`
        orientation: "landscape",
      },
    };

Package Version
1.8.0

Can't make it work in Nuxt SSR

Could you please make a replicate of the current demo in Nuxt? I just cannot make it work following the instructions.

  1. I've made the plugin file.
  2. I've included as a plugin with mode: 'client'
  3. I created a component with the options and the content and wrapped it into a "client-only" tag.
  4. called the generate PDF

The component:

<template>
  <client-only>
    <vue-html2pdf
      ref="html2Pdf"
      :show-layout="false"
      :float-layout="true"
      :enable-download="true"
      :preview-modal="true"
      :paginate-elements-by-height="1400"
      filename="hee hee"
      :pdf-quality="2"
      :manual-pagination="false"
      pdf-format="a4"
      pdf-orientation="landscape"
      pdf-content-width="800px"
      @progress="onProgress($event)"
      @hasStartedGeneration="hasStartedGeneration()"
      @hasGenerated="hasGenerated($event)"
    >
      <section slot="pdf-content">
        <MenuGrid v-if="activeMenu" :menu="activeMenu" />
      </section>
    </vue-html2pdf>
  </client-only>
</template>

<script>
import MenuGrid from '~/components/MainFoodMenu/MenuGrid.vue'
export default {
  components: {
    MenuGrid,
  },
  layout: 'nonApp',
  data() {
    return {
      output: null,
      activeMenu: '',
    }
  },
  async fetch() {
    this.activeMenu = this.$store.state.activeMenu
  },
  async mounted() {
    this.print()
  },

  methods: {
    print() {
      this.$refs.html2Pdf.generatePdf()
    },
  },
}
</script>

The nuxt config:

const colors = require('vuetify/es5/util/colors').default

module.exports = {
  head: {
    titleTemplate: '%s - ' + process.env.npm_package_name,
    title: process.env.npm_package_name || '',
    meta: [
      { charset: 'utf-8' },
      { name: 'viewport', content: 'width=device-width, initial-scale=1' },
      {
        hid: 'description',
        name: 'description',
        content: process.env.npm_package_description || '',
      },
    ],
    link: [{ rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }],
  },
  /*
   ** Customize the progress-bar color
   */
  loading: { color: '#fff' },
  /*
   ** Global CSS
   */
  css: ['~/assets/css/globalStyles.css'],
  plugins: ['~/plugins/firebase.js', { src: '~/plugins/vue-html2pdf.js', mode: 'client' }],

  buildModules: [
    '@nuxtjs/eslint-module',
    '@nuxtjs/vuetify',
    "@nuxtjs/date-fns"
  ],
  modules: [
    '@nuxtjs/axios',
    '@nuxtjs/dotenv',
  ],
  axios: {},
  serverMiddleware: [],
  vuetify: {
    customVariables: ['~src/assets/variables.scss'],
    theme: {
      themes: {
        light: {
          primary: '#53783B',
          accent: colors.grey.darken3,
          secondary: colors.amber.darken3,
          info: colors.teal.lighten1,
          warning: colors.amber.base,
          error: colors.deepOrange.accent4,
          success: colors.green.accent3,
        },
      },
    },
  },
  /*
   ** Build configuration
   */
  srcDir: 'src',
  buildDir: 'functions/.nuxt',
  build: {
    extend(config, ctx) {
      // Run ESLint on save
      if (ctx.isDev && ctx.isClient) {
        config.module.rules.push({
          enforce: 'pre',
          test: /\.(js|vue)$/,
          loader: 'eslint-loader',
          exclude: /(node_modules)/,
          options: {
            fix: true
          }
        })
      }
    },
    extractCSS: true,

  },
}

The errors:

image

What I've tried:

  • Importing VueHtml2pdf within the script tag and registering the component. I then get these errors:

image


  • adding it to transpile in the nuxt config:
  build: {
 
    transpile: ['vue-html2pdf']
  },
  • Nothing happens.

I really do not know what else to do, can you please help me? I don't seem to find any other example on how to apply it in Nuxt.

Thank you

[QUESTION] Close button destroys pdf object ?

I have a table like this:

Caption

When I click the last button in each row...a pdf is generated. Internally I send a request to an API with the corresponding id for each row. first time it prints all good. But when I click another button on different row...the content doesn't update, it just print the first pdf with the exact same data.

I checked the object that contains the data printed in pdf and it's changeing according to each row...so I don't know where is the problem. Here is some code. thanks for your help!

 export default {
    data () {
      return {
       desserts: [],
       }
  },
  components: {VueHtml2pdf},
  methods: {        
   generateReport (obj) {
      console.log(obj)
      this.desserts = obj;
      this.$refs.html2Pdf.generatePdf()
  }
},

}

   <vue-html2pdf
    :show-layout="false"
    :float-layout="true"
    :preview-modal="true"
    :paginate-elements-by-height="1600"
    filename="Presupuesto"
    :enable-download="false"
    :pdf-quality="2"
    :manual-pagination="false"
    pdf-format="letter"
    pdf-orientation="portrait"
    pdf-content-width="100%"

    @hasStartedGeneration="hasStartedGeneration()"
    @hasGenerated="hasGenerated($event)"
    ref="html2Pdf">

Practical question : how it works the "paginate-elements-by-height" property ?

Hello,

I'm not sure to understand the operation of "paginate-elements-by-height" property.
I have a page of 2424px of height containing some "<section>" :

section 1 : '121px' of height
section 2 : '495px' of height
section 3 : '311px' of height
section 4 : '84px' of height
section 5 : '156px' of height
section 6 : '553px' of height
section 7 : '455px' of height

(I had too some margins between sections ~ '250px')

My question is what value put in "paginate-elements-by-height" ?

An alternative question, is it possible to force all sections to be on a separate page ? Something like "page-break: auto" ?

Thanks for your help,
Regards

Only emit blob, no download

Great package! Very well built, my compliments. Is there any way to only emit the blob and prevent the download of the generated pdf?

Content is not splitted in pages.

Hi, I just found out that content is not being splitted. Also I've got a initial blank page.
Is there any way to solve this issues? I'm desperate!
I've got '#terms-and-conditions' where the content is.
Then I'll clone and append to :

    <vue-html2pdf
      ref="html2Pdf"
      :show-layout="false"
      :enable-download="false"
      :preview-modal="true"
      :paginate-elements-by-height="1400"
      filename="hee hee"
      :pdf-quality="0.8"
      pdf-format="a4"
      pdf-orientation="portrait"
      pdf-content-width="800px"
    >
      <div ref="pdfContainer" class="row" slot="pdf-content" />
    </vue-html2pdf>
 generatePdf() {
      const content = document.querySelector('#terms-and-conditions')

      this.$refs.pdfContainer.append(content)
      this.$refs.html2Pdf.generatePdf()

    },

No break page:
imatge

Initial blank page:
imatge

vue-html2pdf not working in pad/mobile view on Chrome.

Describe the bug
its working on Safari and firefox view but when i tried to open it on Chrome ipad or mobile view it just show a blank area of the content . plz see the attached image.

Google Chrome is up to date
Version 87.0.4280.88 (Official Build) (x86_64)

Screenshots
invoice bug

Package Version
"vue-html2pdf": "^1.8.0",

Display element only pdf

Hi !
I use the module for Nuxt, everything works perfectly, thank you.
I just had a problem, can we add elements in the DOM but only visible for the pdf generation?

Thanks,
Enzo

Can't load .svg images

I'm using vue-cli to serve an app on localhost:8888, the image shows when inside a normal component, no cors issues, but the same code doesn't work with vue-html2pdf.

<section slot="pdf-content">
    <img src="/svg/logo.svg" alt="logo" height="90px">
</section>
:html-to-pdf-options="{
     html2canvas: { useCORS: true}
} 

Why doesn't it work? anyone can provide a working example on how to load images.

Doesn't support <style> tag

Hi,

It seems the library doesn't support <style> tag.
How can I customize the style for print for exemple (I mean without use style attribute) ?

Thanks for your help

Page Break works great - still can't get margin's right.

Hey, thanks for the 1.6.0 update, page break works great. Still can't get margins right though. Any suggestions how how to get better top/bottom margins:

Screen Shot 2020-07-15 at 12 49 57 PM

I've tried playing with the data options, but the below does nothing:

 htmlToPdfOptions: {
                //margin: 0,
                margin: {
                  top: 0,
                  bottom: 60,
                  left: 0
                },

and I've also tried using CSS, but that just breaks the page break entirely where text disappears in between the pages:

Screen Shot 2020-07-15 at 1 01 46 PM

Attribute "paginate-elements-by-height" generate a bug

Hi,

Attribute "paginate-elements-by-height" generate a bug if it too small.
In this case, the browser freeze and the processus use 99% of processor.

I think it's a bug not catched. You could genrate a warning in the console.

Thanks for you work ;)

:paginate-elements-by-height not working as expected

Describe the bug
I set :manual-pagination="false" and :paginate-elements-by-height="700" (for example).
The elements do not move onto the next page after the height limit is reached.

To Reproduce
Here is a condensed copy of my Vue component, containing just the settings I'm using and 4 x 250px high elements.

Because the :paginate-elements-by-height property is 700, I would expect the third block to be on the next page as the total height for all 4 would be 1000px, and the total height for the first 3 to be 750px.

<template>
    <VueHtml2Pdf
        ref="pdf"
        class="mx-auto"
        :float-layout="false"
        :enable-download="true"
        :preview-modal="false"
        :htmlToPdfOptions="htmlToPdfOptions"
        pdf-content-width="960px"
        :manual-pagination="false"
        :paginate-elements-by-height="700"
    >
        <template slot="pdf-content">
            <div style="height: 250px; background: red;"></div>
            <div style="height: 250px; background: blue;"></div>
            <div style="height: 250px; background: green;"></div>
            <div style="height: 250px; background: orange;"></div>
        </template>
    </VueHtml2Pdf>
</template>

<script>
import VueHtml2Pdf from 'vue-html2pdf';

export default {
    components: {
        VueHtml2Pdf,
    },

    data() {
        return {
            htmlToPdfOptions: {
                margin: 0.5,
                filename: 'PaginateByHeight.pdf',
                image: {
                    type: 'jpeg',
                    quality: 1
                },
                enableLinks: false,
                html2canvas: {
                    scale: 4,
                    scrollX: 0,
                    scrollY: 0,
                    useCORS: true,
                    width: 960,
                },
                jsPDF: {
                    unit: 'in',
                    format: 'a4',
                    orientation: 'portrait'
                }
            }
        };
    },

    mounted() {
        this.$refs.pdf.generatePdf();
    }
}
</script>

Screenshots
image

Package Version
1.8.0

Additional context
The actual PDF I'm generating is somewhat more complicated, with many charts, but each chart is still in its own section and they have very similar heights (+-50px). The charts are being cut off which is why I need the pagination by height functionality.

Image with base64 support

I need to load image into the PDF from the API link, however since it doesn't support remote link, can we add support to base64 image?

Npm Build issue linked to Uglify-js

Describe the bug
The app runs great, exports pdfs but when I try to run 'npm run build' I get errors that are linked to the Uglify-js plugin that is a dependency of plugins which are dependencies of vue-html2pdf. So I won't be able to use it in production which is a real shame.

To Reproduce
Steps to reproduce the behavior:

  1. Create app and running with Visual Studio - works fine, exports pdf.
  2. npm run build give error attached:
Unexpected token name «of», expected punc «;» [17.bundle-v=2.0.14-0.js:1184,26]
npm ERR! code ELIFECYCLE
npm ERR! errno 2
npm ERR! [email protected] build: `cross-env NODE_ENV=production webpack --progress --hide-modules`
npm ERR! Exit status 2
npm ERR!
npm ERR! Failed at the [email protected] build script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\HWS05\AppData\Roaming\npm-cache\_logs\2020-11-03T12_14_00_333Z-debug.log

I then tried in a new app:

  1. deleted node modules (using 'rimraf node_modules' command)
  2. deleted my package-lock.json file
  3. deleted all files from %temp% folder
  4. Shut down laptop
  5. Restart laptop
  6. npm install
  7. npm i vue-html2pdf
  8. npm run dev (no error)
  9. npm run build - same error

Package Version
1.8.0

Text not breaking correctly between pages

Describe the bug
I'm splitting up all my sections like it says to do but I can't seem to split up the text between pages.

To Reproduce
Steps to reproduce the behavior:

      <template slot="pdf-content">
        <section id="pdf-content" class="pdf-content">
...

          <section class="pdf-item">
            <v-row style="padding: 10px">
              <v-col cols="10" style="text-align: justify">
                Lorem Ipsum is simply dummy text of the printing and
                typesetting industry. Lorem Ipsum has been the
                industry's standard dummy text ever since the 1500s,
                when an unknown printer took a galley of type and
                scrambled it to make a type specimen book. It has
                survived not only five centuries, but also the leap
                into electronic typesetting, remaining essentially
                unchanged. It was popularised in the 1960s with the
                release of Letraset sheets containing Lorem Ipsum
                passages, and more recently with desktop publishing
                software like Aldus PageMaker including versions of
                Lorem Ipsum.
              </v-col>
            </v-row>
          </section>

...
        </section>
      </template>
    <vue-html2pdf
      :show-layout="false"
      :float-layout="false"
      :enable-download="false"
      :preview-modal="true"
      :paginate-elements-by-height="1400"
      filename="hee hee"
      :pdf-quality="2"
      :manual-pagination="false"
      :html-to-pdf-options="htmlToPdfOptions"
      pdf-format="a4"
      pdf-orientation="landscape"
      pdf-content-width="800px"
      ref="html2Pdf"
    >

Screenshots
image

Package Version
1.8.0

Weird space at starting of PDF

When Generate pdf after scrolling some part of visible content of data, PDF get unexpected weird space on top.
But when generating PDF without scrolling, It works great.

hee hee (2).pdf

"vue-html2pdf": "^1.8.0",
"vue": "^2.6.10",

Here I am uploaded generated PDF from your given demo. When I scroll some content of data and generate the PDF, it got some space on top of Pdf (Refer the attached PDF). But when generate the Pdf without scrolling, It works great.

Uknown padding left in landscape mode

First of all I would like to thank you for your software, it actually saved me in my work. I had a great time generating pdf's in portrait mode, no problems. But when I try to generate in landscape, the layout preview looks fine, but the generated pdf comes with a padding left that I can't get rid off

<vue-html2pdf :show-layout="true" :enable-download="true" :preview-modal="true" :paginate-elements-by-height="3000" filename="file" :pdf-quality="2" pdf-format="a4" pdf-orientation="landscape" pdf-content-width="1123px" @hasGenerated="$emit('generated', $event)" >

The layout I'm passing is just a section with width 100% and height 794px aligning some text. Some images:

Layout:

layout

Preview:

preview

bring back @hasGenerated

The hasDownloaded is not a valid replacement for my usecase.

I just need the old @hasGenerated(blob) function with nothing else, because the code will handle the rest.

I don't want any kind of automatic download and setting enable-download = false, doesn't trigger beforeDownload so I have no way to intercept the pdf blob and cancle the download event after that.

I think @hasGenerated can still be a valid alternative to @hasDownloaded and both can cooexist.

Can the component act as a wrapper?

Firstly thank you for providing this repository, which I've found very helpful.

This isn't a bug/code issue but I wasn't sure the best place to ask.

In my Vue file, I have a heap of content:

<template>

  // lots of Vue content

</template>

I want to use vue-html2pdf and wrap the existing content, is that possible? I've tried using it as an outer wrapper for content it does not render/show my Vue code inside the element.. The only way I've been able to use it so far is like so:

<template>
  <div>
    <div>Lots of Vue Content</div>
  
    <vue-html2pdf>
          Lots of Vue content (a copy/paste of the above code, line for line)
    </vue-html2pdf>
  </div>
</template>

Is there something I have to do with the props to get it to wrap and display the content inside the wrapper? As it happens, I'm having to copy and paste my code and that's not very D.R.Y.

The show-layout props seems to cause the content to float above the page, but I just want to render the Vue code

Progress always showing 70%

I am generating a pdf with 13 sections (charts), and it would be great if the progress matched the generated sections, or something like this. It is possible?

Confirm Licencing

This is a great library. Sorry to be a pain, but can you confirm the licence for use. Thank you

Blank PDF Created

I've just copied and pasted the examples and I'm not getting diddly.. Just a blank page.. Any ideas?

Here is my code:

 `<div>
    <vue-html2pdf
      :show-layout="false"
      :float-layout="true"
      :enable-download="true"
      :preview-modal="true"
      :paginate-elements-by-height="1400"
      filename="hee hee"
      :pdf-quality="2"
      :manual-pagination="false"
      pdf-format="a4"
      pdf-orientation="landscape"
      pdf-content-width="800px"
      @progress="onProgress($event)"
      @hasStartedGeneration="hasStartedGeneration()"
      @hasGenerated="hasGenerated($event)"
      ref="html2Pdf"
    >
      <section slot="pdf-content">
          <h4>
              Title
          </h4>

          <span>
              Value
          </span>
      </section>
    </vue-html2pdf>
  </div>`

And then the method
generateReport() { this.$refs.html2Pdf.generatePdf() }

I've included it as a component:
components: { VueHtml2pdf },

and it imports fine
import VueHtml2pdf from 'vue-html2pdf'

I am using Vuetify if that makes a difference.. But other than that I'm at a loss?

Blank pdf when using table in section

I used table in pdf-content slot and when I generate the pdf, its all blank.

<vue-html2pdf
        :show-layout="false"
        :float-layout="true"
        :enable-download="false"
        :preview-modal="true"
        filename="hehehe"
        :paginate-elements-by-height="1100"
        :pdf-quality="2"
        pdf-format="a4"
        pdf-orientation="portrait"
        pdf-content-width="800px"
        :manual-pagination="false"
        ref="html2Pdf"
    >
    <section slot="pdf-content">
    <table>
      <thead>
       <th></th>
      </thead>
    </table>
</table>
</vue-html2pdf>

When we click on close button from modal it popups again and again..

download () {
 this.$refs.html2Pdf.generatePdf()
}

using this method with example template you given ..

<template>
   <div>
     <vue-html2pdf
        :show-layout="false"
        :enable-download="true"
        :preview-modal="true"
        :paginate-elements-by-height="1400"
        filename="hee hee"
        :pdf-quality="2"
        :manual-pagination="false"
        pdf-format="a4"
        pdf-orientation="landscape"
        pdf-content-width="800px"

        @progress="onProgress($event)"
        @hasStartedGeneration="hasStartedGeneration()"
        @hasGenerated="hasGenerated($event)"
        ref="html2Pdf"
    >
        <section slot="pdf-content">
            <h1>hello</h1>
        </section>
    </vue-html2pdf>
   </div>
</template>

styles not working

No idea why, on preview-modal looks fine, but after generating I get plain text pdf :/ Also it doesn't work only on web server, when I run project on localhost, styles works.

Image is still blocked by CORS

Hi @kempsteven ,
This issue still happened when I add an image to a pdf.
Here is the code.

<vue-html2pdf
        :show-layout="true"
        :float-layout="false"
        :enable-download="false"
        :preview-modal="true"
        :paginate-elements-by-height="1400"
        filename="hee hee"
        :pdf-quality="2"
        :manual-pagination="false"
        pdf-format="a4"
        pdf-orientation="landscape"
        :pdf-content-width="800"
        :html-to-pdf-options="htmlToPdfOptions"
        ref="html2Pdf">
        <section slot="pdf-content">
            <!-- PDF Content Here -->
      <img
          class="user-image"
          src="https://tikupic.21cnjy.com/2b/8e/2b8e0f8dc3583052c96be88209fe094c.png"
          alt="User Image"
          ref="userImage"
        />
        </section>
    </vue-html2pdf>
computed: {
    htmlToPdfOptions() {
      return {
        html2canvas: {
          taintTest: true,
          useCORS: true
        }
      }
    }
  }

This image displays well on my website,
image
but does not work well when I try to export PDF.
Here is the error message.
error-msg

So, would you help me to check this issue? In my opinion, this issue still belongs to CORS.
THX

Originally posted by @missingeverytime in #20 (comment)

Adding margin to options cut text in half

After adding margin (say 10 on 4 side) to options, sometimes text get cut off. I tried using the .pdf-item but doesn't seems to be working. Whats the best way to resolve this?

WhatsApp Image 2020-07-06 at 12 44 06

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.