MS Dynamics CRM - Download document template as PDF - Plugin / Action

Ankaprasad
Posted by Ankaprasad under C# category on | Points: 40 | Views : 8058
In this example i'm using custom action.

1. Create custom action with 3 input parameters (document template id, Record Id, Entity type code)
2. Generate javascript code using "CRM Rest builder" and add javascript function in JS File.

function DownloadDocumentTemplateAsPDF()
{
// You can pass dynamic values here //
var parameters = {};
parameters.TemplateId = "118c855e-f435-ea11-a813-000d3a5631e2";
parameters.RecordId= "6329dbd0-4e1c-e511-80d3-3863bb347ba8";
parameters.TypeCode= "4"; // Entity type code for lead - 4

var req = new XMLHttpRequest();
req.open("POST", Xrm.Page.context.getClientUrl() + "/api/data/v9.1/new_DownloadDocumentTemplatePDF", true);
req.setRequestHeader("OData-MaxVersion", "4.0");
req.setRequestHeader("OData-Version", "4.0");
req.setRequestHeader("Accept", "application/json");
req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
req.onreadystatechange = function() {
if (this.readyState === 4) {
req.onreadystatechange = null;
if (this.status === 204) {
//Success - No Return Data - Do Something
} else {
Xrm.Utility.alertDialog(this.statusText);
}
}
};
req.send(JSON.stringify(parameters));
}

3. Create custom button and call the above js function.
4. Follow the below code to create custom action/plugin assembly.

public void Execute(IServiceProvider serviceProvider)
{
IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);

string documentTemplateId = context.InputParameters["TemplateId"].ToString();
string recordId = context.InputParameters["RecordId"].ToString();
int typeCode = Convert.ToInt32(context.InputParameters["TypeCode"]);

CreatePDFNote(service, documentTemplateId, recordId, typeCode);
}


        public static void CreatePDFNote(IOrganizationService _service, string documentTemplateId, string recordId, int entityTypeCode)
{
// Create new Organization service with admin user to call "ExportPdfDocument" message
IOrganizationService pdfService = GetExportPDFService();

try
{
OrganizationRequest request = new OrganizationRequest("ExportPdfDocument");
request["EntityTypeCode"] = entityTypeCode;
request["SelectedTemplate"] = new EntityReference("documenttemplate", new Guid(documentTemplateId));
List<Guid> records = new List<Guid> { new Guid(recordId) };
request["SelectedRecords"] = JsonConvert.SerializeObject(records);

OrganizationResponse pdfResponse = (OrganizationResponse)pdfService.Execute(request);

//Write to file
string b64File = Convert.ToBase64String((byte[])pdfResponse["PdfFile"]);

// Create note by using the above base 64 string / create email attachment and send it to customer .

Entity Annotation = new Entity("annotation");
Annotation.Attributes["subject"] = "PDF note using Document template";
Annotation.Attributes["documentbody"] = b64File;
Annotation.Attributes["objectid"] =new EntityReference("lead", new Guid(recordId));
Annotation.Attributes["mimetype"] = @"application/pdf";
Annotation.Attributes["notetext"] = "Sample PDF attachment";
Annotation.Attributes["filename"] = "NOTEPDF.pdf";
_service.Create(Annotation);
}
catch (Exception ex)
{
}
}

5.Make sure you create a new organization service with admin user to execute "ExportPdfDocument" sdk message

        public static IOrganizationService GetExportPDFService()
{
IOrganizationService _service = null;
if (_service == null)
{
string serviceURL = "https://xyka15.api.crm.dynamics.com/XRMServices/2011/Organization.svc";

ClientCredentials credentials = new ClientCredentials();
credentials.UserName.UserName = "Prasad@xyka15.onmicrosoft.com"; // User Name
credentials.UserName.Password = "*******"; // Password
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
Uri serviceuri = new Uri(serviceURL);

try
{
OrganizationServiceProxy proxy = new OrganizationServiceProxy(serviceuri, null, credentials, null);
proxy.EnableProxyTypes();
_service = (IOrganizationService)proxy;

}
catch (Exception ex)
{

}
}
return _service;
}

6. Add "Newtonsoft.json" from NuGet packages.

Note : We are using Newtonsoft.json so it requires IL Merge. So add the below 2 NuGet packages for IL Merge.

1. ILMerge
2. ILMerge.MSBuild.Task

Hope it helps..!!!

Comments or Responses

Login to post response