c# - 如何从 .DOCX 文件中获取带有图像的标题文本

标签 c# .net openxml

我想从文档文件中获取标题图像。我使用以下代码,它给了我图像路径,但我无法获取它

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

最佳答案

我认为你的方法不起作用,因为 doc 文件是一个 zip 文件。 我不知道您需要哪种格式的图像,但您可以尝试类似的方法来检索图像对象。我用一个工作示例更新了我的答案,希望它有所帮助。

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);
    }
}

这是一个如何获取图片位置的示例,但请记住,只有当您的图片获得绝对位置时,它才有效。

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

关于c# - 如何从 .DOCX 文件中获取带有图像的标题文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40764264/

相关文章:

c# - DataContract XML 序列化和 XML 属性

c# - 秒表耗时线程安全

C# Windows 服务使用来自 MSDN "Find and Replace text in a Word document"的 FlatDocument 示例保持文件锁定

openxml - 在哪里可以了解有关 Excel 专用 OpenXML 元素的更多信息?

c# - 非静态隐式运算符

c# - Convert.ToString(Decimal, IFormatProvider) 或 String.Format

c# - 如何在 C# 中将代码块(不是完整方法)作为参数传递?

c# - 如何在不创建本地文件的情况下使用 OpenXML 创建 Excel 文件?

c# - 如何查找流是否具有 unicode

.net - WPF 调整窗口大小