[SalesForce] LWC download PDF file

I use LWC components in Customer Community.
There is datatable component with records and I implemented the function to export selected records in .csv and .pdf.

csv works fine, but I experience the next issue when downloading the file as pdf:
enter image description here

Here is the code I use to create and download the file:

main.js

handleExportAction(evt) {
    const selectedFormat = evt.detail.value;
    try {
        let _file;
        let _type;
        switch (selectedFormat) {
            case 'csv':
                _file = parseToCSV(this.columns, this.selectedRows);
                _type = 'text/html';
                break;
            case 'pdf':
                _file = parseToPDF(this.columns, this.selectedRows);
                _type = 'application/pdf';
                break;
            default:
                _file = undefined;
                _type = undefined;
        }
        downloadDataAsFile('Subscription Overview.' + selectedFormat, _type, _file);
    } catch(e) {
        console.error(e);
    }
}

service.js – parse&donwloadFile functions

const parseToPDF = (tableCols, rows) => {
    let cols = [];
    tableCols.filter(el => cols.push('<th>' + el.label));

    let fileData = '<html><head>';
    fileData += '<title>Subscription Overview</title>';
    fileData += '<body><table>';
    fileData += '<tr>';
    fileData += cols.map(col => col).join('</th>') + '</th>';
    fileData += '</tr>';
    fileData += '<tr>';
    fileData += '<td>Test Data</td>';
    fileData += '</tr>';
    fileData += '</body></html>';
    console.log('file: ' + fileData);

    return fileData;
};

const downloadDataAsFile = (name, type, data) => {
var file = new Blob([data], { type: type });
if (window.navigator.msSaveOrOpenBlob) { // IE10+
    window.navigator.msSaveOrOpenBlob(file, filename);
} else { // Others
    var a = document.createElement("a"),
        url = URL.createObjectURL(file);
    a.href = url;
    a.download = name;
    document.body.appendChild(a);
    a.click();
    setTimeout(function () {
        document.body.removeChild(a);
        window.URL.revokeObjectURL(url);
    }, 0);
}
};

The body (fileData) variable is for testing purposes, I tried other options but the result was the same.

Probably the issue is in contentType which I set as application/pdf?

I did not find any limitations related to creating pdf files with js.
Did someone experienced this issue before?

Thanks in advance.

Best Answer

HTML is not a valid PDF content, this is why you can't open the generated file.

Because of the complexity of the PDF specification, I would recommend using existing javascript libraries like pdfkit or use APIs to generate PDFs.

Related Topic