Adding a tab stop to a paragraph range in c# - 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();
}
}

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

Not able to Highlight a word inside word file using OpenXML

I am using Open XML SDK to highlight a specific word inside a docx file but I not able to do that, after an extensive research I did the following I tried to open the document and then edit the color of the word and save it again, but I get no thing saved while I found the document last edit time with now date.
What is wrong with that code?
void HighLightWord(string documentUrl, string word)
{
using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(documentUrl, true))
{
var body = wordDoc.MainDocumentPart.Document.Body;
var paras = body.Elements<Paragraph>();
DocumentFormat.OpenXml.Wordprocessing.Color color = new DocumentFormat.OpenXml.Wordprocessing.Color();
foreach (var para in paras)
{
foreach (var run in para.Elements<Run>())
{
foreach (var text in run.Elements<Text>())
{
if (text.Text.Contains(word))
{
color.Val = "365F91";
run.Append(color);
wordDoc.MainDocumentPart.Document.Save();
return;
}
}
}
}
wordDoc.Close(); // close the template file
}
}
Create a simple document in the Word application with the formatting you need. Save and close. Open the document in the Open XML SDK Productivity Tool. That will generate the code required to create the document. Then you can compare your code to that of the Tool's.
FWIW any kind of formatting is a child element of the RunProperties, so appending a color directly to the Run cannot work. In addition, you need to create an object for the kind of formatting (it's not clear from your description whether you want to change the text color or apply highlight formatting). That is what's appended to the RunProperties. It's also important that your code first check whether RunProperties are available for the Run. If not, that first needs to be created before anything can be appended to it.

Break Links PowerPoint 2010

I have been struggling with C# and PowerPoint, I posted earlier about how to update Links in ppt using C# if the links were set to manual, I didn't get any responses so I figured I would try to circumvent the issue by setting the links to automatic in the file, then when C# opens it it updates them, saves the file, and then breaks them and saves it as another file name, but that hasn't proven any easier.
All I need to know is how to break the links. I know some VBA and wrote a code to break them, but when I call a macro in C# with a RunMacro method it doesn't seem to be working with the method I am using (? - I'm new to C# so I don't fully understand why this is, but if you Google "run macro PowerPoint C#" you will find the way I am sure I tried to go about it.) Please help, I am at a complete loss.
My script looks something like this
Using PowerPoint = Microsoft.Office.Interop.PowerPoint;
public void Main()
{
PowerPoint.Application ppt = new PowerPoint.Application();
PowerPoint.Presentation PRS = ppt.Presentations.Open(#"Filename.pptm",
Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoTrue);
PRS.UpdateLinks();
PRS.Save
//here is where I need to break the links
PRS.SaveAs(#"filename with links broken.pptm",
Microsoft.Office.Interop.PowerPoint.PpSaveAsFileType.ppSaveAsOpenXMLPresentationMacroEnabled, MsoTriState.msoTrue);
PRS.Close();
ppt.Quit();
}
I tried setting the linkformat to manual before opening the file, but that doesn't affect any shapes that are already created, only new ones created within the program afterwards.
I have done a similar project in Powerpoint which also involves breaking links. In my program I am reading from an Excel file and take this data and put it into a Powerpoint presentation. In my Powerpoint template file I have all of my links to my Excel file laid out and formatted the way that I want it to look. The program begins to run and this fills the Excel file. After the writing to Excel is finished, I open up Powerpoint and UpdateLinks() to my presentation. Once the links are updated I break the links using a for loop on the Shapes in the Powerpoint. After, I save and close the document. Below is my function that I use to create my Powerpoint file based off of each of my ppt file templates (for my example I iterate through multiple ppt files because each ppt file contains only one slide. They are all combined into one slideshow later in the process).
public void CreatePowerpoint()
{
string[] fileArray = Directory.GetFiles(#"C:\Users\Me\Desktop\test");
Microsoft.Office.Interop.PowerPoint.Application pptApp = new Microsoft.Office.Interop.PowerPoint.Application();
for (int i = 0; i < fileArray.Length; i++)
{
string file = fileArray[i];
Microsoft.Office.Interop.PowerPoint.Presentation powerpoint = pptApp.Presentations.Open(file);
powerpoint.UpdateLinks();
Microsoft.Office.Interop.PowerPoint.Slides slides = powerpoint.Slides;
Microsoft.Office.Interop.PowerPoint.Slide slide = slides[1];
Microsoft.Office.Interop.PowerPoint.Shapes pptShapes = (Microsoft.Office.Interop.PowerPoint.Shapes)slide.Shapes;
foreach (Microsoft.Office.Interop.PowerPoint.Shape y in pptShapes)
{
Microsoft.Office.Interop.PowerPoint.Shape j = (Microsoft.Office.Interop.PowerPoint.Shape)y;
try
{
//If auto link update is disabled for links
//j.LinkFormat.j.Update();
if (j.LinkFormat != null)
{
j.LinkFormat.BreakLink();
}
}
catch (Exception)
{
}
}
powerpoint.SaveAs(#"C:\Users\Me\Desktop\test" + i + ".pptx");
powerpoint.Close();
Thread.Sleep(3000);
}
pptApp.Quit();
}
Changing things before opening a file will have no effect on files that aren't open, of course. Iterate through the shapes collection on each slide and for each shape:
If .Type = msoLinkedOLEObject Then
.LinkFormat.BreakLink
End If
msoLinkedOLEObject = 10

How to insert Page break when creating MS Word document

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");

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