2

I have a Render a VisualForce Page as a PDF and I need to convert it into an image file and store it into the Document folder.

Can Anyone Give me the Codes to convert the PDF VisualForce Page into an image file?

Reason for doing this is because my boss want it an image file instead of a PDF file when he open the file in the document folder and also when it is send to Facebook via Graph API the user can just click on the Picture to see whereas if I use a PDF I can only upload the URL of the PDF and he doesn't like that.

1

You can't render a Visualforce into an image. There is no standard mechanism available from Salesforce. But there are many JavaScript libraries available using which you can take a screenshot of a web page. One such library is html2canvas you can check the example page to see the implementation. After converting the page to an image you can upload it to the Salesforce document folder.

Update

You can use the toDataURL method to convert the screenshot to a base64 image data and save it using a remote method. the code should be something as below. Please note this is not a compiled code, some fixes may be required.

JavaScript

$('#screenshot').click(function () {
    html2canvas($('body,html'), {
        onrendered: function (canvas) {
            var imgData = canvas.toDataURL('image/png').split(',')[1];
            SaveImage.saveImage('001i000000gDY4Z',imgData,handleResult); // 
        }
    });
});

function handleResult(result,event) {
    if(result.success) {
        alert('Screenshot attached');
    } else {
        alert('Error: '+result.errorMessage);
    }
}

Controller

public with sharing class SaveImage {
    @RemoteAction public static RemoteSaveResult saveImage(Id parID, String imageBody) {
        Attachment a = new Attachment(ParentId=parID, name='Image.png', ContentType='image/png', Body=EncodingUtil.base64Decode(imageBody));
        Database.saveResult result = Database.insert(a,false);
        RemoteSaveResult newResult = new RemoteSaveResult();
        newResult.success = result.isSuccess();
        newResult.attachmentId = a.Id;
        newResult.errorMessage = result.isSuccess()?'':result.getErrors()[0].getMessage();
        return newResult;
    }
}
2
  • o IC But I still need the codes on how store it into the document folder after the HTML2canvas take a screenshot of it
    – Jerome AJJ
    Apr 14 '17 at 6:14
  • Check my updated answer.
    – Saroj Bera
    Apr 14 '17 at 10:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.