So with Visual Studio/C# and Microsoft.Office.Interop.Word;
I have this code which places text correctly to the word doc
private void WriteBookLine(string theLine, int al, string font, int fontSize, int fontBold, int spaceAfter)
{
paraTop = doc.Content.Paragraphs.Add(ref oMissing);
paraTop.Range.Text = theLine;
if (al == 0)
paraTop.Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
else if (al == 1)
paraTop.Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphLeft;
paraTop.Range.Font.Name = font;
paraTop.Range.Font.Size = fontSize;
paraTop.Range.Font.Bold = fontBold;
paraTop.Format.SpaceAfter = spaceAfter;
paraTop.Range.InsertParagraphAfter();
}
But when I call this code to place a picture as the next paragraph in the word doc
private void WriteBookImage(int im)
{
paraTop = doc.Content.Paragraphs.Add(ref oMissing);
if (im == 0)
{
doc.InlineShapes.AddPicture(@"C:\Users\fred\source\repos\xxx\wwwroot\images\yyy.png");
}
paraTop.Range.InsertParagraphAfter();
}
This places the image at the very top of the document on page 1, line 1 instead as the next paragraph, any ideas where I am going wrong please
Cheers
Kev
Try this first:
private void WriteBookImage(int im)
{
paraTop = doc.Content.Paragraphs.Add(ref oMissing);
if (im == 0)
{
//you should specify the range [where] to add inlineshpae
//in this case, doc will be the [where] and the last InlineShape in the doc will be the exactly [where]
//doc.InlineShapes.AddPicture(@"C:\Users\fred\source\repos\xxx\wwwroot\images\yyy.png");
//in this case, paraTop(the last paragrahp you just added it in before) will be the [where]
// the [where] argument just like the parameter Range of the object Hyperlinks Bookmark, etc, and Anchor of the object Shape, in their method Add.
//paraTop.Range.InlineShapes.AddPicture(@"C:\Users\fred\source\repos\xxx\wwwroot\images\yyy.png");
doc.InlineShapes.AddPicture(@"C:\Users\fred\source\repos\xxx\wwwroot\images\yyy.png", Range:paraTop.Range.Next()); // specify by argument Range, use Next methot to get the new paragraph just be added before.
//In my testing yesterday, I found an error in the official documentation, and have already submitted a correction:
//Returns a **Paragraph** object When the caller is not the last paragraph in a document, that represents a new, blank paragraph added to a document, otherwise, that will be the calling paragraph itself.
//https://github.com/MicrosoftDocs/VBA-Docs/pull/1727/commits/ddd0bbe1b29e90a64012dd8d1e9ec9a1a3c86e4f
//https://github.com/MicrosoftDocs/office-developer-word-pia-ref-dotnet/pull/22#issuecomment-1637070970
}
paraTop.Range.InsertParagraphAfter();
// if you want to insert the new paragraph here then :
//paraTop.Range.Next().InlineShapes.AddPicture(@"C:\Users\fred\source\repos\xxx\wwwroot\images\yyy.png");
}