Search code examples
c#.netopenxmlopenxml-sdk

How to read EMF file from Word document in OpenXML and save it


I have a word document that has an EMF image file in it. I have to read that image file and save it in the system. Following is the code that I am using:

  var lstImages = selectedImage.Descendants < DocumentFormat.OpenXml.Drawing.Pictures.Picture > ();

  if (lstImages != null && lstImages.Any())
  {
    foreach(var image in lstImages)
   {
      string imageFileName = image.NonVisualPictureProperties?.NonVisualDrawingProperties?.Name;
      string blip = image.BlipFill.Blip.Embed.Value;
      ImagePart img = (ImagePart) wordDoc.MainDocumentPart.GetPartById(blip);
      GetExtension(ref fileName, imageFileName, img);
      string binaryDateTime = _dateTimeHelper.GetDateTimeUtcNow().ToBinary().ToString();

      var stream = img.GetStream();
      var byteStream = new byte[stream.Length];
      int length = (int) stream.Length;
      stream.Read(byteStream, 0, length);
      stream.Dispose();
      var uploadPath = "D://ImageFile//"

      if (!_directoryManager.Exists(uploadPath)) {
        _directoryManager.CreateDirectory(uploadPath);
      }

      fileName = string.Concat(binaryDateTime, "_", fileName);

      string completePath = string.Concat(uploadPath, fileName);

      using(var fileStream = new FileStream(completePath, FileMode.OpenOrCreate)) {

        // Write bytestream to disk
        fileStream.Write(byteStream, 0, length);
        fileStream.Close();
      }
    }
  }

The saved file when being open says the file is damaged. Can you guide what is it that I am doing wrong or is there an easier way to save or convert EMF file as png?

Please note this code works for other formats i-e. png, jpeg, bmp etc but not EMF


Solution

  • I actually changed the way it reads the stream and it worked for me.

      using (var fileStream = new FileStream(completePath, FileMode.OpenOrCreate))
                {
                    try
                    {
                        using (var ms = new MemoryStream())
                        {
                            var stream = img.GetStream();
                            stream.CopyTo(ms);
                            ms.WriteTo(fileStream);
                        }
                    }
                    catch (Exception ex)
                    {
                        LogHelper.Log(ex.Message, LogLevel.Warning);
                    }
                }