如何使用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();
答案 0 :(得分:0)
根据评论中的进一步讨论,我已编辑原始问题以使其更清晰。
考虑到您已有的代码:您最终只能看到一张图片的原因是:
docRange = wordDoc.Range();
docRange.Paste();
在代码的开头,声明一个Object变量:
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();