I'm having big problems with a code that should add watermark pictures (used as stationery) to a document before saving it as PDF. Inserting the picture to all relevant headers is no problem. But as soon as I try to strech the picture (shape) to the whole page width and height, Word 2007 (SP3) throws an exception. The same code works fine in Word 2010 (SP1). It doesn't matter if I use the Office 12 or Office 14 interop assemblies (always used with "Embed Interop Types" true).
The exception thrown is the following:
System.Runtime.InteropServices.COMException (0x800A122C): Falscher Zeichnungselement-Typ für diesen Befehl.
at Microsoft.Office.Interop.Word.Shape.set_RelativeHorizontalSize(WdRelativeHorizontalSize prop)
at BEKO.PDB.AuxiliaryServices.Documents.WordCreationService.AddWatermarkToHeader(HeaderFooter header, String watermarkFilePath)
I don't know exactly what the english error message would be, but the translation is something like "Invalid painting type (or maybe shape type) for this command".
The weird thing is that it doesn't always error on the same interop call. If I remove the line that sets the RelativeHorizontalSize
property it fails when setting another property, like WidthRelative
(with the same exception). If I add a line that sets shape.LeftRelative
(to the "do not use" constant) it even fails on a line that otherwise works like shape.Top
(again with the same exception).
The code I'm using is from a macro that was recorded in the failing Word 2007. I'm also correctly switching to the header SeekView before executing any header related code because I already needed that for some other header/footer code.
Here is the full code that adds the shape. It should just insert the picture and strech it to the full page size. Note: This method is only called for headers that are actually existing (headerFooter.Exists
) and that are not linked to the previous (!headerFooter.LinkToPrevious
).
private static void AddWatermarkToHeader(HeaderFooter header, string watermarkFilePath) {
header.Range.Editors.Add(WdEditorType.wdEditorEveryone);
Shape shape = header.Shapes.AddPicture(
FileName: watermarkFilePath,
LinkToFile: false,
SaveWithDocument: true
);
shape.WrapFormat.AllowOverlap = (int)MsoTriState.msoTrue;
shape.WrapFormat.Type = WdWrapType.wdWrapNone;
shape.RelativeHorizontalPosition = WdRelativeHorizontalPosition.wdRelativeHorizontalPositionPage;
shape.RelativeVerticalPosition = WdRelativeVerticalPosition.wdRelativeVerticalPositionPage;
shape.Left = 0;
shape.Top = 0;
shape.RelativeHorizontalSize = WdRelativeHorizontalSize.wdRelativeHorizontalSizePage;
shape.RelativeVerticalSize = WdRelativeVerticalSize.wdRelativeVerticalSizePage;
shape.WidthRelative = 100;
shape.HeightRelative = 100;
shape.ZOrder(MsoZOrderCmd.msoSendBehindText);
}
Please give any advice how to fix this so that the code works with both Word 2007 and Word 2010.