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

效果图:

C# 设置Word文档中图片的大小
对已有的图片进行大小设置

//加载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文档中图片的大小

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;