How to Convert String to Blob in Salesforce Apex

In Salesforce, a Blob is a collection of binary data stored as a single object. We can convert this data type to or from a String using the toString and valueOf methods, respectively.

Recently, while developing an Apex class to generate a text file with content and store it in Salesforce as an attachment or file, I realized the need to save the file as a text file and store it in Salesforce as a file attachment.

As a solution for this, I converted the String to a blob. In the steps below, I will explain how to convert a string to a blob in Salesforce Apex.

Convert String to Blob in Salesforce Apex

To convert a string to a blob in Salesforce Apex, we will use the Blob.valueof() function. I will explain the method in the steps below.

  1. Open the Apex anonymous window and enter the code below.
String blbString = 'Pdf Document';

Blob strBlob = Blob.valueOf(blbString);

System.debug('Blob length: ' + strBlob.size());
  1. After entering the code, select the checkbox Open in debug, then click on the Execute button.
    • In the Console log window, select the object to debug only. You will then see that the string is converted to a blob data type. Using the .size() function, we display the length of the blob.
Convert string to blob in Salesforce apec

In this way, we can convert the string to a blob in Salesforce Apex by using the valueOf(string) function.

By now, you will be able to convert a string data type to a blob in Salesforce Apex by using the Blob.valueOf(blbString) function.

You may also like to read.

4 Hours Live Workshop

BUILD YOUR AI CRM ASSISTANT WITH AGENTFORCE

Build a Smart AI-Powered CRM Assistant with Agentforce in Just 4 Hours—Hands-On, Live, and Ready for Real-World Use!

27 August 2026 | 7 PM to 11 PM IST | 9:30 AM to 1:30 PM EST

Early Bird: $9 – First 15 Seats

Agentforce in Salesforce

DOWNLOAD FREE AGENTFORCE EBOOK

Start with AgentForce in Salesforce. Create your first agent and deploy to your Salesforce Org.