I have the below HTML:
<template>
<lightning-button onclick={generateData} label="Generate PDF"></lightning-button>
<iframe id="pdfFrame" src="/resource/pdfjs/web/viewer.html" width="100%" height="100%" class="pdfFrame"
onload={generateData}></iframe>
</template>
JS:
import { LightningElement } from 'lwc';
import { loadScript } from "lightning/platformResourceLoader";
import JSPDF from '@salesforce/resourceUrl/jspdf';
import getContacts from '@salesforce/apex/PdfGenerator.getContactsController';
export default class JspdfDemo extends LightningElement {
contactList = [];
headers = this.createHeaders([
"Id",
"FirstName",
"LastName"
]);
renderedCallback() {
Promise.all([
loadScript(this, JSPDF)
]);
}
generatePdf() {
const { jsPDF } = window.jspdf;
const doc = new jsPDF({
encryption: {
userPassword: "user",
ownerPassword: "owner",
userPermissions: ["print", "modify", "copy", "annot-forms"]
// try changing the user permissions granted
}
});
doc.text("Hi I'm Matt", 20, 20);
doc.table(30, 30, this.contactList, this.headers, { autosize: true });
doc.save("demo.pdf");
}
generateData() {
getContacts().then(result => {
this.contactList = result;
this.generatePdf();
});
}
createHeaders(keys) {
var result = [];
for (var i = 0; i < keys.length; i += 1) {
result.push({
id: keys[i],
name: keys[i],
prompt: keys[i],
width: 65,
align: "center",
padding: 0
});
}
return result;
}
}
This is the JS PDF librarythat I am using as a static resource:
After clicking the button it successfully downloads the PDF file.
But instead of downloading the file, I need to display the PDF file using iframe on salesforce I created iFrame tag in the HTML and tried below JS
this.template.querySelector('iframe').contentWindow.postMessage(this.pdfData, window.location.origin);
I tried passing blob or base64 as below
this.pdfData = doc.output('blob);
or
this.pdfData = new Blob([doc.output('blob')], { type: 'application/pdf' });
or
this.pdfData = doc.output('datauristring');
But the above did not work as expected, and also the generate PDF button doesn't work on salesforce 1 mobile app, can someone please suggest how to display the PDF on salesforce on both mobile and desktop view instead of downloading it. The other solution I am thinking of is saving this PDF to a content document and then use the content document to display the PDF file, but it would be a lot better if the iframe solution works so that we can eliminate server-side call.
Update:
I am not able to save the file to the content document also I have created another thread for that Saving PDF file to content document saves as black pages
screenshot of the page: