Skip to content

Instantly share code, notes, and snippets.

@jagmohansingh
Last active March 19, 2021 12:16
Show Gist options
  • Save jagmohansingh/5f33158d469f6a6e00b5dd33c450e765 to your computer and use it in GitHub Desktop.
Save jagmohansingh/5f33158d469f6a6e00b5dd33c450e765 to your computer and use it in GitHub Desktop.
Save DOM As Image Attachment - Visualforce
<apex:page standardController="Account" extensions="SaveDOMToImageCtrl" docType="html-5.0">
<!-- load domtoimage JS library -->
<apex:includeScript value="{!$Resource.DomToImage}" />
<style type="text/css">
#image_data {
border: red 2px solid;
background-color: white;
}
</style>
<div>
<div id="image_data">
<!-- render the Matrix report here -->
</div>
<button value="Save Image" type="button" onclick="saveDOM()">
Save Image
</button>
</div>
<script type="text/javascript">
var recordId = '{!recordId}';
function saveDOM() {
if (domtoimage) {
var node = document.getElementById('image_data');
var promises = [];
promises.push(domtoimage.toPng(node));
Promise.all(promises).then(function(results) {
var dataUrl = results[0];
if(recordId) {
var attName = 'IMAGE_' + recordId + '.png';
var attBody = dataUrl.split(',')[1];
Visualforce.remoting.Manager.invokeAction(
'{!$RemoteAction.SaveDOMToImageCtrl.saveImage}',
attName, attBody, recordId,
function(result, event) {
if(event.status && result) {
window.location.href = '/' + recordId;
} else {
alert('Something went wrong, please refresh the page.');
}
}
);
}
}).catch(function (error) {
console.error('oops, something went wrong!', error);
});
} else {
alert('Something went wrong, please refresh the page.');
}
}
</script>
</apex:page>
global with sharing class SaveDOMToImageCtrl {
public SaveDOMToImageCtrl(ApexPages.StandardController sc) {
}
@RemoteAction
global static Boolean saveImage(String name, String body, String parentId) {
// delete old image
delete [select Id from Attachment where ParentId = :parentId and Name like 'IMAGE_%'];
// save the latest version
Attachment att = new Attachment();
att.Name = name;
att.Body = EncodingUtil.base64Decode(body);
att.ParentId = parentId;
Database.SaveResult res = Database.insert(att);
return res.isSuccess();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment