在 Word 中替換圖像
Spire.Doc for .NET是一款專門對(duì) Word 文檔進(jìn)行操作的 .NET 類庫。在于幫助開發(fā)人員無需安裝 Microsoft Word情況下,輕松快捷高效地創(chuàng)建、編輯、轉(zhuǎn)換和打印 Microsoft Word 文檔。擁有近10年專業(yè)開發(fā)經(jīng)驗(yàn)Spire系列辦公文檔開發(fā)工具,專注于創(chuàng)建、編輯、轉(zhuǎn)換和打印Word/PDF/Excel等格式文件處理,小巧便捷。在 C#、VB.NET 中從 Word 中提取圖像。
在 Spire.Doc 中可以用 Word 文檔中的文本或圖像替換圖像,在本教程中,我們將向您展示如何使用 Spire.Doc 和 C# 將指定的圖像替換為另一個(gè)圖像。
下面是替換圖片之前的原始Word文檔:
  
 
	
代碼片段:
第 1 步:加載 Word 文檔。
Document document = new Document("Input.docx");
第 2 步:用新圖像替換標(biāo)題為“圖1”的圖像。
//Loop through the paragraphs of the section
foreach (Paragraph paragraph in document.Sections[0].Paragraphs)
{
//Loop through the child elements of paragraph
foreach (DocumentObject docObj in paragraph.ChildObjects)
{
if (docObj.DocumentObjectType == DocumentObjectType.Picture)
{
DocPicture picture = docObj as DocPicture;
if (picture.Title == "Figure 1")
{
//Replace the image
picture.LoadImage(Image.FromFile("PinkRoses.jpg"));
}
}
}
}
第 3 步:保存并關(guān)閉文檔。
document.SaveToFile("ReplaceImage.docx");
document.Close();
生成的文檔如下所示:
  
 
	
完整代碼:
using System.Drawing;
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
namespace Replace_Image
{
class Program
{
static void Main(string[] args)
{
//Load the Word document
Document document = new Document("Input.docx");
//Loop through the paragraphs of the section
foreach (Paragraph paragraph in document.Sections[0].Paragraphs)
{
//Loop through the child elements of paragraph
foreach (DocumentObject docObj in paragraph.ChildObjects)
{
if (docObj.DocumentObjectType == DocumentObjectType.Picture)
{
DocPicture picture = docObj as DocPicture;
if (picture.Title == "Figure 1")
{
//Replace the image
picture.LoadImage(Image.FromFile("PinkRoses.jpg"));
}
}
}
}
//Save and close the document
document.SaveToFile("ReplaceImage.docx");
document.Close();
}
}
}
以上便是如何使用 C# 在 Word 中替換圖像,如果您有其他問題也可以繼續(xù)瀏覽本系列文章,獲取相關(guān)教程,你還可以給我留言或者加入我們的官方技術(shù)交流群(767755948)

 QQ交談
QQ交談 在線咨詢
在線咨詢 
                 
                
 渝公網(wǎng)安備
            50010702500608號(hào)
渝公網(wǎng)安備
            50010702500608號(hào)
             
            
 客服熱線
客服熱線