Tip #608: Generate documents in code

CRM 2016 has the ability to generate documents using Word templates. For workflows there’s a custom action called SetWordTemplate which can be added via Add Step > Perform Action > SetWordTemplate.

Generate document action in the workflow
But what if you want to generate the document in a plugin, javascript or in external application so that the functionality can be used by custom UI, batch processes or even from an external system via the web service?

Shamira (Sam) Fernando has the answer. The below snippet can be used to generate a document from code and the action attaches the generated document to the target record. The document template needs to be a system template – personal document templates won’t work.

OrganizationRequest req = 
   new OrganizationRequest("SetWordTemplate");

req["Target"] = 
   new EntityReference("account", accountGuid);
req["SelectedTemplate"] = 
   new EntityReference("documenttemplate", templateGuid);


27 thoughts on “Tip #608: Generate documents in code

  1. Jason Damien says:

    Good tip, thanks Shamira!

  2. Awesome, very handy snippet of code. Did you know that using the standard workflow step, it seems you cannot choose to merge TO a custom entity, however you can merge WITH a custom entity. Without implementing this code snippet I am not sure yet if it gets around that workflow issue. I will advise once our team of elves tries this tomorrow for me.

    • Sam Fernando says:

      Hi Martin,

      Yes, you cannot merge TO another other than the one that you are merging the template WITH.

      You can develop a work action that fetches the attached note (after the generation) from the source record and reattach it to a new record. That’ll be the work around.


    • Matt says:

      Hi Martin

      I’ve been trying to merge to a custom entity in a workflow step without success – hopefully it’s a ‘feature’ that MS will fix. Did you have any success using the OrganizationRequest setting Target to a custom entity?



      • Matt,

        what specific issues are you experiencing when merging to a custom entity in a workflow step? It works for me just fine.


        • Matt says:

          Hi George

          I’ve created a Document Template against a custom entity. I can generate documents using this template from the Word Templates ribbon button. When I create a workflow on the custom entity and add step Perform Action->SetWordTemplate, on setting the properties I can set SelectedTemplate to the Document Template but I can’t set Target to be my custom entity. If I use the lookup none of my custom entities are present in the Look for dropdown. Similarly, if I set the Dynamic Values Look for dropdown to my custom entity only the lookup fields on the custom entity are available and not the custom entity record itself.

          I’ve tried various different options in the Communication & Collaboration section when defining my custom entities.

          Any ideas appreciated



          • Hey Matt,

            I think you’re onto something here. Fresh entity doesn’t seem to have a reference to the entity itself to select as a parameter for the SetWordTemplate action.

            After playing with different settings, it seems that enabling the entity for the Business process flows seems to be the requirement.


  3. Matt says:

    Bingo. That’s got it – enabled the entity for Business process flows – obviously!

    Thanks George.



    • AdamV says:

      I too tried all sorts of settings that ought to have nothing to do with it, such as Document Management and Mail Merge. Never thought to try BPF. Well discovered!
      Also need Notes of course, so it has somewhere to stick the document

  4. Edwin says:


    Is the same functionality can be used in order to generate Excel Template with a setExcelTemplate action for example ?

    best Regards,

    • Edwin,

      I don’t see why not, Excel generation is very similar.


      • Edwin says:

        Hi George, thank you for your response.

        As the setExcelTemplate action is not proposed inside a step of a workflow passing by the UI, I haven’t found either how to perform the action by code with : OrganizationResquest(“SetExcelTemplate”);

        The previous request seems to be not supported…

        Maybe in a future release ?


      • AdamV says:

        Broadly similar but Excel templates are intended to be used for a RetrieveMultiple, whereas Word templates work against a single record

  5. Jogendar Bandaru says:

    Thanks for the snippet. I am successfully able to create the attachment through this. I am trying to get the Guid of the attachment that is created in this process. I searched in the response, but no luck. Any ideas??

    • Jogendar,

      does not look like this request sends a record id (or anything else, for that matter) back. It could be because of the asynchronous operation used. I’d use fetch to locate the attachment. Not 100% reliable, but will work

  6. Robert says:

    I am using Sam’ s snippet but no success i receive this when i run the workflow:
    Unexpected exception from plug-in (Execute): Workflow1.Workflow: System.IO.FileNotFoundException: Could not load file or assembly ‘Microsoft.Xrm.Tooling.Connector, Version=, Culture=neutral, PublicKeyToken=31bf3856ad364e35’ or one of its dependencies. The system cannot find the file specified.

    Any help.

  7. Neil says:

    Hi, this tip is slightly misleading, it mentions generating a document from javascript but the code is for a plugin, not javascript! I want to do this without having to deploy and maintain plugin code, is it possible via javascript?


  8. Zarko says:

    Thanks for the tip. I am trying to use it to save the document to SharePoint, but it seems that this operation is not synchronous. My logic was to get the latest Annotation object with same name as template right after the response comes back, but the behavior was inconsistent, I would receive exception sometimes.

    I am trying now with ExecuteWorkflowRequest, where workflow contains SetWordTemplate action and is configured to be synchronous. I didn’t receive an exception for now, tested in loop, deleting document every time right after the request. Could anybody confirm that this behavior will be consistent, while system is under pressure for example?

    Thanks in advance

  9. pardha says:

    How to get the attached ID. post-execution. Pls help

  10. Anonymous says:

    This doesn’t work for online plugins or workflows

    • Joel Lindstrom says:

      You realize this tip is 3 years and 4 versions old. Flow will soon be able to trigger actions, making this tip unnecessary

      • Tulio Campos says:

        Hi, first thank for share a great content here!

        Im trying fix a problem with that, because my code use it since 2017 and now stoped working.
        I have the error “The request SetWordTemplate cannot be invoked from the Sandbox”.
        My entity don’t let me use the option ”process work flow” as solved for Matt in April 26, 2016.

        So, Im a begginner using CRM, can you please help me ?

  11. Tulio says:

    why u delete my question?

Leave a Reply

Your email address will not be published. Required fields are marked *