[英]how to get header text with image from .DOCX file
我想獲取標題圖像形式的doc文件。 我使用以下代碼,它給了我圖像路徑,但我無法獲得它
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;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.