Last active
July 20, 2019 02:28
-
-
Save surajp/88aec82b67249c1e2324bfb744a5af60 to your computer and use it in GitHub Desktop.
Convert images in rich text areas that are references to a Document, to base64 for exporting
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* This code is untested. | |
* Assumes references to images in rich text fields is in the form of 'https://<url>/<documentId>' and refers to a document record | |
*/ | |
public class ImageToBase64{ | |
public void convertToBase64(Id[] recordIds){ | |
Account[] accts = new Account[]{}; | |
Map<Id,Id[]> acctDocMap = new Map<Id,Id[]>(); | |
Map<Id,Document> docMap = new Map<Id,Document>(); | |
Id[] alldocIds = new Id[]{}; | |
for(Account a : [Select RichText__c from Account where Id in :recordIds]){ | |
Pattern p = Pattern.compile('<img[^>]*?src="([^">]*)"[^>]*?>'); | |
Matcher m = p.matcher(a.RichText__c); | |
Pattern urlSuffix = Pattern.compile('/([^/]*)$'); | |
while(m.find()){ | |
String imageUrl = m.group(1); | |
Matcher m2 = urlSuffix.matcher(imageUrl); | |
if(!m2.find() || String.isBlank(m2.group(1))) | |
continue; | |
Id docId = m2.group(1); | |
alldocIds.add(docId); | |
if(!acctDocMap.containsKey(a.Id) | |
acctDocMap.put(a.Id,new Id[]{docId}); | |
else | |
acctDocMap.get(a.Id).add(docId); | |
} | |
} | |
if(acctDocMap.size()>0){ | |
docMap = new Map<Id,Document>([Select Type,Body from Document where Id in :alldocIds()]); | |
for(Id acctId: acctDocMap.keySet()){ | |
Account a = acctDocMap.get(acctId); | |
m = p.matcher(a.RichText__c); | |
String newText=''; | |
Integer lastMatchIndex=0; | |
while(m.find()){ | |
String imageUrl = m.group(1); | |
Matcher m2 = urlSuffix.matcher(imageUrl); | |
Id docId = m2.group(1); | |
if(!docMap.containsKey(docId)){ | |
newText += a.RichText__c.substring(lastMatchIndex,m.end(1)); | |
} | |
else{ | |
Document d = docMap.get(docId); | |
Blob b = doc.Body; | |
String base64Str = EncodingUtil.base64Encode(doc.Body); | |
newText += a.RichText__c.substring(lastMatchIndex,m.start(1))+imageUrl.replaceFirst('data/'+doc.Type+';'+base64Str); | |
} | |
lastMatchIndex=m.end(1); | |
} | |
newText += a.RichText__c.substring(lastMatchIndex); | |
a.RichText__c = newText; | |
accts.add(a); | |
} | |
} | |
update accts; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
For exporting RTA with images and importing to another environment