Spire.Doc 圖片和形狀教程:C# 如何插入圖片到 Word 以及提取 Word 中的圖片

更多資源查看:Spire.XLS圖表系列教程 | Spire.PDF系列教程

圖片是Word文檔的基本要素之一,常見的對Word圖片的操作有插入、刪除、替換和提取。本文將介紹如何使用Spire.Doc通過編程的方式添加圖片到指定位置,以及如何獲取Word文檔中的圖片並保存到本地路徑。

下載Spire.Doc最新試用版

在指定位置插入圖片

//實例化一個Document對象
Document doc = new Document();

//添加section和段落
Section section = doc.AddSection();
Paragraph para = section.AddParagraph();

//加載圖片到System.Drawing.Image對象, 使用AppendPicture方法將圖片插入到段落
Image image = Image.FromFile(@"C:\Users\Administrator\Desktop\logo.png");
DocPicture picture = doc.Sections[0].Paragraphs[0].AppendPicture(image);

//設置文字環繞方式
picture.TextWrappingStyle = TextWrappingStyle.Square;

//指定圖片位置
picture.HorizontalPosition = 50.0f;
picture.VerticalPosition = 50.0f;

//設置圖片大小
picture.Width = 100;
picture.Height = 100;

//保存到文檔
doc.SaveToFile("Image.doc", FileFormat.Doc);

效果圖:

Add-image-to-word-document-and-extract-images-from-word-document-1

 

提取Word文檔中的圖片

//初始化一個Document實例並加載Word文檔
Document doc = new Document();
doc.LoadFromFile(@"Image.doc");

int index = 0;
//遍歷Word文檔中每一個section
foreach (Section section in doc.Sections)
{
    //遍歷section中的每個段落
    foreach (Paragraph paragraph in section.Paragraphs)
    {
        //遍歷段落中的每個DocumentObject
        foreach (DocumentObject docObject in paragraph.ChildObjects)
        {
            //判斷DocumentObject是否爲圖片
            if (docObject.DocumentObjectType == DocumentObjectType.Picture)
            {
                //保存圖片到指定路徑並設置圖片格式
                DocPicture picture = docObject as DocPicture;
                String imageName = String.Format(@"images\Image-{0}.png", index);
                picture.Image.Save(imageName, System.Drawing.Imaging.ImageFormat.Png);
                index++;
            }
        }
    }
}

效果圖:

Add-image-to-word-document-and-extract-images-from-word-document-2

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章