eKoopmans / html2pdf.js

Client-side HTML-to-PDF rendering using pure JS.
MIT License
4.05k stars 1.37k forks source link

How to manipulate document before render #333

Open emahuni opened 4 years ago

emahuni commented 4 years ago

I have been digging around to find a solution to this and was disappointed that I could find none. Here is my solution after going through html2pdf code. Unfortunately they don't document the lib very concisely and this is why we are glob-trotting looking for answers like this.

import $ from 'jquery';
html2pdf()
        .set({
          margin:      [10, 10],
          filename:    `blah.pdf`,
          // don't use html2canvas onclone, it doesn't work
        })
        .from('source')
        .toContainer()
        .then(()=>{
          const doc = $('.html2pdf__container');
          doc.find('.remove-on-export').remove();
          doc.find('.hide-on-export').hide(); // or or add / remove classes
          doc.find('.show-on-export').show(); // or add / remove classes
        })
        .save();

This enables me to manipulate the document however I like as you would with onclone.

dannio commented 4 years ago

My solution was to clone the element and add a class to it, then assign a different set of css rules to that class.

e.g:

  var element = document.getElementById('element-to-pdf').cloneNode(true);
  element.classList.add("pdf-format");
  html2pdf(element, {
    filename:     'html2pdf.pdf',
    image:        { type: 'jpeg', quality: 1 }
  })