0
votes

I have created a word document based on a template.

Now I would like to get a base64 string of this new word document.

I found some things about getting a memorystream and then translate it into base64 but I don't really understand how it works.

Any idea to transform this WordprocessingDocument doc in base64 ?

Thanks

1

1 Answers

1
votes

the easiest way is

byte[] bytes= System.IO.File.ReadAllBytes(sFullFileName);
string sBase64Bytes = System.Convert.ToBase64String(bytes);

you don't have to use memory stream to load the bytes and translate to base 64. but if you want to update some content in memory and get updated base64 in memory, you can try this one:

          byte[] bytes = System.Convert.FromBase64String(sBase64Data);
          using (MemoryStream ms = new MemoryStream(bytes, true))
          {
              ms.Write(bytes, 0, bytes.Length);
              using (WordprocessingDocument doc = WordprocessingDocument.Open(ms,true))
              {
                  XmlDocument xCusDoc = OpenXmlHelper.GetCustomXmlDocument(doc);
                  sLayoutName = xCusDoc.DocumentElement.Attributes["name"].Value.ToString();
                  using (MemoryStream msw= new MemoryStream())
                  {
                      ms.WriteTo(msw);
                      bytes = msw.GetBuffer();
                  }
              }//end using (WordprocessingDocument doc
          }//end using (MemoryStream ms 

if you like to save it to a physical file, you can write bytes.

System.IO.File.WriteAllBytes(sFileName, bytes);