其他分享
首页 > 其他分享> > CodeGo.net> Office.Interop.Word:如何将图片添加到文档而不会被压缩

CodeGo.net> Office.Interop.Word:如何将图片添加到文档而不会被压缩

作者:互联网

如何使用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();

这样可以压缩图片.

有可选的LinkToFile和SaveWithDocument参数,但是已保存的图像被压缩,因此不需要链接,因为图片文件不能在外部存在.

对于Excel,似乎具有用于MsoPictureCompress参数的Shapes.AddPicture2 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,net,visual-studio,ms-word,office-interop
来源: https://codeday.me/bug/20191118/2028208.html