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.
- 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());- 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.

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.
- Convert String To Lowercase And Uppercase In Salesforce Apex
- Convert a String to Decimal in Salesforce Apex
- Convert String to Boolean in Salesforce Apex
- Convert String to Date in Salesforce Apex
I am Bijay Kumar, the founder of SalesforceFAQs.com. Having over 10 years of experience working in salesforce technologies for clients across the world (Canada, Australia, United States, United Kingdom, New Zealand, etc.). I am a certified salesforce administrator and expert with experience in developing salesforce applications and projects. My goal is to make it easy for people to learn and use salesforce technologies by providing simple and easy-to-understand solutions. Check out the complete profile on About us.