Sandip Gend Sandip Gend - 10 days ago 4
C# Question

how to get header text with image from .DOCX file

i want to get header image form doc file. i use following code it gives me image path but i can't get it

DocumentFormat.OpenXml.Packaging.ImagePart img = header.ImageParts.FirstOrDefault();
string imgpath = img.Uri.OriginalString;

Jo. Jo.
Answer

I think your approach didn't work because the doc file is a zip file. I don't know in which format you need that image, but you can try something like this to retrieve an image object. I updated my answer with an working example hope it helps.

using (var document = WordprocessingDocument.Open("your document path", true))
{
    //Get the header
    var header = document.MainDocumentPart.HeaderParts.First();
    //These are your paragraphs where you can get the headers Text from
    var paragraphList = header.Header.Descendants<DocumentFormat.OpenXml.Wordprocessing.Paragraph>();
    //Get the imageId
    string imgId = header.GetIdOfPart(header.ImageParts.First());

    var imageSource=new BitmapImage();
    //Get the imageStream
    using (var imgStream = ((ImagePart)header.GetPartById(imgId)).GetStream())
    {
        //Copy stream to BitmapImage
        using (var memoryStream = new MemoryStream())
        {
            imgStream.CopyTo(memoryStream);
            memoryStream.Position = 0;
            imageSource.BeginInit();
            imageSource.CreateOptions = BitmapCreateOptions.PreservePixelFormat;
            imageSource.CacheOption = BitmapCacheOption.OnLoad;
            imageSource.UriSource = null;
            imageSource.StreamSource = memoryStream;
            imageSource.EndInit();
        }
        imageSource.Freeze();
        //Save BitmapImage to file
        var encoder = new PngBitmapEncoder();
        encoder.Frames.Add(BitmapFrame.Create(imageSource));
        using (var stream = new FileStream("your path for the image.png", FileMode.Create))
            encoder.Save(stream);
    }
}

and this is an example how you can get position of your picture, but keep in mind it will only work if your picture got an absolute position.

  List<DocumentFormat.OpenXml.Wordprocessing.Drawing> sdtElementDrawing =
  header.Header.Descendants<DocumentFormat.OpenXml.Wordprocessing.Drawing>().ToList();
  var distL= sdtElementDrawing.First().Anchor.DistanceFromLeft;
Comments