Wednesday, August 20, 2014

SharePoint 2013 - Generate document with data using server object model

When we provide a content management solution with SharePoint, often we need to generate reports or documents using existing data. To generate reports we can use SSRS with “SharePoint List” as the data source. But, how can we generate a word document in a given template?

In this article I will show how to generate a word document with data using SharePoint server object model. To explain the concept I will implement following scenario.

  • Generate contract approval summary document from a template
  • Fill approvers section from list fields

Following are the steps we need to follow.

1. Create a content type and associate with list fields

I’ve created the content type with necessary fields in visual studio and deployed to the farm.

image

2. Associate the content type to a document library and go to advanced settings to change the document template

we will navigate to advanced settings and upload an empty word document (e.g.: template.docx)

image

3. Click on edit template and modify the document to build the template

image

To add dynamic content, we will use quick parts section of the document. As you can see, the content type fields are available in the quick parts section. we will embed those fields to our document accordingly

image

image

Then we will save changes

4. Use following code to create document

  1. var web = SPContext.Current.Web;
  2. web.AllowUnsafeUpdates = true;
  3.  
  4. var tplurl = listItem.ParentList.ContentTypes["Contract Approval Summary"].DocumentTemplateUrl;
  5. byte[] stream = web.GetFile(tplurl).OpenBinary();
  6.  
  7.  
  8. var itemProperties = new Hashtable();
  9. itemProperties.Add("AGMName", agmName);
  10. itemProperties.Add("RegionalControllerName", regionalName);
  11. itemProperties.Add("RVPName", rvpName);
  12.  
  13. listItem.ParentList.RootFolder.Files.Add(listItem.DisplayName + " Approval Summary.docx", stream, itemProperties, true);
  14. web.AllowUnsafeUpdates = false;

That will create the document with required fields.Those fields will be embedded to the document as per the template

No comments: