eKoopmans/html2pdf.js

How to set document properties (meta) like title and keywords?

nipunadodan opened this issue · 2 comments

Since this is based on jsPDF which has a way to set properties, I believe there has to be a way to set properties when using html2pdf.js as well. But couldn't seem to find on the documentation. Any leads?

/* jsPDF way of setting meta data */

var doc = new jsPDF();
doc.text(20, 20, 'This PDF has a title, subject, author, keywords and a creator.');

// Optional - set properties on the document
doc.setProperties({
 title: 'Title',
 subject: 'This is the subject',
 author: 'Author Name',
 keywords: 'generated, javascript, web 2.0, ajax',
 creator: 'Creator Name'
});

you can do it like this

const properties = {
title: 'Title',
subject: 'This is the subject',
author: 'Author Name',
keywords: 'generated, javascript, web 2.0, ajax',
creator: 'Creator Name'
};

       // Generate the PDF
      html2pdf().set(opt).from(element).toPdf().get('pdf').then(pdf => {

        // Add the document properties to the generated PDF
        pdf.setProperties(properties);

        // Download the PDF
        pdf.save();
      });

Seems like the previous solution is not working great.
As I mainly tested it in the browser console, I didn't face the issue due to .toPdf being async.
Here's the latest solution that worked just fine for me in the app. (using v.0.9.3)

const worker = html2pdf(null, options).from(element);

const prereqs = [() => worker.prop.pdf || worker.toPdf()];

return worker.thenList(prereqs).then(() => {
  worker.prop.pdf.setProperties({
    title: filename,
    author: '',
    keywords: 'chat, thread, support',
    creator: '',
    subject: '',
  });

  return worker.saveAs(filename);
});

Also seems there's a difference in pdfjs API between 0.9.3 and 0.10.1 — In v0.10.1 you'd need to use .setDocumentProperties instead of .setProperties