How to insert a page at the end of a document? - c#

I am doing some VSTO development for Word using C#. I am having a hard time figuring out how to insert a page(a .docx file) at the end of my active document.

WORD._Application app = new WORD.Application();
WORD._Document doc = app.Documents.Open ... ;
WORD.Selection selection = app.Selection;
object breakType = WORD.WdBreakType.wdPageBreak;
selection.InsertBreak(ref breakType);

Related

C# .Net - Insert text in Bookmark without opening Word

I managed to insert a text in a Bookmark of a Word document using Microsoft.Office.Interop.Word.
using Microsoft.Office.Interop.Word;
using Application = Microsoft.Office.Interop.Word.Application;
using Range = Microsoft.Office.Interop.Word.Range;
Application app = new Microsoft.Office.Interop.Word.Application();
Document doc = app.Documents.Open(#"C:\wordDocument.docx");
string bookmark = "bookmarkName";
Bookmark bm = doc.Bookmarks[bookmark];
Range range = bm.Range;
range.Text = "Hello World";
doc.Bookmarks.Add(bookmark, range);
/* OR
doc.Bookmarks[bookmark].Select();
app.Selection.TypeText("Hello");
*/
The problem is this also opened the Word document. Can this be done without opening the document itself? Like its all happening in the background?
Try using the Save and Close function after updating the text of the Bookmark of your Word Document.
Add the below code after the doc.Bookmarks.Add(bookmark, range);.
doc.Save();
doc.Close();
EDIT:
If the computer is slow, the Word document might show within a second since you open it up. As hardcoregamer said, you can try to hide the object of Word.Application first before opening it.
using Microsoft.Office.Interop.Word;
using Application = Microsoft.Office.Interop.Word.Application;
using Range = Microsoft.Office.Interop.Word.Range;
Application app = new Microsoft.Office.Interop.Word.Application();
app.Visible = false; //Hide the Word.Application object.
Document doc = app.Documents.Open(#"C:\wordDocument.docx");
string bookmark = "bookmarkName";
Bookmark bm = doc.Bookmarks[bookmark];
Range range = bm.Range;
range.Text = "Hello World";
doc.Bookmarks.Add(bookmark, range);
doc.Save(); //save the document.
doc.Close(); //close the document.
app.Quit(); //close the Word.Application object. otherwise, you'll get a ReadOnly error later.

Word Interop Bookmarks Dont Exist

I am currently creating a c# program which uses a template.dotx containing pre-defined building blocks (with bookmarks) to insert pages of content into a new document, all working as follows
Word._Application oWord;
Word._Document oDoc;
object oMissing = System.Reflection.Missing.Value;
object bAddress = "bAddress";
oWord = new Word.Application();
object oTemplate = _template;
oDoc = oWord.Documents.Add(ref oTemplate, ref oMissing,
ref oMissing, ref oMissing);
Word.Template objTmpl = (Word.Template)oDoc.get_AttachedTemplate();
Word.BuildingBlock objBB = objTmpl.BuildingBlockEntries.Item("PageBB");
Range where = oDoc.Range(oDoc.Content.End - 1, oDoc.Content.End - 1);
var orng = objBB.Insert(where, true);
orng.Bookmarks[bAddress].Range.Text = "Address";
I would like to do this in reverse, to open created file at a later date, and read through each bookmark to get the value.
The problem is when I open the resulting DocXCreatedFromTemplate.docx, the bookmarks have disappeared. Programmatically, I receive the bookmark not in collection error, but also by allowing word to open and checking manually the bookmarks are replaced with text but the bookmark reference has gone.
Is there any way to get round this?
I have worked this out, the following text replaces and deletes the bookmark
orng.Bookmarks[bAddress].Range.Text = "Address";
The solution was to re-add the bookmark afterwards using a method as follows
private void UpdateBookmarkWithoutDeleting(object bookmark, string text, _Document document)
{
var bookmarkRange = document.Bookmarks[bookmark].Range;
bookmarkRange.Text = text;
document.Bookmarks.Add(bookmark.ToString(), bookmarkRange);
}
I found the information at the following link (in VB):
https://wordmvp.com/FAQs/MacrosVBA/InsertingTextAtBookmark.htm

How to get exact page from .doc?

So i have a .doc with many pages and i want to open a specific page within C#. Here is the code i'm using to view the doc
string docPath = #"...\path\to\doc.doc";
Microsoft.Office.Interop.Word.Application app = new
Microsoft.Office.Interop.Word.Application();
Document doc = app.Documents.Open(docPath);
string words = doc.Content.Text;
doc.Close();
app.Quit();

Word Export ASP.NET MVC Beginner

i'm new to ASP.NET MVC and tried to generate an export from Formdata to word file. That worked quite well, all the Bookmarks in the Document are filled correctly with following code:
string savePath = (#"U:\Coding ASP.MVC\WebForm Export into WordFile\Gutachten.docx");
string templatePath = (#"U:\Coding ASP.MVC\WebForm Export into WordFile\wordTemplate.docx");
Microsoft.Office.Interop.Word.Application app = new Microsoft.Office.Interop.Word.Application();
Microsoft.Office.Interop.Word.Document doc = new Microsoft.Office.Interop.Word.Document();
doc = app.Documents.Open(templatePath);
doc.Activate();
if (doc.Bookmarks.Exists("FileNoSIS"))
{
doc.Bookmarks["FileNoSIS"].Range.Text = FileNoSIS;
}
if (doc.Bookmarks.Exists("NameOfAction"))
{
doc.Bookmarks["NameOfAction"].Range.Text = NameOfAction;
}
doc.SaveAs2(savePath);
app.Application.Quit();
Response.Write("Success");
But now i want to get the thing done with a stream to edit the document and offer the new filled document as a download. Can anybody here give me some advice or any tip how to get there?
Thx

Replace a bookmark in a Word document with the contents of another word document

I'm looking to replace a bookmark in a word document with the entire contents of another word document. I was hoping to do something along the lines of the following, but appending the xml does not seem to be enough as it does not include pictures.
using Word = Microsoft.Office.Interop.Word;
...
Word.Application wordApp = new Word.Application();
Word.Document doc = wordApp.Documents.Add(filename);
var bookmark = doc.Bookmarks.OfType<Bookmark>().First();
var doc2 = wordApp.Documents.Add(filename2);
bookmark.Range.InsertXML(doc2.Contents.XML);
The second document contains a few images and a few tables of text.
Update: Progress made by using XML, but still doesn't satisfy adding pictures as well.
You've jumped in deep.
If you're using the object model (bookmark.Range) and trying to insert a picture you can use the clipboard or bookmark.Range.InlineShapes.AddPicture(...). If you're trying to insert a whole document you can copy/paste the second document:
Object objUnit = Word.WdUnits.wdStory;
wordApp.Selection.EndKey(ref objUnit, ref oMissing);
wordApp.ActiveWindow.Selection.PasteAndFormat(Word.WdRecoveryType.wdPasteDefault);
If you're using XML there may be other problems, such as formatting, images, headers/footers not coming in correctly.
Depending on the task it may be better to use DocumentBuilder and OpenXML SDK. If you're writing a Word addin you can use the object API, it will likely perform the same, if you're processing documents without Word go with OpenXML SDK and DocumentBuilder. The issue with DocumentBuilder is if it doesn't work there aren't many work-arounds to try. It's open source not the cleanest piece of code if you try troubleshooting it.
You can do this with openxml SDK and Document builder. To outline here is what you will need
1> Inject insert key in main doc
public WmlDocument GetProcessedTemplate(string templatePath, string insertKey)
{
WmlDocument templateDoc = new WmlDocument(templatePath);
using (MemoryStream mem = new MemoryStream())
{
mem.Write(templateDoc.DocumentByteArray, 0, templateDoc.DocumentByteArray.Length);
using (WordprocessingDocument doc = WordprocessingDocument.Open([source], true))
{
XDocument xDoc = doc.MainDocumentPart.GetXDocument();
XElement bookMarkPara = [get bookmarkPara to replace];
bookMarkPara.ReplaceWith(new XElement(PtOpenXml.Insert, new XAttribute("Id", insertKey)));
doc.MainDocumentPart.PutXDocument();
}
templateDoc.DocumentByteArray = mem.ToArray();
}
return templateDoc;
}
2> Use document builder to merge
List<Source> documentSources = new List<Source>();
var insertKey = "INSERT_HERE_1";
var processedTemplate = GetProcessedTemplate([docPath], insertKey);
documentSources.Add(new Source(processedTemplate, true));
documentSources.Add(new Source(new WmlDocument([docToInsertFilePath]), insertKey));
DocumentBuilder.BuildDocument(documentSources, [outputFilePath]);

Categories