C# 設置Word文檔中圖片的大小

在創建Word文檔時,我們經常需要向文檔中插入圖片,但插入圖片的大小有時候可能會太大或太小,這時候我們就需要對圖片的大小進行調整,使得圖片與文章更加協調、美觀。這篇文章將介紹如何使用Free Spire.Doc組件和C#在Word文檔中對新添加的圖片和已有的圖片進行大小設置。

在使用以下代碼前需要創建一個C#應用程序並引用Spire.Doc.dll到工程中。

對新添加的圖片進行大小設置

//創建Document實例
Document document = new Document();
 
//添加節和段落
Section s = document.AddSection();
Paragraph p = s.AddParagraph();
 
//添加圖片到段落
DocPicture Pic = p.AppendPicture(Image.FromFile(@"MickeyMouse.jpg"));
 
picture.TextWrappingStyle = TextWrappingStyle.Square; 
picture.HorizontalPosition = 180f;
picture.VerticalPosition = 60f;
 
//設置圖片的大小
Pic.Width = 120f;
Pic.Height = 170f;
 
//保存文檔
document.SaveToFile("Image.docx", FileFormat.Docx);

效果圖:


對已有的圖片進行大小設置

//加載Word文檔
Document document = new Document("Image.docx");
 
//獲取第一個節
Section section = document.Sections[0];
//獲取第一個段落
Paragraph paragraph = section.Paragraphs[0];
 
//調整段落中圖片的大小 
foreach (DocumentObject docObj in paragraph.ChildObjects)
{
    if (docObj is DocPicture)
    {
        DocPicture picture = docObj as DocPicture;
        picture.Width = 50f;
        picture.Height = 50f;
    }
}
 
//保存文檔 
document.SaveToFile("ResizeImages.docx");


效果圖:

C#操作Word對象:
指定位置  :  設置書籤。
主要代碼:

Word.Application oWord;
 Word.Document oDoc;
object name= "d:\\myfile.doc";
  object Range=System.Reflection.Missing.Value;
object bookmarks="C2";
oWord = new Word.ApplicationClass();
oWord.Visible = true;

//打開文檔
oDoc = oWord.Documents.Open(ref name, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref  oMissing, ref  oMissing, ref oMissing, ref oMissing);
oDoc.Bookmarks.get_Item(ref bookmarks).Select();               
//插入圖片 並設置圖片大小 
InlineShape il=oWord.Selection.InlineShapes.AddPicture("c:\\wjjpg.jpg", ref oMissing, ref oMissing, ref Range);
  il.Width = 40;
  il.Height = 50;

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