DocX Set BookMark font styles C# - c#

I am using xceedsoftware/DocX to generate word documents from templates in C#, Unable to set styles for bookmark text alone. Trying to create extension, please find below code. I can only see option to set font styles for entire paragraph, not a single bookmark. Am I missing something. How do I set font style, background color, strikethrough, etc., for my bookmark text alone?
public static void ProcessBookMark(this DocX doc, string BookMarkName, string BookMarkValue, bool? Bold = false)
{
var Bm = doc.Bookmarks[BookMarkName];
if (Bm != null)
{
Bm.SetText(BookMarkValue);
Bm.Paragraph.Font("Arial");
if (Bold==true)
Bm.Paragraph.Bold();
}
}

Related

Search Word Document and hide range where Style.localName = "MyStyle"

I have a lot of Word documents where I need to hide text witch is formatted with a custom Word.Style type.
I’m using C# in a Windows Form and I’ve tried to open the Word documents one by one and go through all paragraphs. I then cast the paragraph style to a style object and from this I get the paragraphs Style localname.
Then if this paragraphs local style name matches one that I need to hide, then I try to take the paragraps.Range, select it, and set it to range.Font.Hidden = 1 I then try to save the document, but it document dosen’t change, so text formatted with my custom style does not change.
I've tried this so far:
using Word = Microsoft.Office.Interop.Word;
Word.Application wordApp = new Word.Application();
private void buttonOpenMany_Click(object sender, EventArgs e)
{
List<string> Styles = new List<string>();
Styles.Add("MyStyle1");
Styles.Add("MyStyle2");
Styles.Add("MyStyle3");
foreach (var item in Directory.GetFiles(textBoxWordFolder.Text,"*.docx"))
{
HideByStyleName(item, Styles);
}
MessageBox.Show("Done");
}
void HideByStyleName(string WordFile, List<string> StylesToHide)
{
wordApp.Documents.Open(WordFile);
Word.Document document = wordApp.ActiveDocument;
Word.Range rng = document.Content;
foreach (Word.Paragraph paragraph in document.Paragraphs)
{
Object styleobject = paragraph.get_Style();
string stylename = ((Word.Style)styleobject).NameLocal;
foreach (var style in StylesToHide)
{
if (stylename == style)
{
Word.Range range = paragraph.Range;
range.Select();
range.Font.Hidden = 1;
}
}
}
document.SaveAs2(WordFile);
document.Close();
}
I’ve also tried to use Range.Find.Execute but are having a hard time to figure out how to use this to find text where the Style.NameLocal =”MyCustomStyle1” And also who to replace this found range with Hidden text. Hope anyone have some input or guides.
Thank you and best regards
Rasmus

RichTextBox with source of rtf string displays incorrect

I have string with rft formatted text. I believe th string is correct, because when i enter in in notepad and save as rtf document, it is displayed correctly.
The problem is that the highlight is not applied to the text when i try to pass it to RichTextBox.
Expected result is RichtextBox with grey bold text with highlighted word "PORTS", but i get only bold grey text
Rtf string that I pass to RichTextBox:
"{\rtf1\ansi\ansicpg1252\deff0\nouicompat\deflang1033{\fonttbl{\f0\fnil\fcharset0 Segoe UI;}}{\colortbl;\red50\green146\blue255;\red235\green153\blue45;\red105\green105\blue105;}\viewkind0\uc1\pard\sa0\sl276\slmult1\cf0\f0\fs32\lang9\b\cf3\highlight2 PORTS\highlight0 documentation. \cf0\b0\par}"
Rtf string that I save as rtf document:
{\rtf1\ansi\ansicpg1252\deff0\nouicompat\deflang1033{\fonttbl{\f0\fnil\fcharset0 Segoe UI;}}{\colortbl;\red50\green146\blue255;\red235\green153\blue45;\red105\green105\blue105;}\viewkind0\uc1\pard\sa0\sl276\slmult1\cf0\f0\fs32\lang9\b\cf3\highlight2 PORTS\highlight0 documentation. \cf0\b0\par}
Example of rtf string that is displayed correctly(here text is not bald and not grey):
"{\rtf1\ansi\ansicpg1252\deff0\nouicompat\deflang1033{\fonttbl{\f0\fnil\fcharset0 Segoe UI;}}{\colortbl;\red50\green146\blue255;\red235\green153\blue45;\red105\green105\blue105;}\viewkind0\uc1\pard\sa0\sl276\slmult1\cf0\f0\fs30\lang9\highlight2 Port\highlight0 Serial \highlight2 port\highlight0 that uses COM \highlight2 port\highlight0 s\par}"
Method that i use to set string to RithTextBox:
private void UpdateRtf()
{
MemoryStream stream = new MemoryStream(ASCIIEncoding.Default.GetBytes(RtfString));
TextRange range = new TextRange(Document.ContentStart, Document.ContentEnd);
range.Load(stream, DataFormats.Rtf);
}

Set Title for Image in MS Word in order for Spire .NET to identify (locate) the image to replace it with a new one

I want to use Spire .NET to replace an image in a template and save as the output docx file. I use the code below to replace it. My problem is I don't know how to set the image title for the image in MS Word so that Spire knows where my image is to replace.
Document document = new Document("template.docx");
//Loop through the paragraphs of the section
foreach (Paragraph paragraph in document.Sections[0].Paragraphs)
{
//Loop through the child elements of paragraph
foreach (DocumentObject docObj in paragraph.ChildObjects)
{
if (docObj.DocumentObjectType == DocumentObjectType.Picture)
{
DocPicture picture = docObj as DocPicture;
if (picture.Title == "logo") // <--- I don't know how to set title in Word
{
//Replace the image
picture.LoadImage(Image.FromFile("logo.png"));
}
}
}
}
document.SaveToFile("generated.docx");
document.Close();
Right click on your picture -> Format Picture -> Layout & Properties -> ALT TEXT, then you will find the title part, see below picture (I'm using Office 2013).

VSTO Word Add-In : Content Control Nesting

I'm building an MS-Word Add-In for the company where I'm doing my internship.
I already created a new ribbon with lots of SplitButtons and Buttons.
Now what i want to do is when you click one of the buttons a content control will ba added to the word doc.
This works fine for Plain Content Controls. These content controls have tags like "sport/basketball/player/name" which is binded to an element in an XML file.
private void addSimpleContentControl(String tag, String placeholder)
{
try
{
contentControlPlain = Globals.ThisAddIn.Application.ActiveDocument.ContentControls.Add(Microsoft.Office.Interop.Word.WdContentControlType.wdContentControlText);
contentControlPlain.Tag = tag;
contentControlPlain.SetPlaceholderText(null, null, placeholder);
}
catch (COMException) { }
}
Now let's talk about my problem.
Some of my elements could be present for more then one time. So what i want to create is a Rich Content control which holds more than one Plain content control.
So i have a SplitButton "player" with buttons like "name","jersey number","position",.....
When one of the underlying buttons is clicked i first check if a rich text control with a specific name already exist.
If not than i make one and add one single Plain content control to it.
Rich content control-> plain text control -> end of Rich content control
So far so good, this all goes fine but from the moment i want to add another plain content control to the rich content control this pops up :
"Plain text controls cannot be inserted around other controls or XML elements"
here is my code to add a plain content control to a rich content control.
private void addContentControlToRich(String tag, String placeholder,String title)
{
Microsoft.Office.Interop.Word.Document doc = Globals.ThisAddIn.Application.ActiveDocument;
foreach (Microsoft.Office.Interop.Word.ContentControl cc in doc.ContentControls)
{
if (cc.Title == title && cc.Type == Microsoft.Office.Interop.Word.WdContentControlType.wdContentControlRichText)
{
try
{
Microsoft.Office.Interop.Word.Range rng = cc.Range;
object oRng = rng;
contentControlPlain = doc.ContentControls.Add(Microsoft.Office.Interop.Word.WdContentControlType.wdContentControlText, ref oRng);
contentControlPlain.Tag = tag;
contentControlPlain.SetPlaceholderText(null, null, placeholder);
contentControlPlain.LockContentControl = true;
break;
}
catch (COMException) { }
}
}
}
instead of
contentControlPlain = doc.ContentControls.Add(Microsoft.Office.Interop.Word.WdContentControlType.wdContentControlText, ref oRng);
use
contentControlPlain = richTextControl.Range.ContentControls.Add(Microsoft.Office.Interop.Word.WdContentControlType.wdContentControlText, ref oRng);
before using above code use code below
Application.Selection.Start = lastControlinRichTextControl.Range.End+1;
and set `oRng = Application.Selection.Range
As per the message, your code is trying to wrap a plain text control around everything in the rich text control (ie an existing plain text control). Fix your range object so that it doesn't do that eg collapse it to just a point inside the rich text control.

C# WPF RichTextBox restrict text formatting to visible text

I have a RichTextBox displaying a FlowDocument that is large (>10k lines). I am attempting to apply text formatting to the entire Document. This is taking a while to complete.
Is there any way to focus the formatting on the visible parts of the Document only?
For Information: I am attempting to search through the contents of the RichTextBox and highlight all matching occurrences. The searching function is baised upon this one. I am using the following code to 'highlight' each match found.
protected void ColorTextRanges(Color color)
{
foreach ( var textRange in locatedInstances )
{
if ( textRange != null )
{
textRange.ApplyPropertyValue( TextElement.BackgroundProperty, new SolidColorBrush( color ) );
}
}
}
Rather than create the brush in the loop create it outside and reuse it. Not going to be major but should help a little. And you might test for the BackgroundProperty and only set it if it is wrong - this might make it slower but if most of the document is already the right color then it should help.
protected void ColorTextRanges(Color color)
{
SolidColorBrush brush = new SolidColorBrush( color );
foreach ( var textRange in locatedInstances )
{
if ( textRange != null )
{
textRange.ApplyPropertyValue( TextElement.BackgroundProperty, brush);
}
}
}
The best performance increase I found was to update the document when out wasn't displayed on the screen. Not sure sure why this is but I can guess that some thing in the screen buffer isn't being updated.

Categories