How do I create a new document in a document library according to a template in a workflow ?
-
06-12-2019 - |
Question
I have a document library with a DOCX template file. I want to create DOCX file in this library in a workflow but I did not succeed.
Before, I created a workflow in Sharepoint Designer to create a new item in the document library, but now I have to write this workflow in Visual Studio 2010 and it doesn't work.
Here is what I do in the workflow :
using (SPSite oSPsite = new SPSite("URL"))
{
using (SPWeb oSPWeb = oSPsite.OpenWeb())
{
oSPWeb.AllowUnsafeUpdates = true;
var docLib = oSPWeb.Lists["gpReports"];
var fileName = "Title.docx";
Hashtable ht = new Hashtable();
ht.Add("Title", "Title");
ht.Add("ProjectYear", "Year");
ht.Add("ProjectDepartment", "Department");
docLib.RootFolder.Files.Add(fileName, new byte[] { }, ht, true);
oSPWeb.AllowUnsafeUpdates = false;
}
}
Every method of Add need a file or a byte array, but I want that the template of the document library is used.
Using the current method, it creates an empty file in the document library.
Is there a way to do that programmatically ?
Solution
Just retrieve the template as an SPFile
and use the OpenBinary()
method to get the byte[]. Then copy that to your new file.
Edit. The template is not actually bound to your list but to a content type, so you need to retrieve it using its url:
byte[] f = w.GetFile(web.Lists[YourList].ContentTypes[yourContentTypeId].DocumentTemplateUrl).OpenBinary();
OTHER TIPS
Try something like that - to create your word file.
Word.Application app = new Word.Application();
Word.Document doc = app.Documents.Add(@"http://...PathToMyWordTemplate.dotx");
doc.SaveAs(FileName: @"c:\test.docx");
You can save the document in memory and pass his byteArray to the docLib.RootFolder.Files.Add... method.
Below is a codesnippet to add predefined content in the word document....
public void CreateDocument(string docName)
{
using (MemoryStream memStream= new MemoryStream())
{
// Create a Wordprocessing document.
using (WordprocessingDocument doc = WordprocessingDocument.Create(memStream,WordprocessingDocumentType.Document))
{
// Add a new main document part.
doc.AddMainDocumentPart();
// Create the Document DOM.
doc.MainDocumentPart.Document =
new Document(
new Body(
new Paragraph(
new Run(
new Text(“Hello World!”)))));
// Save changes to the main document part.
doc.MainDocumentPart.Document.Save();
//Adding Document to SharePoint
AddToSharePoint(memStream,docName)
}
}
}
protected void AddToSharePoint(MemoryStream memStream,string fileName)
{
using (SPSite spSite = new SPSite(siteUrl))
{
//Get the document library object
SPList docLib = spSite.RootWeb.Lists["Shared Documents"];
SPFile file = docLib.RootFolder.Files.Add(fileName, memoryStream, true);
file.Update();
}
}