Omit last page on NUMPAGES Aspose .net - c#

I'm looking for a solution in ASPOSE .Net to decrement the NUMPAGES. Reason is that I don't want to count the last page of the document. Here is what I tried so far:
builder.Write("Page ");
builder.InsertField("Page", "");
builder.Write(" of ");
builder.InsertField("NUMPAGES", $"{(doc.PageCount - 1)}");
// Another try in separate build
builder.InsertField("NUMPAGES - 1", "");
// Another try in separate build
builder.InsertField("NUMPAGES", "NUMPAGES - 1");
Document either doesn't display anything or count the last page as well.

You should use formula and nested NUMPAGES field to get the desired output. Field code in your MS Word document should look like this:
{={NUMPAGES}-1}. To insert such field using Aspose.Words you can use code like this:
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
// Insert formula field
Field formula = builder.InsertField("=", "");
// Move document builder inside field code of the inserted field
// And put NUMPAGES field in it.
builder.MoveTo(formula.Separator);
builder.InsertField("NUMPAGES");
builder.Write("-1");
doc.UpdateFields();
doc.Save(#"C:\Temp\out.docx");
Please see Aspose.Words documentation to learn how to work with fields.

Related

Iterate through a Microsoft Word document to find and replace tables

I have some VBA code that iterates through a document to remove tables from a document. The following code works fine in VBA:
Set wrdDoc = ThisDocument
With wrdDoc
For Each tbl In wrdDoc.Tables
tbl.Select
Selection.Delete
Next tbl
End With
Unfortunately, I cannot easily translate this code to C#, presumably because there is a newer Range.Find method. Here are three things I tried, each failing.
First attempt (re-write of the VBA code):
foreach (var item in doc.Tables)
{
item.Delete; //NOPE! No "Delete" function.
}
I tried this:
doc = app.Documents.Open(sourceFolderAndFile); //sourceFolderAndFile opens a standard word document.
var rng = doc.Tables;
foreach(var item in rng)
{
item.Delete; //NOPE! No "Delete" function.
}
I also tried this:
doc = app.Documents.Open(sourceFolderAndFile); //sourceFolderAndFile opens a standard word document.
var rng = doc.Tables;
Range.Find.Execute(... //NOPE! No Range.Find available for the table collection.
...
Could someone please help me understand how I can use C# and Word Interop (Word 2013 and 2016) to iterate through a document, find a table, and then perform a function, like selecting it, deleting it, or replacing it?
Thanks!
It took me some time to figure this answer out. With all the code samples online, I missed the need to create an app. For posterity, here is how I resolved the problem.
Make sure you have a Using statement, like this:
using MsWord = Microsoft.Office.Interop.Word;
Open the document and then work with the new msWord reference, the range, and the table. I provide a basic example below:
//open the document.
doc = app.Documents.Open(sourceFolderAndFile, ReadOnly: true, ConfirmConversions: false);
//iterate through the tables and delete them.
foreach (MsWord.Table table in doc.Tables)
{
//select the area where the table is located and delete it.
MsWord.Range rng = table.Range;
rng.SetRange(table.Range.End, table.Range.End);
table.Delete();
}
//don't forget doc.close and app.quit to clean up memory.
You can use the Range (rng) to replace the table with other items, like text, images, etc.

Add dynamic table row using microsoft work automation c#

I have a word document template which contains several form fields that need to be filled using c# code.
below is the document image
The code below is used to reach and fill the document form fields,
But when i reach the table sections sometimes the rows need to be filled are more than what is pre defined inside the template.
red marked area is the table which i want to fill it with data and create as many rows as needed.
the code i use for filling the data is
string fileName = Path.GetTempFileName();
File.WriteAllBytes(fileName, Properties.Resources.DocumentTemplate);
Word.Application word = new Word.Application();
Word.Document doc = new Word.Document();
doc = word.Documents.Add(fileName);
doc.Activate();
doc.FormFields["file_num"].Range.Text = "some text";
doc.FormFields["fam_size"].Range.Text = "another text";
doc.FormFields["nationality"].Range.Text = "another text";
for(int i =0; i< rowsInDatabaseCount; i++)
{
//i don't know how to add row and reach each form field inside
}
I hope someone can help me on how to achieve what i want.
Thank you in advance...
There are multiple ways to handle that.
1) Since the data is coming from a database, one way is to use InsertDatabase method.
2) You could insert the block as tab or comma separated text then convert to a table using ConvertToTable() method.
3) You might use Rows and Cols collections (of Table) and .Add method to add new rows.
4) You might instead create your template as an XSL and transform data (XML) using that XSL to generate final HTM. Word is able to open an HTM file.
(All these options worked for me in "resume", "test results" ... creations which have similar layouts to the ones you gave. I found final option 4 to be the most dynamic one, where end users could define their own templates using simple HTML editors - worked better than word templates for me).

Insert a table into a middle of word processing document (Open XML SDK)

I have a template Word document which i fill details into with openXML SDK 2.0 (using c#).
I also need to insert a table into file, and i found this tutorial on MSDN.
But - the example is appending the table to the end of the document, and I want it to be somewhere in the middle.
I may need to replace this line:
doc.MainDocumentPart.Document.Body.Append(table);
with something else. (The full code is in the link above).
Please help me.. I found nothing yet.
Thanks.
One way to do this may be to use Content Controls as placeholders to insert the table into them from code.
var myContentControl = doc.MainDocumentPart.Document.Body.Descendants<SdtBlock>()
.Where(e => e.Descendants<SdtAlias>().FirstOrDefault().Val == "myTablePlaceholder").FirstOrDefault();
SdtContentBlock sdtContentBlock1 = new SdtContentBlock();
sdtContentBlock1.Append(table); // Your table
myContentControl.Append(sdtContentBlock1);

Fetch data which is in between html tags

I have a word document. When I upload that document, I need to fetch the name from that. I always have the name in the first row, the data in the word document is like,
Shanish K
shanish#gmail.com
.....
......
For this, I just converted the word file to html, and from that am trying to read the name. Once I converted the word file am getting the style defenitions also along with the actual content. I dunno how to get only the data which is there in the first row. Can anyone help me out here. Thanks in advance...
note:- I noticed something when I was debugging, that the actual contents are in between paragraph tags like <p .....>Shanish</p> ....., is is possible to fetch the data in between the first <p></p> ?
Yes, you can use HTMLAgilityPack, FizzlerEx or CSQuery
I would use FizzlerEx. Load the document and select the first matched p element.
using HtmlAgilityPack;
using Fizzler.Systems.HtmlAgilityPack;
var web = new HtmlWeb();
var document = web.Load("http://example.com/page.html")
var page = document.DocumentNode;
var name = page.QuerySelector("p:eq(0)");

Add text to word table in c# using word interop

I am using Word.Interop in c# to inject data into a word document whch serves as a template for me.
This document has a table I wish to fill.
like this:
I am inserting the text like this (simpilified):
String text = "1" + "\t" + "2" + "\t" ; //Etc..
But this is not working.
Any idea how I should do it?
This will not work. If you want to create a new table in a word document, set a bookmark in the document where you want the table to be created, then create the table as described here:
http://msdn.microsoft.com/en-us/library/vstudio/w1702h4a.aspx
If you have an existing fixed table in the document, place custom document properties in the cells, then set their values like this:
thedocument.CustomDocumentProperties["NameOfTheCustomProperty"].Value = 1;

Categories