Wednesday, 24 August 2016 08:23

How to set text direction in Word

We can use the TextDirection enumeration in Spire.Doc.Documents namespace to set the direction of text in a word document. This enumeration contains six members: LeftToRight, TopToBottom, LeftToRightRotated, TopToBottomRotated, RightToLeft and RightToLeftRotated. The following example shows how to set text direction for all text and a part of text in a section.

Detail steps:

Step 1: Initialize a new instance of Document class and load the word document.

Document document = new Document();
document.LoadFromFile("Word.docx");

Step 2: Set text direction for all text in a section.

//Get the first section and set its text direction
Section section = document.Sections[0];
section.TextDirection = TextDirection.RightToLeftRotated;

To set text direction for a part of text, we can put the text in a table and then set text direction, as shown in the following step:

Step 3: Add a new section to the document and a table to the section, get the target table cell and set text direction for it, afterwards append text to the cell.

//Add a new section to the document
Section sec = document.AddSection();
//Add a table to the new section
Table table = sec.AddTable();
//Add one row and one column to the table
table.ResetCells(1, 1);
//Get the table cell
TableCell cell = table.Rows[0].Cells[0];
table.Rows[0].Height = 150;
table.Rows[0].Cells[0].Width = 10;
//Set text direction for the cell and append some text
cell.CellFormat.TextDirection = TextDirection.RightToLeftRotated;
cell.AddParagraph().AppendText("Hello,world: vertical style");

Add a new paragraph to check if above settings will affect the text direction of other text in this section:

sec.AddParagraph().AppendText("New Paragraph");

Step 4: Save the document.

document.SaveToFile("result.docx", FileFormat.Docx);

Result:

Set text direction for all text in a section:

How to set text direction in Word

Set text direction for a part of text:

How to set text direction in Word

Full codes:

using Spire.Doc;
using Spire.Doc.Documents;

namespace Set_text_direction_in_Word
{
    class Program
    {
        static void Main(string[] args)
        {
            Document document = new Document();
            document.LoadFromFile("Word.docx");
            //Set text direction for all text in a section
            Section section = document.Sections[0];
            section.TextDirection = TextDirection.RightToLeftRotated;

            // Set text direction for a part of text
            Section sec = document.AddSection();
            Table table = sec.AddTable();
            table.ResetCells(1, 1);
            TableCell cell = table.Rows[0].Cells[0];
            table.Rows[0].Height = 150;
            table.Rows[0].Cells[0].Width = 10;
            cell.CellFormat.TextDirection = TextDirection.RightToLeftRotated;
            cell.AddParagraph().AppendText("Hello,world: vertical style");

            sec.AddParagraph().AppendText("New Paragraph");

            //Save the document
            document.SaveToFile("result.docx", FileFormat.Docx);
        }
    }
}

When we operate the word documents by edit the wording, and its format on the word documents, we usually use Microsoft Word's Tracking Changes feature to mark our every changes. Later if we want to share the final version of our document to others, we need to remove the tracked changes by accepting them or rejecting them. Spire.Doc offers a property Document.TrackChanges to turn on/off track changes and the method of Document.AcceptChanges();/Document.RejectChanges(); to accept/reject the track changes. This article will show you how to accept/reject the tracked changes on word document in C# with the help of Spire.Doc.

Firstly view the sample word document with tracked changes:

How to accept/reject the tracked changes on word document in C#

Here comes to the steps of how to accept or reject the tracked changes:

Step 1: Create a new word document and load the document from file.

Document doc = new Document();
doc.LoadFromFile("sample.docx");

Step 2: Get the first section and the paragraph we want to accept/reject the changes.

Section sec = doc.Sections[0];
Paragraph para = sec.Paragraphs[0];

Step 3: Accept the changes or reject the changes.

para.Document.AcceptChanges();
//para.Document.RejectChanges();

Step 4: Save the document to file.

doc.SaveToFile("result.docx", FileFormat.Docx);

Effective screenshot after accept the tracked changes:

How to accept/reject the tracked changes on word document in C#

Full codes:

static void Main(string[] args)
{
    Document doc = new Document();
    doc.LoadFromFile("sample.docx");

    Section sec = doc.Sections[0];
    Paragraph para = sec.Paragraphs[0];

    para.Document.AcceptChanges();

//para.Document.RejectChanges();

 doc.SaveToFile("result.docx", FileFormat.Docx);

}

A looping slideshow displays each slide automatically for a certain amount of time. Once the slideshow reaches the end, it repeats from the beginning. This article will introduce how to programmatically set a PowerPoint document to keep looping when presenting.

Code Snippet:

Step 1: Initialize an instance of Presentation class. Load a sample PowerPoint document to it.

Presentation ppt = new Presentation();
ppt.LoadFromFile(@"C:\Users\Administrator\Desktop\sample.pptx");

Step 2: Set the Boolean value of ShowLoop as true, which makes the slideshow repeat with continuous looping.

ppt.ShowLoop = true;

Step 3: Set the PowerPoint document to show animation and narration. Use slide transition timings to advance slide.

ppt.ShowAnimation = true;
ppt.ShowNarration = true;
ppt.UseTimings = true;

Step 4: Save the file.

ppt.SaveToFile("LoopEnding.pptx", FileFormat.Pptx2010);

Full Code:

[C#]
Presentation ppt = new Presentation();
ppt.LoadFromFile(@"C:\Users\Administrator\Desktop\sample.pptx");

ppt.ShowLoop = true;
ppt.ShowAnimation = true;
ppt.ShowNarration = true;
ppt.UseTimings = true;

ppt.SaveToFile("LoopEnding.pptx", FileFormat.Pptx2010);
[VB.NET]
Dim ppt As New Presentation()
ppt.LoadFromFile("C:\Users\Administrator\Desktop\sample.pptx")

ppt.ShowLoop = True
ppt.ShowAnimation = True
ppt.ShowNarration = True
ppt.UseTimings = True

ppt.SaveToFile("LoopEnding.pptx", FileFormat.Pptx2010)

When we operate the excel files with large amounts of data, we may find that some of the cells need to be widened to allow the data to fit. Spire.XLS offers a method worksheet.AutoFitColumn(); and worksheet.AutoFitRow(); to enable developers to adjust the widths of the columns and the height of the rows to fit the content and make the whole Excel worksheet tidy and clean. This article will demonstrate how to auto fit the columns and rows in Excel worksheet in C#.

Note: Before Start, please download the latest version of Spire.XLS and add Spire.Xls.dll in the bin folder as the reference of Visual Studio.

Firstly please check the Excel worksheet need to AutoFit the columns and rows:

AutoFit Column Widths and Row Heights in Excel

Step 1: Create a new Excel workbook and load from file.

Workbook workbook = new Workbook();
workbook.LoadFromFile("Sample.xlsx");

Step 2: Get the first worksheet from the workbook.

Worksheet worksheet = workbook.Worksheets[0];

Step 3: AutoFit the whole worksheets Column widths and Row heights.

worksheet.AllocatedRange.AutoFitColumns();
worksheet.AllocatedRange.AutoFitRows();

Step 4: Save the document to file.

workbook.SaveToFile("Result.xlsx", FileFormat.Version2010);

Effective screenshot after AutoFit and rows and columns in Excel:

AutoFit Column Widths and Row Heights in Excel

Full codes:

{
    Workbook workbook = new Workbook();
    workbook.LoadFromFile("Sample.xlsx");

    Worksheet worksheet = workbook.Worksheets[0];

    worksheet.AllocatedRange.AutoFitColumns();
    worksheet.AllocatedRange.AutoFitRows();

    workbook.SaveToFile("Result.xlsx", FileFormat.Version2010);
}

Trendline

A trendline is a line superimposed on a chart revealing the overall direction of the data. There are six different types of trendlines:

  • linear
  • logarithmic
  • polynomial
  • power
  • exponential
  • moving average

Add trendline for chart series

Spire.Presentation enables developers to add all types of the trendlines mentioned above by using Charts.ChartSeriesDataFormat.AddTrendLine() method and set the trendline type by using Charts.TrendlinesType enum.

Here comes to the detailed steps:

Step 1: Initialize a new instance of Presentation class and load the ppt file.

Presentation ppt = new Presentation();
ppt.LoadFromFile("Sample.pptx");

Step 2: Get the target chart, add trendline for the first data series of the chart and specify the trendline type.

IChart chart = ppt.Slides[0].Shapes[0] as IChart;
ITrendlines it = chart.Series[0].AddTrendLine(TrendlinesType.Linear);
//Set the trendline properties to determine what should be displayed.
it.displayEquation = false;
it.displayRSquaredValue = false;

Step 3: Save the file.

ppt.SaveToFile("output.pptx",FileFormat.Pptx2010);

Output:

How to add trendline for chart series in PowerPoint

Full codes:

using Spire.Presentation;
using Spire.Presentation.Charts;

namespace Add_trendline_for_chart_series
{
    class Program
    {
        static void Main(string[] args)
        {
            Presentation ppt = new Presentation();
            ppt.LoadFromFile("Sample.pptx");

            IChart chart = ppt.Slides[0].Shapes[0] as IChart;
            ITrendlines it = chart.Series[0].AddTrendLine(TrendlinesType.Linear);
            it.displayEquation = false;
            it.displayRSquaredValue = false;

            ppt.SaveToFile("output.pptx",FileFormat.Pptx2010);
        }
    }
}

A text box can be formatted to display number, currency, date, time, zip code, phone number, social security number, etc. Adobe Acrobat provides various built-in JavaScripts, such as AFNumber_Keystroke(2, 0, 0, 0, "$", true) and AFNumber_Format(2, 0, 0, 0, "$", true), to format and validate the input of text field. The script with Format suffix is used to format the input, the script with Keystroke suffix is used to validate the input.

However, Spire.PDF has offered corresponding methods to perform formatting and validation on text field. Here is the list of frequently used formats and corresponding methods in Spire.PDF.

Description Example JavaScript Method
Date 01/31/2008 AFDate_FormatEx("mm/dd/yyyy");
AFDate_KeystrokeEx("mm/dd/yyyy");
GetDateFormatString("mm/dd/yyyy");
GetDateKeystrokeString("mm/dd/yyyy");
Date 1/31/2008 AFDate_FormatEx("m/d/yyyy");
AFDate_KeystrokeEx("m/d/yyyy");
GetDateFormatString("m/d/yyyy");
GetDateKeystrokeString("m/d/yyyy");
Zip code 12345 AFSpecial_Format(0);
AFSpecial_Keystroke(0);
GetSpecialFormatString(0);
GetSpecialKeystrokeString(0);
Zip+4 12345-1234 AFSpecial_Format(1);
AFSpecial_Keystroke(1);
GetSpecialFormatString(1);
GetSpecialKeystrokeString(1);
Phone number (123) 456-7890 AFSpecial_Format(2);
AFSpecial_Keystroke(2);
GetSpecialFormatString(2);
GetSpecialKeystrokeString(2);
Money (minus sign if negative) $12,345.00
-$12,345.00
AFNumber_Format(2, 0, 0, 0, "$", true);
AFNumber_Keystroke(2, 0, 0, 0, "$", true);
GetNumberFormatString(2, 0, 0, 0, "$", true);
GetNumberKeystrokeString(2, 0, 0, 0, "$", true);
Validate 1.5≤input value≤5.5 AFRange_Validate(true,1.5,true,5.5) GetRangeValidateString(true, 1.5, true, 5.5);

This tutorial demonstrates how to create a text box and display its contents in currency format in C# and VB.NET.

Code Snippets:

Step 1: Create an object of PdfDocument and add a page to it.

PdfDocument pdf = new PdfDocument();
PdfPageBase page = pdf.Pages.Add();

Step 2: Initialize an instance of PdfTextBoxField class and set its position, border width and border style.

PdfTextBoxField textbox = new PdfTextBoxField(page, "Number-TextBox");
textbox.Bounds = new RectangleF(10, 10, 100, 20);
textbox.BorderWidth = 0.75f;
textbox.BorderStyle = PdfBorderStyle.Solid;

Step 3: Set a JavaScript action to be performed when uses type a keystroke into a text field. This action can check the keystroke for validity and reject or modify it.

string js = PdfJavaScript.GetNumberKeystrokeString(2, 0, 0, 0, "$", true);
PdfJavaScriptAction jsAction = new PdfJavaScriptAction(js);
textbox.Actions.KeyPressed = jsAction;

Step 4: Set a JavaScript action to format the value of text field before showing it.

js = PdfJavaScript.GetNumberFormatString(2, 0, 0, 0, "$", true);
jsAction = new PdfJavaScriptAction(js);
textbox.Actions.Format = jsAction;

Step 5: Add the text box to PDF field and save the file.

pdf.Form.Fields.Add(textbox);
pdf.SaveToFile("FormatField.pdf",FileFormat.PDF);

Output:

How to Format Textbox Field using JavaScript in C#, VB.NET

Full Code:

[C#]
PdfDocument pdf = new PdfDocument();
PdfPageBase page = pdf.Pages.Add();
PdfTextBoxField textbox = new PdfTextBoxField(page, "Number-TextBox");
textbox.Bounds = new RectangleF(10, 10, 100, 20);
textbox.BorderWidth = 0.75f;
textbox.BorderStyle = PdfBorderStyle.Solid;

string js = PdfJavaScript.GetNumberKeystrokeString(2, 0, 0, 0, "$", true);
PdfJavaScriptAction jsAction = new PdfJavaScriptAction(js);
textbox.Actions.KeyPressed = jsAction;

js = PdfJavaScript.GetNumberFormatString(2, 0, 0, 0, "$", true);
jsAction = new PdfJavaScriptAction(js);
textbox.Actions.Format = jsAction;

pdf.Form.Fields.Add(textbox);
pdf.SaveToFile("FormatField.pdf",FileFormat.PDF);
[VB.NET]
Dim pdf As New PdfDocument()
Dim page As PdfPageBase = pdf.Pages.Add()
Dim textbox As New PdfTextBoxField(page, "Number-TextBox")
textbox.Bounds = New RectangleF(10, 10, 100, 20)
textbox.BorderWidth = 0.75F
textbox.BorderStyle = PdfBorderStyle.Solid

Dim js As String = PdfJavaScript.GetNumberKeystrokeString(2, 0, 0, 0, "$", True)
Dim jsAction As New PdfJavaScriptAction(js)
textbox.Actions.KeyPressed = jsAction

js = PdfJavaScript.GetNumberFormatString(2, 0, 0, 0, "$", True)
jsAction = New PdfJavaScriptAction(js)
textbox.Actions.Format = jsAction

pdf.Form.Fields.Add(textbox)
pdf.SaveToFile("FormatField.pdf", FileFormat.PDF)

Simple introduction about OpenDocument Spreadsheet format

The OpenDocument Spreadsheet format (commonly referred to as ODS format) is an XML-based file format for editable spreadsheet documents defined by OASIS. This free ISO-standardized format is now widely supported by a variety of free software applications, such as OpenOffice.org and the LibreOffice suite.

Using C#/VB.NET to convert Excel to .ods format via Spire.XLS

Spire.XLS, a powerful .NET excel component, enables developers to convert excel documents to ods format easily. This part will introduce you the solution of converting excel to .ods format in c# and vb.net.

Now, please view the following screenshot of the original excel document in .xlsx format:

How to Convert Excel to OpenDocument Spreadsheet (.ods) format in C#, VB.NET

Then refer to the following steps:

Step 1: Initialize a new instance of Workbook class and load the excel document from file.

Workbook workbook = new Workbook();
workbook.LoadFromFile("Sample.xlsx");

Step 2: Invoke Workbook.SaveToFile(string fileName, FileFormat fileFormat) method to save the excel document to ODS format.

workbook.SaveToFile("Result.ods",FileFormat.ODS);

Run the project, we will get the following result file in .ods format:

How to Convert Excel to OpenDocument Spreadsheet (.ods) format in C#, VB.NET

Full codes:

[C#]
using Spire.Xls;

namespace Convert_Excel_to_ODS
{
    class Program
    {
        static void Main(string[] args)
        {
            Workbook workbook = new Workbook();
            workbook.LoadFromFile("Sample.xlsx");
            workbook.SaveToFile("Result.ods",FileFormat.ODS);
        }
    }
}
[VB.NET]
Imports Spire.Xls

Namespace Convert_Excel_to_ODS
	Class Program
		Private Shared Sub Main(args As String())
			Dim workbook As New Workbook()
			workbook.LoadFromFile("Sample.xlsx")
			workbook.SaveToFile("Result.ods", FileFormat.ODS)
		End Sub
	End Class
End Namespace=

With the help of Spire.Doc for .NET, not only can we split a word document by section, but also can split it by page break. We've already introduced how to split a Word document into multiple documents by section break. In this article, we'll learn how to split a word document by page break with Spire.Doc for .NET.

Please view the following screenshot of the original word document which has two page breaks at the end of the first and the second page.

How to split a word document by page break in C#

Now refer to the following detail steps to split it into 3 separate documents by page breaks.

Step 1: Create a word document and load the original word document.

Document original = new Document();
original.LoadFromFile("New Zealand.docx");

Step 2: Create a new word document and add a section to it.

Document newWord = new Document();
Section section = newWord.AddSection();

Step 3: Split the original word document into separate documents according to page break.

int index = 0;
//traverse through all sections of original document
foreach (Section sec in original.Sections)
{
    //traverse through all body child objects of each section
    foreach (DocumentObject obj in sec.Body.ChildObjects)
    {
        if (obj is Paragraph)
        {
            Paragraph para = obj as Paragraph;
            //add paragraph object in original section into section of new document
            section.Body.ChildObjects.Add(para.Clone());
            foreach (DocumentObject parobj in para.ChildObjects)
            {
                if (parobj is Break && (parobj as Break).BreakType == BreakType.PageBreak)
                {
                    //get the index of page break in paragraph
                    int i = para.ChildObjects.IndexOf(parobj);
                    //remove the page break from its paragraph
                    section.Body.LastParagraph.ChildObjects.RemoveAt(i);

                    //save the new document to a .docx file.
                    newWord.SaveToFile(String.Format("result/out-{0}.docx", index), FileFormat.Docx);
                    index++;

                    //create a new document
                    newWord = new Document();
                    //add a section for document
                    section = newWord.AddSection();
                    //add paragraph object in original section into section of new document
                    section.Body.ChildObjects.Add(para.Clone());
                    if (section.Paragraphs[0].ChildObjects.Count == 0)
                    {
                        //remove the first blank paragraph
                        section.Body.ChildObjects.RemoveAt(0);
                    }
                    else
                    {
                        //remove the child objects before the page break
                        while (i >= 0)
                        {
                            section.Paragraphs[0].ChildObjects.RemoveAt(i);
                            i--;
                        }
                    }
                }
            }
        }
        if (obj is Table)
        {
            //add table object in original section into section of new document
            section.Body.ChildObjects.Add(obj.Clone());
        }
    }
}
//save to a .docx file
newWord.SaveToFile(String.Format("result/out-{0}.docx", index), FileFormat.Docx);

Output:

How to split a word document by page break in C#

Full codes:

using System;
using Spire.Doc;
using Spire.Doc.Documents;

namespace Split_Word_Document_by_Page_Break
{
    class Program
    {
        static void Main(string[] args)
        {
            Document original = new Document();
            original.LoadFromFile("New Zealand.docx");
            Document newWord = new Document();
            Section section = newWord.AddSection();

            int index = 0;
            foreach (Section sec in original.Sections)
            {
                foreach (DocumentObject obj in sec.Body.ChildObjects)
                {
                    if (obj is Paragraph)
                    {
                        Paragraph para = obj as Paragraph;
                        section.Body.ChildObjects.Add(para.Clone());

                        foreach (DocumentObject parobj in para.ChildObjects)
                        {
                            if (parobj is Break && (parobj as Break).BreakType == BreakType.PageBreak)
                            {
                                int i = para.ChildObjects.IndexOf(parobj);
                                section.Body.LastParagraph.ChildObjects.RemoveAt(i);
                                newWord.SaveToFile(String.Format("result/out-{0}.docx", index), FileFormat.Docx);
                                index++;

                                newWord = new Document();
                                section = newWord.AddSection();
                                section.Body.ChildObjects.Add(para.Clone());
                                if (section.Paragraphs[0].ChildObjects.Count == 0)
                                {
                                    section.Body.ChildObjects.RemoveAt(0);
                                }
                                else
                                {
                                    while (i >= 0)
                                    {
                                        section.Paragraphs[0].ChildObjects.RemoveAt(i);
                                        i--;
                                    }
                                }
                            }
                        }
                    }
                    if (obj is Table)
                    {
                        section.Body.ChildObjects.Add(obj.Clone());
                    }
                }
            }
            newWord.SaveToFile(String.Format("result/out-{0}.docx", index), FileFormat.Docx);
        }
    }
}

We have already demonstrated how to create the excel pivot table with Spire.XLS for .NET. It enables developers to set the property of PivotFieldFormatType to set format for the Data fields on pivot table. The following code sample will show you how to set display formats for data fields in C#.

Note: Before Start, please download the latest version of Spire.XLS and add Spire.Xls.dll in the bin folder as the reference of Visual Studio.

Firstly please check the original DataField format on PivotTable:

Set Data fields format on Excel PivotTable in C#

Step 1: Create a new Excel workbook and load from file.

Workbook workbook = new Workbook();
workbook.LoadFromFile("Sample.xlsx");

Step 2: Get the first worksheet from the workbook.

Worksheet sheet = workbook.Worksheets[0];

Step 3: Accessing the first Pivot table from the first worksheet.

XlsPivotTable pt = sheet.PivotTables[0] as XlsPivotTable;

Step 4: Accessing the Data Field.

PivotDataField pivotDataField = pt.DataFields[0];

Step 5: Setting data display format by setting the property of PivotFieldFormatType as PercentageOfColumn.

pivotDataField.ShowDataAs = PivotFieldFormatType.PercentageOfColumn;

Step 6: Save the document to file.

workbook.SaveToFile("Result.xlsx", ExcelVersion.Version2010);

The effective screenshot after setting the Datafield format in PivotTable:

Set Data fields format on Excel PivotTable in C#

Full codes of how to set the Datafields type in Excel Pivot Table.

static void Main(string[] args)

 {
     Workbook workbook = new Workbook();
     workbook.LoadFromFile("Sample.xlsx");

     Worksheet sheet = workbook.Worksheets[0];

     XlsPivotTable pt = sheet.PivotTables[0] as XlsPivotTable;

     PivotDataField pivotDataField = pt.DataFields[0];

     pivotDataField.ShowDataAs = PivotFieldFormatType.PercentageOfColumn;

     workbook.SaveToFile("Result.xlsx", ExcelVersion.Version2010);

 }

A PDF document encrypted with a user password legally cannot be opened without the password. We’d better detect if a document is password protected or not before we try to open it. This article presents how to determine if a PDF document is encrypted with password using Spire.PDF in C#, VB.NET.

Code Snippet:

Step 1: Initialize an instance of PdfDocument class.

PdfDocument doc = new PdfDocument();

Step 2: Load a sample PDF document.

doc.LoadFromFile(@"C:\Users\Administrator\Desktop\Encrypted.pdf");

Step 3: Detect whether the document is encrypted with password or not.

bool isEncrypted = doc.IsEncrypted;
Console.WriteLine(isEncrypted);

Result:

How to detect if a PDF document is password protected in C#, VB.NET

Full Code:

[C#]
PdfDocument doc = new PdfDocument();
doc.LoadFromFile(@"C:\Users\Administrator\Desktop\Encrypted.pdf");

bool isEncrypted = doc.IsEncrypted;
Console.WriteLine(isEncrypted);
Console.Read();
[VB.NET]
Dim doc As New PdfDocument()
doc.LoadFromFile("C:\Users\Administrator\Desktop\Encrypted.pdf")

Dim isEncrypted As Boolean = doc.IsEncrypted
Console.WriteLine(isEncrypted)
Console.Read()