toPDF() function in Apex
Blob.toPdf() is an Apex method introduced in Spring ’26 that allows developers to convert HTML content directly into a PDF as a Blob. It provides a native way to generate PDFs within Apex, eliminating the dependency on Visualforce pages. With support for modern styling, it’s well-suited for generating invoices, reports, and automating document creation.
Key points of Blob.toPdf()
- Usage: Accepts an HTML string as input and returns a Blob containing the generated PDF data.
- Rendering Engine: Built on the same reliable Visualforce PDF engine, ensuring consistent layout, improved font rendering, and support for international characters.
- Implementation: Commonly paired with ContentVersion to save generated PDFs as Salesforce Files.
- Native Conversion: Directly transforms HTML content into PDF format without requiring intermediate steps.
- No Visualforce Required: Unlike PageReference.getContentAsPdf(), this method does not rely on a Visualforce page, resulting in cleaner and more efficient code.
- Asynchronous Compatibility: Fully supported in asynchronous Apex contexts such as Batch, Queueable, and Scheduled Apex, removing earlier limitations.
- Unit Test Friendly: Can be executed within test classes, allowing validation of PDF output without using Test.isRunningTest() conditions.
- CSS Support: Supports inline CSS styling, leveraging the Visualforce rendering engine for well-formatted and visually appealing PDFs.
Advantages over traditional methods
- No Visualforce Dependency: Eliminates the need to create and maintain Visualforce pages with renderAs="pdf".
- Backend Compatible: Works seamlessly across backend processes, including Batch, Queueable, Scheduled Apex, and Triggers.
- Simplified Development: Reduces overall code complexity for generating dynamic documents.
Syntax:
Blob pdfBlob = Blob.toPdf(htmlString)Example:
Account acc = [SELECT Id FROM Account WHERE Name='Test Acc' LIMIT 1]; String htmlbody = '<html><body>Salesforcescool blog-Helps you to learn about salesforce,apex,LWC and many more things that belongs to salesforce ecosystem.</body></html>'; // generated using Blob.toPdf() Blob pdfBlob = Blob.toPdf(htmlbody); //Saving blob value of html as pdf in files ContentVersion pdfFile = new ContentVersion(); pdfFile.Title = 'MyPDF.pdf'; pdfFile.PathOnClient = 'MyPDF.pdf'; pdfFile.VersionData = pdfBlob; pdfFile.IsMajorVersion = true; pdfFile.FirstPublishLocationId = acc.Id; insert pdfFile;Output:
Hope you like this post, for any feedback or suggestions please feel free to comment. I would appreciate your feedback and suggestions.


0 Comments
Post a Comment