1

I want to create a LWC to download a simple PDF file with a random string. Here is my code:

Apex Class:

public with sharing class PdfLwcController {
    @AuraEnabled
    public static String getBase64String() {
        String s = 'Hello World!';
        
        return EncodingUtil.base64Encode(Blob.toPdf(s));
    }
}

Client-side controller:

import { LightningElement } from 'lwc';
import getBase64String from '@salesforce/apex/PdfLwcController.getBase64String';

export default class PdfButton extends LightningElement {
    handleClick() {
        getBase64String({})
            .then(response =>{
                // I don't know how to generate and download pdf file.
            })
    }
}

HTML:

<template>
    <lightning-card title="Downloading Pdf Demo">
        <lightning-button label="Neutral" title="Non-primary action" onclick={handleClick} class="slds-m-left_x-small"></lightning-button>
    </lightning-card>
</template>

The Server-side controller can return a Base64 String, but I don't know how to generate the PDF file and download it immediately (don't save it to the attachment or file). Do you have any idea? Thank you so much.

2 Answers 2

4

I've solved the problem. Here is the change in client-side controller:

let element = document.createElement('a');
element.setAttribute('href', 'data:application/pdf;base64,' + response);
element.setAttribute('download', 'myzip.pdf');

element.style.display = 'none';
document.body.appendChild(element);

element.click();

document.body.removeChild(element);

Thanks @Rory for the advice.

1
  • This is a great solution, nice find! Just thought I'd add that the element variable can be declared with const rather than let as it's not being reassigned. Thanks! Nov 16, 2023 at 17:40
1

I have done something similar but for zip files. Here was the code I used.

var element = document.createElement('a');
element.setAttribute('href', 'data:text/plain;base64,' + zipfile_blob);
element.setAttribute('download', 'myzip.zip');

element.style.display = 'none';
document.body.appendChild(element);

element.click();

document.body.removeChild(element);

You should be able to modify this to download as a PDF instead of a zip.

2
  • Hey man, I've tried it but it's failed to download (Download action is worked but it said Failed - Network error).
    – Tran Tai
    Jul 1, 2022 at 0:58
  • I've solved the problem, thanks for your hint.
    – Tran Tai
    Jul 1, 2022 at 3:24

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .