Sort Microsoft.Office.Interop.Word in C# - c#

I use Microsoft.Office.Interop.Word to get words from Word file and then I populate it into a table layout panel. Unfortunately, the words displayed at the table layout panel are not following exact sequence as in the Word file.
How to fix this?
// Open a doc file.
Microsoft.Office.Interop.Word.Application application = new Microsoft.Office.Interop.Word.Application();
Document d ocument = application.Documents.Open(txtUploadedPathToken.Text);
// Loop through all words in the document.
int count = document.Words.Count;
for (int i = 1; i <= count; i++)
{
// Write the word.
string text = document.Words[i].Text;
//Console.WriteLine("Word {0} = {1}", i, text);
tableLayoutPanel2.Controls.Add(new Label() { Text = text, Anchor = AnchorStyles.Left, AutoSize = true}, 0, 0);
}

Your word document reading code seems OK. but you may need to change how you add items to panel. Since you add new items to same position (0,0) it may give incorrect order.
foreach (Microsoft.Office.Interop.Word.Range range in document.Words)
{
string text = range.Text;
tableLayoutPanel2.Controls.Add(new Label() { Text = text, Anchor = AnchorStyles.Left, AutoSize = true});
}

Related

TextBox is not creating newline when reading text file C#

I have this program that supposed to reads multiple text files on the same folder, in that folder there's 2 text files which are supposed to be read, ok now I have to generate a new TextBox based on the total numbers of text files in that folder.
Main Goal
Load the contents of those files in each textbox
File1.txt contents will be loaded into TextBox1.
File2.txt contents will be loaded into TextBox2.
Content of File1.txt:
Title 1
ABCDEFG
Content of File2.txt:
Title 2
1234567890
The problem
Loading the contents of those files into each TextBoxes works fine, but the problem is that the newline isn't created on the TextBoxes.
Instead I got this on each textboxes:
TextBox 1:
Title 1ABCDEFG
TextBox 2:
Title 21234567890
Do the necessary stuff as soon the program loads:
private void Form1_Load(object sender, EventArgs e) {
flowLayoutPanel1.AutoScroll = true;
var dirs_notes = #"C:\MAIN_LOC\DATA_LOC\";
var count_notes = Directory.GetFiles(dirs_notes,"*.*",SearchOption.AllDirectories).Count();
string setup_path = #"C:\MAIN_LOC\DATA_LOC\";
if(Directory.Exists(setup_path)) {
string[] get_notes = Directory.GetFiles(dirs_notes, "*.txt", SearchOption.AllDirectories);
string[] get_texts = get_notes.Select(x => File.ReadAllText(x)).ToArray();
for(int i=0; i<count_notes; i++) {
int top = 25;
int h_p = 170;
var load_note = new Guna2TextBox() {
Text = "\n" + get_texts[i],
Name = "Note" + i,
Multiline = true,
AcceptsTab = true,
AcceptsReturn = true,
WordWrap = false,
Width = 230,
Height = 145,
BorderRadius = 8,
Font = new Font("Bahnschrift", 13),
ForeColor = Color.White,
FillColor = ColorTranslator.FromHtml("#1E1E1E"),
BorderColor = ColorTranslator.FromHtml("#2C2C2C"),
Location = new Point(450, top)
};
top += h_p;
flowLayoutPanel1.Controls.Add(load_note);
}
} else {
MessageBox.Show("There's problem with loading notes..", "Flow Notes System");
}
}
A fix could be using the Lines property instead of the Text property.
var dirs_notes = #"C:\MAIN_LOC\DATA_LOC\";
// Be sure to count only txt files here...
var count_notes = Directory.GetFiles(dirs_notes,"*.txt",SearchOption.AllDirectories).Count();
string setup_path = #"C:\MAIN_LOC\DATA_LOC\";
if(Directory.Exists(setup_path)) {
string[] get_notes = Directory.GetFiles(dirs_notes, "*.txt", SearchOption.AllDirectories);
var get_texts = get_notes.Select(x => File.ReadLines(x));
for(int i=0; i<count_notes; i++) {
....
var load_note = new Guna2TextBox() {
Lines = "\n" + get_texts[i].ToArray(),
But a better approach is to use this instead:
// No counting here (counting means load all
// files names in a memory array and the get its length
var files = Directory.EnumerateFiles(dirs_notes,"*.txt",SearchOption.AllDirectories)
int i = 1;
// Enumerate files one by one without loading all names in memory
foreach(string file in files) {
int top = 25;
int h_p = 170;
var load_note = new Guna2TextBox() {
// Set the textbox with the current file lines content
// again one by one without loading all texts in memory
Lines = File.ReadLines(file).ToArray(),
Name = "Note" + i,
...
}
i++;
.....
}

Aspose pdf table

i have added a table with two rows and two columns and set border to all cells. but it shows the border only for first column
Sample code is shown below
var tableestdet = new Table
{
ColumnWidths = "120,120",
Margin = new MarginInfo { Top = 40, Left = 10 },
DefaultCellBorder = new BorderInfo((int)BorderSide.All, 1F),
};
tableestdet.DefaultCellTextInfo = new TextInfo { Alignment = AlignmentType.Center };
var estdet1 = tableestdet.Rows.Add();
estdet1.DefaultRowCellPadding = new MarginInfo { Top = 5, Bottom = 5 };
var req=estdet1.Cells.Add("Requested By:");
var estde=estdet1.Cells.Add("Entered By:");
var estdet2 = tableestdet.Rows.Add();
estdet2.DefaultCellTextInfo = new TextInfo
{
FontSize = 8,
Alignment = AlignmentType.Center
};
estdet2.DefaultRowCellPadding = new MarginInfo { Top = 5, Bottom = 5 };
estdet2.Cells.Add(Requestedby);
estdet2.Cells.Add(CustomerName);
sec1.Paragraphs.Add(tableestdet);
We have noticed that you are working with an outdated version of the API so please upgrade to Aspose.PDF for .NET 19.2 which is latest available version of the API as it includes more features and bug fixes. You may use below code snippet to add a table on page of PDF document, while setting borders for all cells.
// Load source PDF document
Aspose.Pdf.Document document = new Aspose.Pdf.Document();
// Add a page to the document
Page page = document.Pages.Add();
// Initializes a new instance of the Table
Aspose.Pdf.Table table = new Aspose.Pdf.Table();
// Set the table border color as LightGray
table.Border = new Aspose.Pdf.BorderInfo(Aspose.Pdf.BorderSide.All, .5f, Aspose.Pdf.Color.FromRgb(System.Drawing.Color.LightGray));
// Set the border for table cells
table.DefaultCellBorder = new Aspose.Pdf.BorderInfo(Aspose.Pdf.BorderSide.All, .5f, Aspose.Pdf.Color.FromRgb(System.Drawing.Color.LightGray));
// Create a loop to add 10 rows
for (int row_count = 1; row_count <= 10; row_count++)
{
// Add row to table
Aspose.Pdf.Row row = table.Rows.Add();
// Add table cells
row.Cells.Add("Column (" + row_count + ", 1)");
row.Cells.Add("Column (" + row_count + ", 2)");
}
// Add table object to first page of input document
page.Paragraphs.Add(table);
// Save updated document containing table object
document.Save(dataDir + "Table_19.2.pdf");
Generated PDF document has been attached for your kind reference Table19.2.pdf. Please feel free to let us know if you need any further assistance.
PS: I work with Aspose as Developer Evangelist.

using Aspose Words to replace page numbers with barcodes

this may be a silly question but I cannot work out an answer to it and after a day I am turning to the community at large for help...
I am using Aspose for Word (C# or .Net) and I am trying to replace the generated page numbering for barcode images of my own creation. I can use fonts to do it currently but I have found they are less reliable with my barcode reader and thus need to be able to read the value from the page numbering and replace it with an image of my own creation.
So really I need to find the numbering container, read the value in it and replace it. Once I have that creating the barcode and inserting it is easy.
Can anyone help?
The current method (sorry its messy but i keep trying new things):
internal static void SetFooters(ref Document doc)
{
doc.FirstSection.HeadersFooters.LinkToPrevious(false);
var builder = new DocumentBuilder(doc);
builder.MoveToDocumentStart();
Section currentSection = builder.CurrentSection;
PageSetup pageSetup = currentSection.PageSetup;
int totalPages = doc.PageCount;
int j = 1;
foreach (Section sect in doc.Sections)
{
//Loop through all headers/footers
foreach (HeaderFooter hf in sect.HeadersFooters)
{
if (
hf.HeaderFooterType == HeaderFooterType.FooterPrimary || hf.HeaderFooterType == HeaderFooterType.FooterEven || hf.HeaderFooterType == HeaderFooterType.FooterFirst)
{
builder.MoveToHeaderFooter(hf.HeaderFooterType);
Field page = builder.InsertField("PAGE");
builder.Document.UpdatePageLayout();
try
{
page.Update();
}
catch { }
int pageNumber = j;
if (int.TryParse(page.Result, out pageNumber))
{ j++; }
// Remove PAGE field.
page.Remove();
builder.Write(string.Format("{0}/{1}", pageNumber, totalPages));
}
}
}
}
HeaderFooter is a section-level node and can only be a child of Section. The page field inside the header/footer returns the latest updated value and it will be same value for all pages of a section.
In your case, I suggest you to insert text-box at the top/bottom of each page and inset the desired contents in it. Following code example inserts the text-box on each page of document and insert page field and some text in it. Hope this helps you.
public static void InsertTextBoxAtEachPage()
{
string filePathIn = MyDir + #"input.docx";
string filePathOut = MyDir + #"output.docx";
Document doc = new Document(filePathIn);
DocumentBuilder builder = new DocumentBuilder(doc);
LayoutCollector collector = new LayoutCollector(doc);
int pageIndex = 1;
foreach (Section section in doc.Sections)
{
NodeCollection paragraphs = section.Body.GetChildNodes(NodeType.Paragraph, true);
foreach (Paragraph para in paragraphs)
{
if (collector.GetStartPageIndex(para) == pageIndex)
{
builder.MoveToParagraph(paragraphs.IndexOf(para), 0);
builder.StartBookmark("BM_Page" + pageIndex);
builder.EndBookmark("BM_Page" + pageIndex);
pageIndex++;
}
}
}
collector = new LayoutCollector(doc);
LayoutEnumerator layoutEnumerator = new LayoutEnumerator(doc);
const int PageRelativeY = 0;
const int PageRelativeX = 0;
foreach (Bookmark bookmark in doc.Range.Bookmarks)
{
if (bookmark.Name.StartsWith("BM_"))
{
Paragraph para = (Paragraph)bookmark.BookmarkStart.ParentNode;
Shape textbox = new Shape(doc, Aspose.Words.Drawing.ShapeType.TextBox);
textbox.Top = PageRelativeY;
textbox.Left = PageRelativeX;
int currentPageNumber = collector.GetStartPageIndex(para);
string barcodeString = string.Format("page {0} of {1}", currentPageNumber, doc.PageCount);
string barcodeEncodedString = "some barcode string";
Paragraph paragraph = new Paragraph(doc);
ParagraphFormat paragraphFormat = paragraph.ParagraphFormat;
paragraphFormat.Alignment = ParagraphAlignment.Center;
Aspose.Words.Style paragraphStyle = paragraphFormat.Style;
Aspose.Words.Font font = paragraphStyle.Font;
font.Name = "Tahoma";
font.Size = 12;
paragraph.AppendChild(new Run(doc, barcodeEncodedString));
textbox.AppendChild(paragraph);
paragraph = new Paragraph(doc);
paragraphFormat = paragraph.ParagraphFormat;
paragraphFormat.Alignment = ParagraphAlignment.Center;
paragraphStyle = paragraphFormat.Style;
font = paragraphStyle.Font;
font.Name = "Arial";
font.Size = 10;
paragraph.AppendChild(new Run(doc, barcodeString));
textbox.AppendChild(paragraph);
//Set the width height according to your requirements
textbox.Width = doc.FirstSection.PageSetup.PageWidth;
textbox.Height = 50;
textbox.BehindText = false;
para.AppendChild(textbox);
textbox.RelativeHorizontalPosition = Aspose.Words.Drawing.RelativeHorizontalPosition.Page;
textbox.RelativeVerticalPosition = Aspose.Words.Drawing.RelativeVerticalPosition.Page;
bool isInCell = bookmark.BookmarkStart.GetAncestor(NodeType.Cell) != null;
if (isInCell)
{
var renderObject = collector.GetEntity(bookmark.BookmarkStart);
layoutEnumerator.Current = renderObject;
layoutEnumerator.MoveParent(LayoutEntityType.Cell);
RectangleF location = layoutEnumerator.Rectangle;
textbox.Top = PageRelativeY - location.Y;
textbox.Left = PageRelativeX - location.X;
}
}
}
doc.Save(filePathOut, SaveFormat.Docx);
}
I work with Aspose as Developer evangelist.

Remove text inside RichTextBox

I have a little problem with RichTextBox, I have a text inside (please look down), and I want remove
text line (that's start char'#' and end new line '\n') with using button.
'#BESTPOSA,COM1_30,0,72.5,01*9e9047d2
'#BESTPOSA,COM1,01*6f8c2c77
'$GPGGA,M,06,0126*66
'$GPRMC,152908.00,D*3A
'#AVEPOSA,FINESTEERING,0*eba27375
'$GPGSA,M,1.3*38*
This is a sample from my data.txt (in there are a lot of GPSdata frame). Of course after operation I want have only "$GPxxx" frame. Please help someone.
If you are just extracting, something like:
var lines = richTextBox1.Lines.Where(l => !l.StartsWith("#"));
Will work. If you want to update the RichTextBox then do:
var lines = richTextBox1.Lines.Where(l => !l.StartsWith("#"));
richTextBox1.Text = String.Join("\r\n", lines);
The RichTextBox has a Lines property which will get you a string array with all of the lines in it. You can loop over that and then determine the line length using a helper methods on the RichTextBox.
var lines = richTextBox1.Lines;
for (int i = lines.Count()-1;i>=0; i--)
{
if (lines[i].StartsWith("#"))
{
var thisLineStart = richTextBox1.GetFirstCharIndexFromLine(i);
var maxLines = richTextBox1.Lines.Count();
if (i >= maxLines)
{
richTextBox1.Text = richTextBox1.Text.Remove(thisLineStart);
}
else
{
var nextLineStart = richTextBox1.GetFirstCharIndexFromLine(i + 1);
richTextBox1.Text = richTextBox1.Text.Remove(thisLineStart, nextLineStart - thisLineStart);
}
}
}

Insert Word doc page number field in text box

I have a text box within a footer in a Word doc. It has some template text that is left-aligned, and then already has the "Page x of n" right-aligned. When I try and replace the template text, all of the text is replaced.
Using C# or VB (either way) I need to replace the text inside of the text box (all of this text should be left-aligned) and then add "Page x of n" (right-aligned).
Here is what I have so far as a test:
string footer;
foreach (Shape shape in oMyDoc.Sections[1].Footers[WdHeaderFooterIndex.wdHeaderFooterPrimary].Shapes)
{
footer = shape.TextFrame.ContainingRange.Text;
footer = footer.Replace("\r", "");
footer = footer.Replace("[Quote Type]", "Big Quote");
footer = footer.Replace("(", "\u2022");
int start = footer.IndexOf("Pager ");
footer = footer.Remove(start + 5);
var numPages = oMyDoc.ComputeStatistics(WdStatistic.wdStatisticPages);
footer = footer + " of " + numPages.ToString();
shape.TextFrame.ContainingRange.Text = footer;
}

Categories