Sandip Gend Sandip Gend - 1 year ago 150
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 Source

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())
            memoryStream.Position = 0;
            imageSource.CreateOptions = BitmapCreateOptions.PreservePixelFormat;
            imageSource.CacheOption = BitmapCacheOption.OnLoad;
            imageSource.UriSource = null;
            imageSource.StreamSource = memoryStream;
        //Save BitmapImage to file
        var encoder = new PngBitmapEncoder();
        using (var stream = new FileStream("your path for the image.png", FileMode.Create))

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 =
  var distL= sdtElementDrawing.First().Anchor.DistanceFromLeft;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download