jles
posted this
06 October 2017
Hi Dan,
You were very close. Please see the snippet below that opens an MS Word document, converts it into a Docentric Toolkit template, adds two data sources and for each of the data sources sets the schema and the sample XML file:
public static void CreateTemplateFromOrdinaryDocument()
{
// Read the ordinary docx file from the disk and make a in-memory copy of it.
MemoryStream ms = new MemoryStream();
string sourceDocFilePath = TemplatesPath + "OrdinaryDocument.docx";
using (FileStream sourceDocStream = File.OpenRead(sourceDocFilePath))
{
sourceDocStream.CopyTo(ms);
}
// Open the in-memory version of the document as a template (actually it is not a template yet).
using (TemplateDocument templateDocument = TemplateDocument.Open(ms))
{
// Make this document a template (Metadata has been created).
templateDocument.MakeTemplate();
// Add the first data source (the default one).
{
DataSource firstDataSource = new DataSource(DataKind.Xml); // This is the default data source and does not have a name.
templateDocument.Metadata.DataSources.Add(firstDataSource); // Add it.
// Infer the scema form a sample XML file.
string sampleXmlFilePath = TemplatesPath + "XmlXsd\\Products.xml";
using (FileStream sampleXmlStream = File.OpenRead(sampleXmlFilePath))
{
firstDataSource.Schema = Docentric.Documents.Reporting.TemplateManagement.Metadata.Xml.Schema.FromSampleXml(sampleXmlStream);
}
}
// Add the second data source.
{
DataSource secondDataSource = new DataSource(DataKind.Xml, "Machine");
templateDocument.Metadata.DataSources.Add(secondDataSource); // Add it.
// Infer the scema form a sample XML file.
string xsdFilePath = TemplatesPath + "XmlXsd\\MachineDNS.xsd";
using (FileStream xsdStream = File.OpenRead(xsdFilePath))
{
secondDataSource.Schema = Docentric.Documents.Reporting.TemplateManagement.Metadata.Xml.Schema.FromXsd("d:\\test.xsd", xsdStream);
}
// Set the preview data.
secondDataSource.PreviewData = new PreviewData("e:\\test.xml", System.Xml.Linq.XElement.Load(TemplatesPath + "XmlXsd\\Products.xml"));
}
}
// Write to the disk.
File.WriteAllBytes(TemplatesPath + "CreatedTemplate.docx", ms.ToArray());
}
Regards,
Jure Leskovec