How can I generate base64 to pdf?

820    Asked by DavidEDWARDS in Salesforce , Asked on May 27, 2024

 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 a pdf file.
            })
    }
}
HTML:

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 ideas? Thank you so much.

Answered by David Piper

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


var element = document.createElement('a');
element.setAttribute('href', [removed] + 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.


Your Answer

Answer (1)

To generate a PDF from a Base64 encoded string in Java, you can follow these steps:

  • Decode the Base64 String: Convert the Base64 string into a byte array.
  • Write the Byte Array to a PDF File: Use FileOutputStream to write the byte array to a file with a .pdf extension.

Here's a complete example in Java:

Step-by-Step Guide





Decode Base64 String:

Use java.util.Base64 to decode the Base64 string.

Write Byte Array to PDF File:

Use FileOutputStream to write the byte array to a file.

Java Code Example

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Base64;

public class Base64ToPdf {
    public static void main(String[] args) {
        // Base64 encoded string (example, replace with your actual Base64 string)
        String base64String = "JVBERi0xLjQKJaqrrK0KNCAwIG9iago8PC9UeXBlIC9QYW..."; // shortened for brevity
        // Specify the path where the PDF will be saved
        String pdfFilePath = "output.pdf";
        // Decode the Base64 string
        byte[] pdfBytes = Base64.getDecoder().decode(base64String);
        // Write the byte array to a PDF file
        try (FileOutputStream fos = new FileOutputStream(pdfFilePath)) {
            fos.write(pdfBytes);
            System.out.println("PDF file created successfully: " + pdfFilePath);
        } catch (IOException e) {
            System.err.println("Error writing PDF file: " + e.getMessage());
        }    }
}

Explanation

Base64 Encoded String:





Replace base64String with your actual Base64 encoded PDF string. Ensure it is a valid Base64 string representing the PDF content.

Decoding Base64:

Base64.getDecoder().decode(base64String) converts the Base64 encoded string into a byte array.

Writing to PDF:

FileOutputStream is used to write the byte array to a file named output.pdf.

The try-with-resources statement ensures that the FileOutputStream is closed automatically after the operation.

Handling Edge Cases

Invalid Base64 String: If the Base64 string is invalid or corrupted, Base64.getDecoder().decode will throw an IllegalArgumentException. You can catch this exception to handle errors gracefully. File Write Errors: If there are issues with file permissions or disk space, the FileOutputStream operations might throw an IOException. Handling these exceptions ensures your program can react appropriately to such issues.

Full Example with Exception Handling

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Base64;



public class Base64ToPdf {
    public static void main(String[] args) {
        // Base64 encoded string (example, replace with your actual Base64 string)
        String base64String = "JVBERi0xLjQKJaqrrK0KNCAwIG9iago8PC9UeXBlIC9QYW..."; // shortened for brevity
        // Specify the path where the PDF will be saved
        String pdfFilePath = "output.pdf";
        try {
            // Decode the Base64 string
            byte[] pdfBytes = Base64.getDecoder().decode(base64String);
            // Write the byte array to a PDF file
            try (FileOutputStream fos = new FileOutputStream(pdfFilePath)) {
                fos.write(pdfBytes);
                System.out.println("PDF file created successfully: " + pdfFilePath);
            }
        } catch (IllegalArgumentException e) {
            System.err.println("Invalid Base64 string: " + e.getMessage());
        } catch (IOException e) {
            System.err.println("Error writing PDF file: " + e.getMessage());
        }
    }
}

This approach ensures your program handles errors gracefully and provides useful feedback if something goes wrong.

4 Months

Interviews

Parent Categories