【问题标题】:Inserting images in word using C# between the sentence在句子之间使用C#在word中插入图像
【发布时间】:2019-11-12 21:36:23
【问题描述】:

我有一个 MS word 文件,里面有一些句子,我需要在两行之间插入一些图像。当我在Microsoft.Office.Interop.Word 中使用AddPicture 方法时,我可以插入图像,但不能插入特定位置。

我没有找到除AddPicture 之外的任何插入方法来将图像插入现有的word 文件。 我正在尝试在苹果之后的特定行之后插入一张图片,那里应该有一张苹果的图片

在这里,我正在创建一个段落并尝试添加图像。这是我的初始文件:

这包含包含苹果、芒果和葡萄等词的段落。

这是我的代码的输出(下)

图片应该插在苹果线之后 所需输出:

Required Output

using System;
using System.Collections.Generic;
using System.Reflection;
using System.Reflection.Metadata;
using Word =Microsoft.Office.Interop.Word;
using System.IO;
namespace ConsoleApp2 
{
    class Program
    {
        static void Main(string[] args)
        {
            Word.Application ap = new Word.Application();
            Word.Document document = ap.Documents.Open(@"C:\Users\ermcnnj\Desktop\Doc1.docx");
            //document.InlineShapes.AddPicture(@"C:\Users\ermcnnj\Desktop\apple.png");
            String read = string.Empty;
            List<string> data = new List<string>();
            for (int i = 0; i < document.Paragraphs.Count; i++)
            {
                string temp = document.Paragraphs[i + 1].Range.Text.Trim();
                if (temp != string.Empty && temp.Contains("Apple"))
                {
                    var pPicture = document.Paragraphs.Add();
                    pPicture.Format.SpaceAfter = 10f;
                    document.InlineShapes.AddPicture(@"C:\Users\ermcnnj\Desktop\apple.png", Range: pPicture.Range);
                }

            }

        }
    }
}

以上是我正在使用的代码。

【问题讨论】:

    标签: c# image ms-word insertion


    【解决方案1】:

    以下代码 sn-p 说明了如何做到这一点。注意。为了清楚起见,仅设置要查找的文本进行了简化-可能需要指定许多其他属性;阅读 Word 语言参考中的 Find 功能。

    如果找到搜索词,则与 Find 关联的 Range 会更改找到的词并且可以采取进一步的操作。在这种情况下,在找到的术语之后插入一个新的(空)段落。 (问题指定该术语是段落的全部内容,所以这就是本示例所假设的内容!)然后将Range 移动到这个新段落并插入InlineShape

    注意图形是如何分配给InlineShape 对象的。如果需要对此对象执行任何操作,请使用对象变量 ils

    Word.Application ap = new Word.Application();
    Word.Document document = ap.Documents.Open(@"C:\Users\ermcnnj\Desktop\Doc1.docx");
    
    Word.Range rng = document.Content;
    Word.Find wdFind = rng.Find;
    
    wdFind.Text = "apple";
    bool found = wdFind.Execute();
    
    if (found)
    {
        rng.InsertAfter("\n");
        rng.MoveStart(Word.WdUnits.wdParagraph, 1);
        Word.InlineShape ils = rng.InlineShapes.AddPicture(@"C:\Test\avatar.jpg", false, true, rng);
     }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-12
      • 2011-07-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多