Create word document and write formatted text - c#

using Word = Microsoft.Office.Interop.Word;
public static void CreateWord()
{
Word.Application objWord = new Word.Application();
Word.Document objDoc = objWord.Documents.Add();
Word.Paragraph objPara;
objPara = objDoc.Paragraphs.Add();
objPara.Range.Text = "Bold text aligned center";
objPara.Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
objPara.Range.Bold = 1;
objPara.Range.InsertParagraphAfter();
objPara = objDoc.Paragraphs.Add();
objPara.Range.Text = "Regular text aligned left";
objPara.Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphLeft;
objPara.Range.Bold = 0;
objPara.Range.InsertParagraphAfter();
objPara = objDoc.Paragraphs.Add();
objPara.Range.Text = "Regular text aligned center\nwith something on the next line";
objPara.Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
objPara.Range.Bold = 0;
objPara.Range.InsertParagraphAfter();
objPara = objDoc.Paragraphs.Add();
objPara.Range.Text = "Regular text aligned left, with some Bold text here\nand some regular text on next line";
objPara.Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphLeft;
objPara.Range.Bold = 0;
objPara.Range.InsertParagraphAfter();
objWord.Visible = true;
objWord.WindowState = Word.WdWindowState.wdWindowStateNormal;
}
The code above creates a Word document and writes text to it, but it looks like this:
I'm assuming that text in Microsoft.Office.Interop.Word is not supposed to act like that, or text should be added in some other way, but I'm failing to find any good information on how to do this.
So, my question is - how to add text from c# to a newly created word document with the right properties, so the result looks like this:
P.S. tips about creating tables using .Interop.Word would also be appreciated.

The key to working with content in Word documents is to understand how to work with Range objects. There's more than one way to achieve a goal of this nature. The following code snippet is my preference: collapsing the Range for each step (think of it like pressing the right-arrow key to "collapse" a selection to a point), rather than mixing Add, InsertAfter and similar methods.
For each change of formatting the Range must be "collapsed". So if you have bold in the middle of a line, that's a separate step. If numerous paragraphs should have the same formatting, they can be combined.
Environment.NewLine and \n can be used interchangeably.
Generally, assign text content, then format the Range.
object oCollapseEnd = Word.WdCollapseDirection.wdCollapseEnd;
doc.Paragraphs.Add();
Word.Range objRange = doc.Content;
objRange.Collapse(ref oCollapseEnd);
objRange.Text = "Bold text aligned center" + Environment.NewLine;
objRange.Bold = 1;
objRange.Paragraphs.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
objRange.Collapse(ref oCollapseEnd);
objRange.Text = "Regular text aligned left" + Environment.NewLine;
objRange.Paragraphs.Alignment = Word.WdParagraphAlignment.wdAlignParagraphLeft;
objRange.Bold = 0;
objRange.Collapse(ref oCollapseEnd);
objRange.Text = "Regular text aligned center\nwith something on the next line" + Environment.NewLine;
objRange.Paragraphs.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
objRange.Bold = 0;
objRange.Collapse(ref oCollapseEnd);
objRange.Text = "Regular text aligned left, with some ";
objRange.Collapse(ref oCollapseEnd);
objRange.Text = "Bold text here";
objRange.Bold = 1;
objRange.Collapse(ref oCollapseEnd);
objRange.Text = "\nand some regular text on next line" + Environment.NewLine;
objRange.Paragraphs.Alignment = Word.WdParagraphAlignment.wdAlignParagraphLeft;
objRange.Bold = 0;

Related

How can I add underlined words in a line of text in a word header object?

I need to add underlined column headers to the header objects in a document. I am using C# and Microsoft.Office.Interop.Word
The pertinent parts of the code look like this...
foreach (Word.HeaderFooter header in wordSection.Headers)
{
int[] fiscalYears = RetrieveFiscalYears(docProfile);
string paddingFY = new String(' ', 8);
Word.Paragraph colParagraph = wordRng.Paragraphs.Add();
int year;
for (int i = fiscalYears.Length - 1; i >= 0; i--)
{
year = fiscalYears[i];
colParagraph.Range.InsertAfter(MARKUP_WORD_TAB);
//begin underline
colParagraph.Range.InsertAfter(paddingFY + year.ToString() + paddingFY);
//end underline
}
colParagraph.Range.InsertAfter(MARKUP_WORD_TAB);
colParagraph = wordRng.Paragraphs.Add();
colParagraph.set_Style(wordDoc.Styles["ColumnHeadings"]);
}
Basically it needs to look similar to ...
Expended Estimated Budgeted
2015 2016 2017
--------- ---------- --------
In the body of the document, my for loop looks like
foreach (int year in fiscalYears)
{
wordApp.Selection.TypeText(MARKUP_WORD_TAB);
wordApp.Selection.Font.Underline = Word.WdUnderline.wdUnderlineSingle;
wordApp.Selection.TypeText(paddingFY + year.ToString() + paddingFY);
wordApp.Selection.Font.Underline = Word.WdUnderline.wdUnderlineNone;
}
But the when I use the selection object, it writes to the body of the document, not to the header/footer objects. I might be able to get around this by using the SeekHeader and making it the focus, but that offers its own challenges...
I've tried using the colParagraph.Range.Font.Underline object, but that underlines the entire line, not just the words that make up the column headings.
I've tried using a find object, but the execute doesn't find the text for some reason.
Appreciate any guidance you can provide.
I had to move the set style above the for loop and set a new range based on the paragraph range and move its start and end positions. Then apply the underlining to the new range.
So now it looks similar to ....
colParagraph.Range.InsertAfter(MARKUP_WORD_TAB);
colParagraph = wordRng.Paragraphs.Last; //reset the range to include the tab so the style can be applied.
colParagraph.set_Style(wordDoc.Styles["ColumnHeadings"]);
int year;
int start = colParagraph.Range.Text.Length - 1;
string yrHeading = string.Empty;
Word.Range underlineRange = null;
for (int i = 0 ; i < fiscalYears.Length; i++)
{
year = fiscalYears[i];
colParagraph = wordRng.Paragraphs.Last; //reset the range to include the last fiscal year that was entered.
start = colParagraph.Range.Text.Length - 1;
colParagraph.Range.InsertAfter(yrHeading);
colParagraph.Range.InsertAfter(MARKUP_WORD_TAB);
underlineRange = colParagraph.Range.Duplicate;
underlineRange.MoveStart(Word.WdUnits.wdCharacter, start);
underlineRange.MoveEnd(Word.WdUnits.wdCharacter, -2); //-2 = /t/r for tab & paragraph characters
underlineRange.Font.Underline = Word.WdUnderline.wdUnderlineSingle;
}
colParagraph = wordRng.Paragraphs.Add();

How to set paragraph line space in itextsharp ?

In my C# windows Form application I use below code. it works fine. but I need to add line space for this paragraph.
var linkFont = FontFactory.GetFont(FontFactory.HELVETICA, 13, iTextSharp.text.Font.UNDERLINE, BaseColor.BLUE);
List<Anchor> anchor = new List<Anchor>();
foreach (string tName in templateName)
{
Anchor anch = new Anchor(tName, linkFont);
anch.Reference = "#" + tName;
anchor.Add(anch);
}
Paragraph templateData = new Paragraph();
templateData.Alignment = Element.ALIGN_LEFT;
for (int z = 0; z < anchor.Count; z++)
{
templateData.Add(anchor[z]);
templateData.Add(" , ");
}
output of this code is below.
Output of above code
if I use following code nothing changed.
Paragraph templateData = new Paragraph();
templateData.Alignment = Element.ALIGN_LEFT;
templateData .SetLeading(15, 1);
How can I fix this issue and add line space for this paragraph ?
Thanks
Change value of Y in:
templateData.SetLeading(15, 10); //'1' to '10' or whatever you want

iTextSharp multiple lines in PdfPCell one under another

I am using iTextSharp to create table in PDF document. I need several lines inside table cell to appear one under another like this:
First line text
Second Line Text
Third Line Text
Fourth line text
Some times with extra line like this :
First line text
Second Line Text
Third Line Text
Fourth line text
I have tried several approaches, with Paragraphs, Chunks, Phrases, did research online but still can not get this result. Please help.
Also, how to make columns to adjust width dynamically to content ? (not wrapping)
Thank you
If you need to align at the text level you'll need to switch to a fixed-width font. But if you're just looking to indent you can just add spaces to new lines within a paragraph:
var p = new Paragraph();
p.Add("First line text\n");
p.Add(" Second line text\n");
p.Add(" Third line text\n");
p.Add("Fourth line text\n");
myTable.AddCell(p);
You could also get complicated and use a sub-table if you need more control:
var subTable = new PdfPTable(new float[] { 10, 100 });
subTable.AddCell(new PdfPCell(new Phrase("First line text")) { Colspan = 2, Border = 0 });
subTable.AddCell(new PdfPCell() { Border = 0 });
subTable.AddCell(new PdfPCell(new Phrase("Second line text")) { Border = 0 });
subTable.AddCell(new PdfPCell() { Border = 0 });
subTable.AddCell(new PdfPCell(new Phrase("Third line text")) { Border = 0 });
subTable.AddCell(new PdfPCell(new Phrase("Fourth line text")) { Colspan = 2, Border = 0 });
myTable.AddCell(subTable);
Though pretty tedious, but for setting font, following seem to work:
Font myFont = FontFactory.GetFont("Arial", 8, Font.NORMAL);
string line1 = "First line of text" + "\n";
string line2= "Second line of text" + "\n";
string line3= " Third Line of text";
Paragraph p1 = new Paragraph();
Phrase ph1 = new Phrase(line1, myFont);
Phrase ph2 = new Phrase(line2, myFont);
Phrase ph3 = new Phrase(line3, myFont);
p1.Add(ph1);
p1.Add(ph2);
p1.Add(ph3);
PdfPCell mycell = new PdfPCell(p1);
You can also do it the following way ..
var xstring = "Your first line \n Your 2nd line";
Phrase p = new Phrase();
p.Add(new Chunk(xstring, yourFontFace));
I text will notice the new line return code and render your phrase on two separate lines.
Your first line
Your 2nd line
Cheers
#region .!!
PdfPTable tbl_A = new PdfPTable(1);
tbl_A.WidthPercentage = 98f;
//float[] colWidthUnderTaking1 = { 1300 };
//tblUnderTaking1.SetWidths(colWidthUnderTaking1);
#region For Page Space
PdfPCell cell_A;
cell_A = new PdfPCell(new Phrase(" ", Smallspace));
cell_A.HorizontalAlignment = 1;
cell_A.BorderWidth = 0;
cell_A.Colspan = 2;
tbl_A.AddCell(cell_A);
cell_A = new PdfPCell(new Phrase(" ", Smallspace));
cell_A.HorizontalAlignment = 1;
cell_A.BorderWidth = 0;
cell_A.Colspan = 2;
tbl_A.AddCell(cell_A);
#endregion
Chunk cMem = new Chunk("The Member ", TableFontmini_ARBold8Nor);
Chunk cName = new Chunk(dt.Rows[0]["EmpName"].ToString(), TableFontmini_ARBold10);
Chunk cjoin = new Chunk(" Has joined On ", TableFontmini_ARBold8Nor);
Chunk cDOJ = new Chunk(" " + dt.Rows[0]["DOJPF"].ToString(), TableFontmini_ARBold10);
Chunk chas = new Chunk("and has been alloted PF Member ID ", TableFontmini_ARBold8Nor);
Chunk cPF = new Chunk(" " + dt.Rows[0]["PFNo"].ToString(), TableFontmini_ARBold10);
Phrase paira = new Phrase();
paira.Add(cMem);
paira.Add(cName);
paira.Add(cjoin);
paira.Add(cDOJ);
paira.Add(chas);
paira.Add(cPF);
Paragraph pName = new Paragraph();
pName.Add(paira);
PdfPCell cell_A2 = new PdfPCell(pName);
cell_A2.HorizontalAlignment = 0;/**Left=0,Centre=1,Right=2**/
cell_A2.BorderWidth = 0;
cell_A2.Colspan = 2;
tbl_A.AddCell(cell_A2);
doc.Add(tbl_A);
#endregion

How to add a simple phrase on a ms-word doc

im programming in C# and i need to add a simple phrase on the last page of each ms-word doc.
i have tried this
Word.Paragraph paragraph;
int totalPages;
Word.Range range;
range = doc.Content.Duplicate;
totalPages = range.ComputeStatistics(Word.WdStatistic.wdStatisticPages);
range = range.GoTo(Word.WdGoToItem.wdGoToPage, Type.Missing, totalPages, Type.Missing);
paragraph = doc.Paragraphs.Add(range);
paragraph.Range.Font.Name = "Arial";
paragraph.Range.Font.Size = 7;
paragraph.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
paragraph.Range.Text = encrypt;
but this code are adding a pharse in the last but one page .
How about something like this (you may need to fix the C# syntax):
doc.Content.InsertParagraphAfter();
Word.Paragraph paragraph = doc.Paragraphs(doc.Paragraphs.Count());
paragraph.Range.Font.Name = "Arial";
paragraph.Range.Font.Size = 7;
paragraph.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
paragraph.Range.Text = encrypt;

Get part of the text from RichTextBox

Can someone please tell me what is wrong with this. I am trying to get text between several characters before caret and the caret."comparable" is never longer than the actual text in the RichTextBox.
This is the code that I have:
int coLen = comparable.Length;
TextPointer caretBack = rtb.CaretPosition.GetPositionAtOffset(coLen,
LogicalDirection.Backward);
TextRange rtbText = new TextRange(caretBack, rtb.CaretPosition);
string text = rtbText.Text;
This returns text = ""
Please help!
This works as expected , I get I a
Piece of code :
RichTextBox rtb = new RichTextBox();
rtb.AppendText("I am adding some texts to the richTextBox");
rtb.CaretPosition = rtb.CaretPosition.DocumentEnd;
int coLen = 3;
TextPointer caretBack = rtb.CaretPosition.GetPositionAtOffset(-coLen);
TextRange rtbText = new TextRange(caretBack, rtb.CaretPosition);
string ttt = rtbText.Text;
EDIT
Here is an MSTest method to explain the behavior of the Caret and reading :
[TestMethod]
public void TestRichtTextBox()
{
RichTextBox rtb = new RichTextBox();
rtb.AppendText("I am adding some texts to the richTextBox");
int offset = 3;
TextPointer beginningPointer = rtb.CaretPosition.GetPositionAtOffset(offset);
TextPointer endPointer = rtb.CaretPosition.DocumentEnd;
TextRange rtbText = new TextRange(beginningPointer, endPointer);
Assert.IsTrue(rtbText.Text == "m adding some texts to the richTextBox\r\n");
// Now we if we keep the same beggining offset but we change the end Offset to go backwards.
beginningPointer = rtb.CaretPosition.GetPositionAtOffset(3);
endPointer = rtb.CaretPosition; // this one is the beginning of the text
rtbText = new TextRange(beginningPointer, endPointer);
Assert.IsTrue(rtbText.Text == "I a");
// Nowe we want to read from the back three characters.
// so we set the end Point to DocumentEnd.
rtb.CaretPosition = rtb.CaretPosition.DocumentEnd;
beginningPointer = rtb.CaretPosition.GetPositionAtOffset(-offset);
endPointer = rtb.CaretPosition; // we already set this one to the end document
rtbText = new TextRange(beginningPointer, endPointer);
Assert.IsTrue(rtbText.Text == "Box");
}
Plus here is a comment from MSDN about the negative index :
offset Type: System.Int32 An offset, in symbols, for which to
calculate and return the position. If the offset is negative, the
position is calculated in the logical direction opposite of that
indicated by the LogicalDirection property.

Categories

Resources