How To Create Pdf From Word Template and Send as Email Attachment?

Today, I explain how to create PDF file from Word Template and send as email attachment using custom workflow activity, and then will create a workflow that perform this Microsoft dynamics implementation functionality.

For this, following are the workflow steps.

1. Create an Email in first step.
2. Set a Word Template in second step which add annotation (Notes) to a parent Record (Word Template already in CRM).
3. Execute custom activity which get annotation from parent record and convert it to PDF and then attach it to Email and send Email.

Let’s start with above steps.

1. Create a Workflow in CRM, workflow provides a default step to create an Email.
2. Then add second step that will set Word Template as annotation to a Parent Record. Here Invoice record is my Parent Record on which I will execute custom workflow activity.

“Set Word Template” step has two input argument, Selected Template and Target.
- Set template in first input argument.
- Set parent record (Invoice) in Target input argument.

3. Now create custom activity which get annotation from parent record and convert it to PDF and then attach it to Email and send Email. So, Create custom activity and add following code.

- This workflow has two inArguments. First Email as “EntityReference” and second “FileName”.
- Add following statements to create organization service.

<p>IOrganizationServiceFactory serviceFactory = context.GetExtension&lt;IOrganizationServiceFactory&gt;();<br />IOrganizationService service = serviceFactory.CreateOrganizationService(workflowContext.InitiatingUserId);</p>

- Then get parent record using organization service.

 Entity _invoice = service.Retrieve(_context.PrimaryEntityName, _context.PrimaryEntityId, new ColumnSet(new string[] { "ownerid", "name" }));  

   - Get email record that was created in first step of workflow.

 Entity emailCreated = service.Retrieve("email", SourceEmailID, new ColumnSet(new string[] { "activityid" }));  

- Here “SourceEmailID” is an email id from Email EntityReference inArgument.
- Next, get word template (annotation) from parent record using QueryExpression as below.

QueryExpression QueryNotes = new QueryExpression("annotation");
QueryNotes.ColumnSet = new ColumnSet(new string[] { "subject", "mimetype", "filename", "documentbody", "annotationid" }); QueryNotes.Criteria = new FilterExpression();
QueryNotes.Criteria.FilterOperator = LogicalOperator.And; QueryNotes.Orders.Add(new OrderExpression("createdon",OrderType.Descending));
QueryNotes.Criteria.AddCondition(new ConditionExpression("objectid", ConditionOperator.Equal, _invoice.Id)); EntityCollection MimeCollection = service.RetrieveMultiple(QueryNotes);

This will retrieve list of all annotations from parent record, but we need latest annotation using following statement.

 Entity NotesAttachment = MimeCollection.Entities.First();  

Get the document content using following statement.

string docContent = NotesAttachment.GetAttributeValue<string>("documentbody");
string content = "{docContent:\"" + docContent + "\"}";
string fileContent = doc2pdf(content);

You can see that I called a function doc2pdf that is as below which will convert document file to PDF. For this we required Aspose. Words assembly which you easily download from internet.

private string doc2pdf(WordContent word)
{ string pdfContent = string.Empty;
if (!string.IsNullOrEmpty(word.docContent))
{ byte[] fileContent = Convert.FromBase64String(word.docContent);
Document doc = new Document(ms);
MemoryStream ms = new MemoryStream(fileContent); ms.Close(); MemoryStream toMS = new MemoryStream();
pdfContent = Convert.ToBase64String(pdfbytes);
doc.Save(toMS, SaveFormat.Pdf); toMS.Position = 0; byte[] pdfbytes = toMS.ToArray(); return pdfContent; } else
{ var resp = "Document content is empty."; return resp;

   - Now Create email attachment entity object as below and set the values.

Entity EmailAttachment = new Entity("activitymimeattachment");
if (NotesAttachment.Contains("subject"))
EmailAttachment["subject"] = NotesAttachment.GetAttributeValue<string>("subject");
EmailAttachment["objectid"] = new EntityReference("email", emailCreated.Id);
EmailAttachment["filename"] = "invoice_1"; //give the file name whatever you want as per your requirement.
EmailAttachment["objecttypecode"] = "email"; if (NotesAttachment.Contains("filename"))
if (NotesAttachment.Contains("mimetype"))
if (NotesAttachment.Contains("documentbody")) EmailAttachment["body"] = fileContent; { EmailAttachment["mimetype"] = @"application/pdf";
Guid attachmentID = service.Create(EmailAttachment);

   Finally, send this email using following code.

SendEmailRequest sendEmail = new SendEmailRequest();
sendEmail.EmailId = emailCreated.Id;
sendEmail.IssueSend = true;
sendEmail.TrackingToken = "";
SendEmailResponse res = (SendEmailResponse)service.Execute(sendEmail);

Now activate this workflow and execute from button click event of html web-resource. You will get the code to execute workflow from html web-resource from here.

James have a highly skilled & experienced CRM development company India. He has wide experience in IT industries to develop creative business system based on Microsoft dynamics CRM.