using System.IO;
using Word = Microsoft.Office.Interop.Word;
namespace Snapper
{
class WordDocumentGenerator
{
public void CreateWordDocument(string fileName)
{
string originalPath = Directory.GetCurrentDirectory();
string path = originalPath;
path += @"\snapshots";
object oMissing = System.Reflection.Missing.Value;
//Create a new Word Application
Word._Application wordApp = new Word.Application();
wordApp.Visible = false;
try
{
//Create a new blank document
object filePath = originalPath + @"\documents" + @"\TSC1.doc";
Word._Document doc = wordApp.Documents.Open(ref filePath,
ref oMissing,
ref oMissing,
ref oMissing,
ref oMissing,
ref oMissing,
ref oMissing,
ref oMissing,
ref oMissing,
ref oMissing,
ref oMissing,
ref oMissing,
ref oMissing,
ref oMissing,
ref oMissing,
ref oMissing);
string[] images = Directory.GetFiles(path);
//Create a range
object what = Word.WdGoToItem.wdGoToLine;
object which = Word.WdGoToDirection.wdGoToFirst;
object myTrue = true;
object myFalse = false;
doc.GoTo(ref what, ref which, ref oMissing, ref oMissing);
//Insert filename as header
var pText = doc.Paragraphs.Add(ref oMissing);
pText.Format.SpaceAfter = 10f;
pText.Range.Text = fileName;
pText.Range.InsertParagraphAfter();
foreach (var image in images)
{
var pImage = doc.Paragraphs.Add(ref oMissing);
pImage.Format.SpaceAfter = 10f;
object myRng = pImage.Range;
doc.InlineShapes.AddPicture(image, ref myFalse, ref myTrue, ref myRng);
}
path = originalPath;
path += @"\documents";
DirectoryInfo docDir = new DirectoryInfo(path);
if (!docDir.Exists)
{
docDir.Create();
}
object savePath = path + @"\" + fileName + ".doc";
doc.SaveAs(ref savePath,
ref oMissing,
ref oMissing,
ref oMissing,
ref oMissing,
ref oMissing,
ref oMissing,
ref oMissing,
ref oMissing,
ref oMissing,
ref oMissing,
ref oMissing,
ref oMissing,
ref oMissing,
ref oMissing,
ref oMissing
);
doc.Save();
}
finally
{
wordApp.Quit(ref oMissing, ref oMissing, ref oMissing);
}
}
}
}
I got suggestions from others to try this as well
wordApp.Selection.HomeKey(Unit: WdUnits.wdStory);
I've tried that as well as combination of the above two.
object units = Word.WdUnits.Story;
wordApp.Selection.HomeKey(ref units, ref oMissing);
var pText = doc.Paragraphs.Add(ref oMissing);
pText.Format.SpaceAfter = 10f;
pText.Range.InsertParagraphAfter();
The content is still getting appended to the end. Could anyone help me in setting up the cursor to start of document and then insert my new content from that position. Thanks in advance.