Loading

Display a Blob as a PDF in a Salesforce Visualforce Page Using Base64 Encoding

Veröffentlichungsdatum: May 4, 2026
Beschreibung

In Salesforce Visualforce, if a PDF file is stored as a Blob value in an Apex controller — for example, as an Attachment Body field — it can be rendered inline in a Visualforce page using a data: URI with Base64 encoding. The EncodingUtil.Base64Encode() Apex method converts the Blob to a Base64 string, which is then used as the src attribute of an <iframe> element in the Visualforce page.
Important browser limitations: The data: URI scheme is not supported in all browsers. Internet Explorer does not support data: URIs for <iframe> elements. Chrome enforces a 2MB size limit on data: URIs. Firefox supports data: URIs of essentially unlimited length. These browser limits are enforced by the browser itself and cannot be controlled by Salesforce.

Lösung

How the Solution Works

The Visualforce page uses an <iframe> element with its src attribute set to a data: URI. The URI combines the ContentType from the Attachment record (for example, application/pdf) and the Base64-encoded body string provided by the Apex controller.
The Apex controller queries the Attachment record by ID and exposes two properties: att (the Attachment record including Body and ContentType) and pdf (the Base64-encoded string of the attachment body using EncodingUtil.Base64Encode()).

 

Visualforce Page

<apex:page controller="ViewPdf">
<iframe src="data:{!att.ContentType};base64,{!pdf}" ></iframe>
</apex:page>

Note: The data: URI may not be supported in all browsers. Internet Explorer does not support data: URIs for <iframe>. Chrome has a 2MB limit. Browsers enforce their own size limits, which Salesforce cannot control.

 

Apex Controller

The controller lazily loads the Attachment record on first access and exposes the Base64-encoded body:

public class ViewPdf {
public Attachment att {
get {
if (att == null) {
att = [SELECT Body, ContentType, Name FROM Attachment WHERE ID = '00PG0000004COZU'];
}
return att;
}
private set;
}
public String pdf {
get {
return EncodingUtil.Base64Encode(att.body);
}
}
}

Replace the Attachment ID 00PG0000004COZU with the ID of your Attachment record.

 

Workaround for the Chrome 2MB data: URI Limit

To avoid the Chrome 2MB limit, create an Object URL from the Blob instead of using a data: URI directly. This approach uses the window.URL.createObjectURL() browser API to generate a temporary URL for the Blob. This requires JavaScript in your Visualforce page to decode the Base64 string, create a Uint8Array, generate a Blob, and set the Object URL as the iframe src.

Nummer des Knowledge-Artikels

000385665

 
Laden
Salesforce Help | Article