如何使用 Microsoft.Office.Interop.Word 程序集在不降低质量的情况下将图片添加到 Word 文档?

在word文档中插入图片的常用方法是:

Application wordApp = new Application();
Document wordDoc = wordApp.Documents.Add();
Range docRange = wordDoc.Range();

string imageName = @"c:\temp\win10.jpg";
InlineShape pictureShape = docRange.InlineShapes.AddPicture(imageName);

wordDoc.SaveAs2(@"c:\temp\test.docx");
wordApp.Quit();

这种方式压缩了图片。

有可选的 LinkToFileSaveWithDocument 参数,但保存的图像是压缩的,不需要链接,因为图片文件不能存在于外部。

对于 Excel,有一个带有 Shapes.AddPicture2 参数的 MsoPictureCompress Method 似乎是为了这个。但我找不到 Word 的任何等价物。

最佳答案

到目前为止,我只找到了解决此问题的方法:

Application wordApp = new Application();
Document wordDoc = wordApp.Documents.Add();
Range docRange = wordDoc.Range();

string imagePath = @"c:\temp\win10.jpg";

// Create an InlineShape in the InlineShapes collection where the picture should be added later
// It is used to get automatically scaled sizes.
InlineShape autoScaledInlineShape = docRange.InlineShapes.AddPicture(imagePath);
float scaledWidth = autoScaledInlineShape.Width;
float scaledHeight = autoScaledInlineShape.Height;
autoScaledInlineShape.Delete();

// Create a new Shape and fill it with the picture
Shape newShape = wordDoc.Shapes.AddShape(1, 0, 0, scaledWidth, scaledHeight);
newShape.Fill.UserPicture(imagePath);

// Convert the Shape to an InlineShape and optional disable Border
InlineShape finalInlineShape = newShape.ConvertToInlineShape();
finalInlineShape.Line.Visible = Microsoft.Office.Core.MsoTriState.msoFalse;

// Cut the range of the InlineShape to clipboard
finalInlineShape.Range.Cut();

// And paste it to the target Range
docRange.Paste();

wordDoc.SaveAs2(@"c:\temp\test.docx");
wordApp.Quit();

关于c# - Office.Interop.Word : How to add a picture to document without getting compressed,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38227689/

10-12 12:45
查看更多