如何在不压缩的情况下将多张图片添加到文档 (Office.Interop.Word)

How to add multiple pictures to document without getting compressed (Office.Interop.Word)

如何使用 Interop.Word 程序集将多张图片添加到 MS Word 中? 非常重要的是它必须不失质量。我发现使用以下代码可以获得最佳质量的结果:

它作为InlinePicture 插入以获得缩放信息,然后删除分辨率较差的图形。然后将图像插入到 Shape 对象中,校正缩放比例,然后将 Shape 转换为 InlineShape 作为最终结果。

如何确保后续的每次插入都不会替换之前的插入。 我需要在此代码中的何处插入 docRange.Collapse() 或如何更改以下代码(使用 newShape 的变体在结果中提供了所需的质量):

            Application wordApp = new Application();
            Document wordDoc = wordApp.Documents.Add();
            float scaledWidth;
            float scaledHeight;
            Shape newShape;
            InlineShape finalInlineShape;
            Range docRange;
            foreach (var filepath in path)
            {
                InlineShape autoScaledInlineShape = wordDoc.InlineShapes.AddPicture(filepath);
                scaledWidth = autoScaledInlineShape.Width;
                scaledHeight = autoScaledInlineShape.Height;
                autoScaledInlineShape.Delete();

                newShape = wordDoc.Shapes.AddShape(1, 0, 0, scaledWidth, scaledHeight);
                newShape.Fill.UserPicture(filepath);

                finalInlineShape = newShape.ConvertToInlineShape();
                finalInlineShape.Line.Visible = Microsoft.Office.Core.MsoTriState.msoFalse;

                finalInlineShape.Range.Cut();
                docRange = wordDoc.Range();
                docRange.Paste();

            }   
            wordDoc.SaveAs2(@"C:\test\Project.docx");
            wordDoc.Close();
            wordApp.Quit();

基于评论中的进一步讨论,我编辑了原始问题以使其更清楚。

考虑到您已有的代码:您最后只看到一张图片的原因是:

 docRange = wordDoc.Range();
 docRange.Paste();

在代码的开头,声明一个对象变量:

 object oCollapseEnd = Word.WdCollapseDirection.wdCollapseEnd;

并将行更改为:

 docRange = wordDoc.Content; //better than using the Range() method
 //Optional, you may want this:
 //docRange.InsertParagraphAfter();
 docRange.Collapse(ref oCollapseEnd);
 docRange.Paste();