Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Office.Interop.Word: How to add a picture to document without getting compressed

How can I add a picture to a word document without loosing quality using the Microsoft.Office.Interop.Word assembly?

The common way to insert a picture to word document is:

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();

This way compresses the picture.

There are optional LinkToFile and SaveWithDocument parameters but the saved image is compressed and a link is not wanted because picture file mustn't exist externally.

For Excel there is the Shapes.AddPicture2 Method with MsoPictureCompress parameter which seems to be for this. But I cannot find any equivalent for Word.

like image 928
Martin Schneider Avatar asked Mar 12 '23 18:03

Martin Schneider


2 Answers

So far I have only found a workaround for this issue:

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();
like image 135
Martin Schneider Avatar answered May 03 '23 15:05

Martin Schneider


According to Microsoft documentation 2002066 you can add the following DWORD entry...

AutomaticPictureCompressionDefault = 0

...to the following registry keys:

For PowerPoint:

HKEY_CURRENT_USER\Software\Microsoft\Office\12.0\PowerPoint\Options

For Word:

HKEY_CURRENT_USER\Software\Microsoft\Office\12.0\Word\Options

For Excel:

HKEY_CURRENT_USER\Software\Microsoft\Office\12.0\Excel\Options

This still works in Office 2019/Office 365 (You need to change 12.0 to 16.0 then). However, all future documents will not compress any images! This may result in very large file sizes!

like image 35
Marc Avatar answered May 03 '23 16:05

Marc