I am working on a code to export CV profile data to a Word document, following a template. I am using C# and OpenXML.
I load the template-file to a MemoryStream, then make a new WordprocessingDocument from that.
The problem occours when I save this document to a file. The resulting document can't be opened in neither MS Word nor LibreOffice Writer, giving me a general input/output error.
So I diabled the code I am testing for inserting the data, meaning the document I create should be an exact copy of the template. But no. No diffrence.
I had a closer look at the files, and unpacked both the template and the generated file, and ran them though WinMerge. The structure inside the files are quite diffrent from each other.
Relevant part of the source-code:
static void Main(string[] args)
{
//force Visual studio to display errors in english (damned localized default settings)
if (Debugger.IsAttached)
CultureInfo.DefaultThreadCurrentUICulture = CultureInfo.GetCultureInfo("en-US");
Console.WriteLine("Hello world");
string pathData = "C:/Users/Lars Erik/Desktop/oppdrag fra synnes/oc-ny.json";
string pathTemplate = "C:/Users/Lars Erik/Desktop/oppdrag fra synnes/test_template/test_template.docx";
if (!File.Exists(pathData))
{
WriteLine("The path for the data is not valid. File not found. Path: " + pathData);
//return;
}
else if (!File.Exists(pathTemplate))
{
WriteLine("The path for the template is not valid. File not found. Path: " + pathTemplate);
//return;
}
//string rawData = File.ReadAllText(pathData);
FileStream Stream = new FileStream(pathData, FileMode.Open);
Byte[] templateRawdata = File.ReadAllBytes(pathTemplate);
MemoryStream outputStream = new MemoryStream();
outputStream.Write(templateRawdata, 0, templateRawdata.Length);
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(Consultant));
Consultant data = serializer.ReadObject(Stream) as Consultant;
//JsonSerializerSettings settings = new JsonSerializerSettings();
//Object data = JsonConvert.DeserializeObject(rawData);
//Consultant data = JsonConvert.DeserializeObject<Consultant>(rawData);
//WriteLine(data.ToString());
WordprocessingDocument template = WordprocessingDocument.Open(pathTemplate, false);
WordprocessingDocument outputdoc = WordprocessingDocument.Open(outputStream, true);
//TranslateCV(data, template, ref outputdoc);
//outputdoc.Close();
outputStream.CopyTo(File.Create("C:/Users/Lars Erik/Desktop/oppdrag fra synnes/OUTPUT/testresult.docx"));
}
Here is some screenshots from WinMerge comparing the should-be identical template and resulting document:
(The UI is in Norwegian. Not sure if I can change that)