How to insert Page break when creating MS Word document - c#

I trying to create a Word document via C#. I want to be able to insert a page break at a certain point in my code, however I am not sure on how to do this. I am mostly using StringBuilder to create the html.
This is being done in Visual studios 2010 with c#. I've looked at some guides but most of them use code like "Word variable". So I'm not sure if "Word" comes from an extra downloaded library or what not.

Here is an example of writing some text to the word doc then adding a page break. Then writing the rest to the text to the document. In order to get a better answer you may need to rewrite your question as it is unclear when you want to insert a break and how you are writing the information to the document. I am assuming a lot which is never good.
using Word = Microsoft.Office.interop.Word;
//create a word app
Word._Application wordApp = new Word.Application();
//add a page
Word.Document doc = wordApp.Documents.Add(Missing.Value, Missing.Value, Missing.Value, Missing.Value);
//show word
wordApp.Visible = true;
//write some tex
doc.Content.Text = "This is some content for the word document.\nI am going to want to place a page break HERE ";
//inster a page break after the last word
doc.Words.Last.InsertBreak(Word.WdBreakType.wdPageBreak);
//add some more text
doc.Content.Text += "This line should be on the next page.";
//clean up
Marshal.FinalReleaseComObject(wordApp);
Marshal.FinalReleaseComObject(doc);
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();

If the location you would like to insert the page break is selected (by Word.Selection) :
The easiest way is to insert there the following code:
selection.TypeText("\f");

Related

Using C# to programmatically find, and populate bookmarks in a Word 2010 Add-In

I have a Microsoft word 2010 add-in project in visual studio, I just followed the MSDN guide to making a new tab with custom functionality on the ribbon. I've done some googling, but I cant seem to find any examples (or if its even possible) to use the C# to find a bookmark, then use the bookmarks name in an SQL query and populate it. The documents I am working with can have dozens of bookmarks, and there are hundreds of documents. Automating this process is a high priority.
So basically if you want to automate word documents (building word document templates via word bookmarks) Here's how I normally go about doing it.
Copy The Template
Work On The Template
Save In Desired Format
Delete Template Copy
Each of the sections that you are replacing within your word document you have to insert a bookmark for that location (easiest way to input text in an area).
I always create a function to accomplish this, and I end up passing in the path - as well as all of the text to replace my in-document bookmarks. The function call can get long sometimes, but it works for me.
Application app = new Application();
Document doc = app.Documents.Open("sDocumentCopyPath.docx");
if (doc.Bookmarks.Exists("bookmark_1"))
{
object oBookMark = "bookmark_1";
doc.Bookmarks.get_Item(ref oBookMark).Range.Text = My Text To Replace bookmark_1;
}
if (doc.Bookmarks.Exists("bookmark_2"))
{
object oBookMark = "bookmark_2";
doc.Bookmarks.get_Item(ref oBookMark).Range.Text = My Text To Replace bookmark_2;
}
doc.ExportAsFixedFormat("myNewPdf.pdf", WdExportFormat.wdExportFormatPDF);
((_Document)doc).Close();
((_Application)app).Quit();
This code should get you up and running unless you want to pass in all the values into a function.
Sometimes if you have large amounts of fields you can build objects/classes to contain the values.
If you need more examples I'm working on a blog post as well, so I have a lot more detail if this wasn't clear enough for your use case.
You can use Spire.Doc or FreeSpire.Doc library for this purpose. I have a github repo, that I showed an example how to working it.
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
using System;
using System.Configuration;
using System.Drawing;
using System.IO;
namespace WorkingDocAndPdf
{
class Program
{
static void Main(string[] args)
{
var sourceFilePath = ConfigurationManager.AppSettings["SourceFilePath"];
var saveFilePath = ConfigurationManager.AppSettings["SaveFilePath"];
var document = new Document(sourceFilePath);
var bookmarksNavigator = new BookmarksNavigator(document);
bookmarksNavigator.MoveToBookmark("client_name");
bookmarksNavigator.ReplaceBookmarkContent("Ramil", true);
bookmarksNavigator.MoveToBookmark("client_taxno");
bookmarksNavigator.ReplaceBookmarkContent("VN-12300254178XY6", true);
bookmarksNavigator.MoveToBookmark("amount");
bookmarksNavigator.ReplaceBookmarkContent("871 AZN", true);
bookmarksNavigator.MoveToBookmark("date");
bookmarksNavigator.ReplaceBookmarkContent(DateTime.Now.ToString("dd.MM.yyyy"), true);
//It is for picture
var sealPath = ConfigurationManager.AppSettings["SealPath"];
bookmarksNavigator.MoveToBookmark("seal", true, true);
var section = document.AddSection();
var image = Image.FromFile(sealPath);
var paragraph = section.AddParagraph();
paragraph.AppendPicture(image);
bookmarksNavigator.InsertParagraph(paragraph);
document.Sections.Remove(section);
if (!Directory.Exists(saveFilePath))
Directory.CreateDirectory(saveFilePath);
var saveFileFullPath = $"{saveFilePath}\\{Guid.NewGuid()}.pdf";
//It is for refresh cross reference bookmark, that you can use one bookmark on different location in document. In word shortcut it is `CTRL A + F9`
document.IsUpdateFields = true;
document.SaveToFile(saveFileFullPath, FileFormat.PDF);
}
}
}
For more information, you can visit my github repo: WorkingDocAndPdf_FreeSpireDoc
My article about FreeSpire.Doc (but written in Azerbaijani): C# working Word and PDF files. Print forms

Page Layout of Sections with Novacode DocX

I am creating a document using Novacode DocX. I would like the entire document to be in landscape orienation, however I would also like to have several section breaks in the document. My code is laid out like this:
DocX doc = DocX.Create(fileName);
doc.PageLayout.Orientation = Novacode.Orientation.Landscape;
foreach (string page in pages)
{
doc.InsertSection(false);
Paragraph p = doc.InsertParagraph();
p.Append(page);
}
doc.PageLayout.Orientation = Novacode.Orientation.Landscape;
doc.SaveAs(Path.Combine(folderPath, fileName));
I've also tried adding doc.PageLayout.Orientation = Novacode.Orientation.Landscape inside the loop after doc.InsertSection(false) and I can't get anything past the first page to turn to landscape.
Is there a way around this?
See this answer from Delford Chaffin: https://stackoverflow.com/a/33178151/316578
"Creating the different sections as separate documents and inserting them into the main document worked well and solved all my problems."

C# Populate word template with OpenXml

I would like to create a new Word document which is based on a template with content controls.
I need to fill those contents controls (text).
I only found how to generate a new Word document but not bases on a template.
Do you have any link or tutorial ?
Maybe am I wrong using OpenXml to fill a template ?
// Create a Wordprocessing document.
using (WordprocessingDocument myDoc =
WordprocessingDocument.Create("d:/dev/test.docx",
WordprocessingDocumentType.Document))
{
// Add a new main document part.
MainDocumentPart mainPart = myDoc.AddMainDocumentPart();
//Create Document tree for simple document.
mainPart.Document = new Document();
//Create Body (this element contains
//other elements that we want to include
Body body = new Body();
//Create paragraph
Paragraph paragraph = new Paragraph();
Run run_paragraph = new Run();
// we want to put that text into the output document
Text text_paragraph = new Text("Hello World!");
//Append elements appropriately.
run_paragraph.Append(text_paragraph);
paragraph.Append(run_paragraph);
body.Append(paragraph);
mainPart.Document.Append(body);
// Save changes to the main document part.
mainPart.Document.Save();
}
Going OpenXML is the right approach, because you can manipulate documents without the need to have MS Word installed – think server scenarios. However, its learning curve is steep and tedious. In my humble opinion, the best way is to ask for a budget to purchase a 3rd party toolkit and focus on the business domain and not on OpenXML tweaks.
In your example, you have a template in Word and want to update (merge) it with data. I have done this with Docentric Toolkit for some of our scenarios and it works very well. Once you understand the basics of how it works you create solutions quickly. If you get stuck guys at DT won’t let you down. See this link (http://www.codeproject.com/Articles/759408/Creating-Word-documents-in-Net-using-Docentric-Too) to get the idea on how you can use it. By default it creates .docx, but you can get fixed final documents (pdf or xps) as well.

Adding a tab stop to a paragraph range in c#

I need help with adding a tab stop(position at 1cm) to a word document using word interop and c#. This is what i tried already.
Range range = paragraph.Range;
int firstTabStart = range .Start;
range .SetRange(firstTabStart, firstTabStart);
range .Paragraphs.TabStops.Add(5, WdTabAlignment.wdAlignTabRight);
When i open my word document i dont see any tab stops.
I can however insert tab alignments using
range .InsertAlignmentTab((int)WdAlignmentTabAlignment.wdCenter,
(int)WdAlignmentTabRelative.wdMargin);
Although, these tabs are absolute and I cannot edit them in the word document.
Please help.
I'm not able to reproduce the issue you're having, but I'm pasting the code I tested with so you can see if it differs any way from your existing code.
I saw tab stops appear in the ruler at 1 & 2 cm in every case:
Using either a .doc or .docx
Using paragraphs.TabStops instead of range.Paragraphs.TabStops
Using a blank document
Using a document with 1 or more paragraphs
Passing in 3rd argument for WdTabLeader in the TabStops.Add method.
And this was done in Word 2010
class Start
{
public static void Main()
{
// Open a doc file.
Application application = new Application();
Document document = application.Documents.Open(#"C:\Users\mmonkan\Documents\word.docx");
Paragraphs paragraphs = document.Paragraphs;
Paragraph paragraph = paragraphs[1];
Range range = paragraph.Range;
range.SetRange(0, 0);
range.Paragraphs.TabStops.Add(28, WdTabAlignment.wdAlignTabRight);
range.Paragraphs.TabStops.Add(56, WdTabAlignment.wdAlignTabRight);
// Close word.
application.Quit(WdSaveOptions.wdSaveChanges);
Console.ReadLine();
}
}

Replacing bookmarks in docx file using OpenXml SDK and C++/CLI

I am trying to replace bookmark in docx with text in c++\cli using open xml SDK concept.
The below piece of code will fetch bookmarks from word document and checks whether the bookmark matches the string “VERSION” if it is true, it is replaced with the string “0000” in the docx file.
Paragraph ^paragraph = gcnew Paragraph();
Run ^run = gcnew Run();
DocumentFormat::OpenXml::Wordprocessing::Text^ text = gcnew DocumentFormat::OpenXml::Wordprocessing::Text(“0000”);
run->AppendChild(text);
paragraph->AppendChild(run);
IDictionary<String^, BookmarkStart^> ^bookmarkMap =
gcnew Dictionary<String^, BookmarkStart^>();
for each (BookmarkStart ^bookmarkStart in
GlobalObjects::wordDoc->MainDocumentPart->RootElement->Descendants<BookmarkStart^>())
{
if (bookmarkStart->Name->Value == “VERSION”)
{
bookmarkStart->Parent->InsertAt<Paragraph^>(paragraph,3);
}
}
The above code works fine in most scenarios(wherever we insert bookmarks), but sometimes times it fails and I am not able to find the reason.
And if the bookmark is inserted at the starting position of a line, then after execution I am not able to open the docx file, there will be some errors.
I tried giving the index value as 0 for InserAt method even this is not working.
Please provide a solution for the above.
Thanks in advance
See How to Retrieve the Text of a Bookmark from an OpenXML WordprocessingML Document for code that retrieves text. It is written in C#, but you could use the code directly from C++/CLI.
See Replacing Text of a Bookmark in an OpenXML WordprocessingML Document for an algorithm that you can use to replace text.

Categories

Resources