Monday, 18 September 2017 09:28

Add Tab Stops to Word Paragraphs in C#

Tab stops are markers placed on the ruler that define how text or numbers are aligned on a line. To add tab stops to a paragraph in Microsoft Word, we need to open the Tabs dialog box and then set the tab stop position, alignment and leader as shown below.

Add Tab Stops to Word Paragraphs in C#

This article elaborates how to add tab stops to paragraphs in word document programmatically using Spire.Doc.

Detail steps:

Step 1: Instantiate a Document object and add a section to it.

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

Step 2: Add paragraph 1 to the section.

Paragraph paragraph1 = section.AddParagraph();

Step 3: Add tab stops to paragraph 1.

//Add tab and set its position (in points)
Tab tab = paragraph1.Format.Tabs.AddTab(28);
//Set tab alignment
tab.Justification = TabJustification.Left;
//move to next tab and append text
paragraph1.AppendText("\tWashing Machine");

//Add another tab and set its position (in points)
tab = paragraph1.Format.Tabs.AddTab(280);
//Set tab alignment
tab.Justification = TabJustification.Left;
//Specify tab leader type
tab.TabLeader = TabLeader.Dotted;
//move to next tab and append text
paragraph1.AppendText("\t$650"); 

Step 4: Add paragraph 2 to the section.

Paragraph paragraph2 = section.AddParagraph();

Step 5: Add tab stops to paragraph 2.

//Add tab and set its position (in points)
tab = paragraph2.Format.Tabs.AddTab(28);
//Set tab alignment
tab.Justification = TabJustification.Left;
//move to next tab and append text
paragraph2.AppendText("\tRefrigerator");

//Add another tab and set its position (in points)
tab = paragraph2.Format.Tabs.AddTab(280);
//Set tab alignment
tab.Justification = TabJustification.Left;
//Specify tab leader type
tab.TabLeader = TabLeader.NoLeader;
//move to next tab and append text
paragraph2.AppendText("\t$800"); 

Step 6: Save and close the document object.

document.SaveToFile("Tab.docx", FileFormat.Docx2013);
document.Close();

Screenshot:

Add Tab Stops to Word Paragraphs in C#

Full code:

//Instantiate a Document object
Document document = new Document();
//Add a section
Section section = document.AddSection();            

//Add paragraph 1
Paragraph paragraph1 = section.AddParagraph();

//Add tab and set its position (in points)
Tab tab = paragraph1.Format.Tabs.AddTab(28);
//Set tab alignment
tab.Justification = TabJustification.Left;
//move to next tab and append text
paragraph1.AppendText("\tWashing Machine");

//Add another tab and set its position (in points)
tab = paragraph1.Format.Tabs.AddTab(280);
//Set tab alignment
tab.Justification = TabJustification.Left;
//Specify tab leader type
tab.TabLeader = TabLeader.Dotted;
//move to next tab and append text
paragraph1.AppendText("\t$650"); 

//Add paragraph 2
Paragraph paragraph2 = section.AddParagraph();

//Add tab and set its position (in points)
tab = paragraph2.Format.Tabs.AddTab(28);
//Set tab alignment
tab.Justification = TabJustification.Left;
//move to next tab and append text
paragraph2.AppendText("\tRefrigerator"); //move to next tab and append text

//Add another tab and set its position (in points)
tab = paragraph2.Format.Tabs.AddTab(280);
//Set tab alignment
tab.Justification = TabJustification.Left;
//Specify tab leader type
tab.TabLeader = TabLeader.NoLeader;
//move to next tab and append text
paragraph2.AppendText("\t$800"); 

//Save and close the document object            
document.SaveToFile("Tab.docx", FileFormat.Docx2013);
document.Close();
Friday, 15 September 2017 06:43

Generate QR Code in Java

In the previous post, we have demonstrated how to use Spire.Barcode for Java to create barcode images in Java applications. This tutorial provides code sample for generating QR code in Java.

package GenerateBarcode;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

import com.spire.barcode.BarCodeGenerator;
import com.spire.barcode.BarCodeType;
import com.spire.barcode.BarcodeSettings;
import com.spire.barcode.QRCodeECL;
import com.sun.javafx.print.Units;

public class QR_Code {

	public static void main(String[] args) throws IOException {

        //create an instance of BarcodeSetteings
        BarcodeSettings settings = new BarcodeSettings();
        //set barcode type
        settings.setType(BarCodeType.QR_CODE);
        //set barcode data
        settings.setData("ABC 123456789");
        //set dispaly text
        settings.setData2D("ABC 123456789");
        //show text on bottom
        settings.setShowTextOnBottom(true);
        //set the border invisible
        settings.hasBorder(false);
        //set width of the barcode module
        settings.setX(2);
        //set the error correction level
        settings.setQRCodeECL(QRCodeECL.M);    
        //create BarCodeGenerator object based on settings
        BarCodeGenerator barCodeGenerator = new BarCodeGenerator(settings);
        //generate image data and store in BufferedImage instance
        BufferedImage bufferedImage = barCodeGenerator.generateImage();
        //save to image
        ImageIO.write(bufferedImage,"png",new File("QR_CODE.png"));
        System.out.println("Complete!");
	}

}

Output:

Generate QR Code in Java

With Spire.XLS for .NET, we could easily add different kinds of charts to Excel worksheet, such as Pie Chart, Column Chart, bar chart, line chart, radar chart, Doughnut chart, pyramid chart, etc. In this article, we'll show you how to remove chart from Excel worksheet by using Spire.XLS.

Below is a sample document which contains a chart and table from the Excel worksheet, then we'll remove the chart from the slide.

How to remove chart from Excel worksheet in C#, VB.NET

C# Code Snippet of how to remove the chart from Excel:

Step 1: Create an instance of Excel workbook and load the document 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: Get the first chart from the first worksheet.

IChartShape chart = sheet.Charts[0];

Step 4: Remove the chart.

chart.Remove();

Step 5: Save the document to file.

workbook.SaveToFile("RemoveChart.xlsx");

Effective screenshot:

How to remove chart from Excel worksheet in C#, VB.NET

Full code:

[C#]
Workbook workbook = new Workbook();
workbook.LoadFromFile("Sample.xlsx");
Worksheet sheet = workbook.Worksheets[0];
IChartShape chart = sheet.Charts[0];
chart.Remove();
workbook.SaveToFile("RemoveChart.xlsx");
[VB.NET]
Dim workbook As New Workbook()
workbook.LoadFromFile("Sample.xlsx")
Dim sheet As Worksheet = workbook.Worksheets(0)
Dim chart As IChartShape = sheet.Charts(0)
chart.Remove()
workbook.SaveToFile("RemoveChart.xlsx")

In Word, textbox can contain multiple elements such as text, image and table. This article demonstrates how to insert table into word textbox, and read and delete existing table from word textbox using Spire.Doc.

Insert table

//Create a Document instance
Document document = new Document();

//Add a section
Section section = document.AddSection();
//Add a paragraph to the section
Paragraph paragraph = section.AddParagraph();

//Add textbox to the paragraph
TextBox textbox = paragraph.AppendTextBox(300, 100);

//Add text to textbox
Paragraph textboxParagraph = textbox.Body.AddParagraph();
TextRange textboxRange = textboxParagraph.AppendText("Table 1");
textboxRange.CharacterFormat.FontName = "Arial";

//Insert table to textbox
Table table = textbox.Body.AddTable(true);
//Specify the number of rows and columns of the table
table.ResetCells(4, 4);

string[,] data = new string[,]  
{  
{"Name","Age","Gender","ID" },  
{"John","28","Male","0023" },  
{"Steve","30","Male","0024" },  
{"Lucy","26","female","0025" }  
};

//Add data to table 
for (int i = 0; i < 4; i++)
{
    for (int j = 0; j < 4; j++)
    {
        TextRange tableRange = table[i, j].AddParagraph().AppendText(data[i, j]);
        tableRange.CharacterFormat.FontName = "Arial";
    }
}

//Apply style to table
table.ApplyStyle(DefaultTableStyle.LightGridAccent3);

//Save the document
document.SaveToFile("Output.docx", FileFormat.Docx2013);

Insert, Read and Delete Table from Word Textbox in C#

Read table

//Create a Document instance and load the word document
Document document = new Document("Output.docx");

//Get the first textbox
TextBox textbox = document.TextBoxes[0];

//Get the first table in the textbox
Table table = textbox.Body.Tables[0] as Table;

StringBuilder sb = new StringBuilder();

//Loop through the paragraphs of the table and extract text to a .txt file
foreach (TableRow row in table.Rows)
{
    foreach (TableCell cell in row.Cells)
    {
        foreach (Paragraph paragraph in cell.Paragraphs)
        {
            sb.AppendLine(paragraph.Text);
        }
    }
}
File.WriteAllText("text.txt", sb.ToString());

Insert, Read and Delete Table from Word Textbox in C#

Delete table

//Create a Document instance and load the word document
Document document = new Document("Output.docx");

//Get the first textbox
TextBox textbox = document.TextBoxes[0];

//Remove the first table from the textbox
textbox.Body.Tables.RemoveAt(0);

//Save the document
document.SaveToFile("RemoveTable.docx", FileFormat.Docx2013);

Insert, Read and Delete Table from Word Textbox in C#

When creating charts from scratch in PowerPoint slide, an Excel sheet with some dummy data will automatically be generated. The dummy data can be overwritten with the data from data source as well as from an existing Excel file. This article demonstrates how we can create chart in PowerPoint using the data in Excel file.

This solution requires Spire.Presneation.dll and Spire.Xls.dll to be added as references in project. Please download Spire.Office and reference the corresponding DLLs from it.

Here is the Excel sheet containing our sample data.

How to Create Chart Using Excel Data in PowerPoint in C#, VB.NET

Step 1: Create a Presentation document.

Presentation ppt = new Presentation();

Step 2: Append a column chart in the first slide.

RectangleF rect = new RectangleF(40, 100, 550, 320);
IChart chart = ppt.Slides[0].Shapes.AppendChart(ChartType.ColumnClustered, rect);

Step 3: Clear the default dummy data.

chart.ChartData.Clear(0, 0, 5, 5);

Step 4: Load an existing Excel file to Workbook instance and get the first worksheet.

Workbook wb = new Workbook();
wb.LoadFromFile("data.xlsx");
Worksheet sheet = wb.Worksheets[0];

Step 5: Import data from the worksheet to chart table.

for (int r = 0; r < sheet.AllocatedRange.RowCount; r++)
{
    for (int c = 0; c < sheet.AllocatedRange.ColumnCount; c++)
    {
        chart.ChartData[r, c].Value = sheet.Range[r + 1, c + 1].Value2;
    }
}

Step 6: Set the series label and categories labels.

chart.Series.SeriesLabel = chart.ChartData["B1", "B1"];
chart.Categories.CategoryLabels = chart.ChartData["A2","A13"];

Step 7: Set the series values.

chart.Series[0].Values = chart.ChartData["B2","B13"];

Step 8: Save the file.

ppt.SaveToFile("chart.pptx",Spire.Presentation.FileFormat.Pptx2013);

Output:

How to Create Chart Using Excel Data in PowerPoint in C#, VB.NET

Full Code:

[C#]
using System;
using Spire.Presentation;
using System.Drawing;
using Spire.Presentation.Charts;
using Spire.Xls;

namespace CreateChartFromExcelData
{
    class Program
    {
        static void Main(string[] args)
        {
            //initialize an instance of Presentation class
            Presentation ppt = new Presentation();
            RectangleF rect = new RectangleF(40, 100, 550, 320);
            IChart chart = ppt.Slides[0].Shapes.AppendChart(ChartType.ColumnClustered, rect);

            //clear the default dummy data
            chart.ChartData.Clear(0, 0, 5, 5);

            //load an existing Excel file to Workbook object
            Workbook wb = new Workbook();
            wb.LoadFromFile("data.xlsx");
            Worksheet sheet = wb.Worksheets[0];

            //import data from the sheet to chart table
            for (int r = 0; r < sheet.AllocatedRange.RowCount; r++)
            {
                for (int c = 0; c < sheet.AllocatedRange.ColumnCount; c++)
                {
                    chart.ChartData[r, c].Value = sheet.Range[r + 1, c + 1].Value2;
                }
            }

            //add chart title
            chart.ChartTitle.TextProperties.Text = "Monthly Sales Report";
            chart.ChartTitle.TextProperties.IsCentered = true;
            chart.ChartTitle.Height = 30;
            chart.HasTitle = true;

            //set the series label
            chart.Series.SeriesLabel = chart.ChartData["B1", "B1"];

            //set the category labels
            chart.Categories.CategoryLabels = chart.ChartData["A2","A13"];

            //set the series values
            chart.Series[0].Values = chart.ChartData["B2","B13"];

            //save the file
            ppt.SaveToFile("chart.pptx",Spire.Presentation.FileFormat.Pptx2013);
        }
    }
}
[VB.NET]
Imports Spire.Presentation
Imports System.Drawing
Imports Spire.Presentation.Charts
Imports Spire.Xls

Namespace CreateChartFromExcelData
    Class Program
        Private Shared Sub Main(args As String())
			'initialize an instance of Presentation class
			Dim ppt As New Presentation()

            Dim rect As New RectangleF(40, 100, 550, 320)

            Dim chart As IChart = ppt.Slides(0).Shapes.AppendChart(ChartType.ColumnClustered, rect)

			'clear the default dummy data
			chart.ChartData.Clear(0, 0, 5, 5)

			'load an existing Excel file to Workbook object
			Dim wb As New Workbook()

            wb.LoadFromFile("data.xlsx")
			Dim sheet As Worksheet = wb.Worksheets(0)

			'import data from the sheet to chart table
			For r As Integer = 0 To sheet.AllocatedRange.RowCount - 1
				For c As Integer = 0 To sheet.AllocatedRange.ColumnCount - 1

                    chart.ChartData(r, c).Value = sheet.Range(r + 1, c + 1).Value2
                Next

            Next

			'add chart title
			chart.ChartTitle.TextProperties.Text = "Monthly Sales Report"
			chart.ChartTitle.TextProperties.IsCentered = True
            chart.ChartTitle.Height = 30
			chart.HasTitle = True

			'set the series label

            chart.Series.SeriesLabel = chart.ChartData("B1", "B1")

			'set the category labels

            chart.Categories.CategoryLabels = chart.ChartData("A2", "A13")

			'set the series values

            chart.Series(0).Values = chart.ChartData("B2", "B13")

			'save the file
			ppt.SaveToFile("chart.pptx", Spire.Presentation.FileFormat.Pptx2013)
		End Sub

    End Class
End Namespace
Thursday, 07 September 2017 03:17

Remove conditional format from Excel in C#

With the help of Spire.XLS, we can set the conditional format the Excel cell in C# and VB.NET. We can also use Spire.XLS to remove the conditional format from a specific cell or the entire Excel worksheet. This article will demonstrate how to remove conditional format from Excel in C#.

Firstly, view the original Excel worksheet with conditional formats:

Remove conditional format from Excel in C#

Step 1: Create an instance of Excel workbook and load the document 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: Remove the conditional formats from the specific Excel Cell B2.

sheet.Range["B2"].ConditionalFormats.Remove();

Step 4: Remove all the conditional formats from the whole Excel worksheet.

sheet.AllocatedRange.ConditionalFormats.Remove();

Step 5: Save the document to file.

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

Remove the conditional format from a special Excel range B2:

Remove conditional format from Excel in C#

Remove all the conditional formats from the entire Excel worksheet:

Remove conditional format from Excel in C#

Full codes of how to remove the conditional formats from Excel worksheet:

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

Worksheet sheet = workbook.Worksheets[0];

//sheet.Range["B2"].ConditionalFormats.Remove();

sheet.AllocatedRange.ConditionalFormats.Remove();

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

In Spire.XLS, we can hide or show the headers of rows and columns by setting the RowColumnHeadersVisible property of XlsWorksheet class. This article elaborates the steps of how to accomplish this function using Spire.XLS.

The following screenshot shows the input file which contain one worksheet with row and column headers.

Hide or Show Row Column Headers in Excel with C#

Detail steps:

Step 1: Instantiate a Workbook instance and load the Excel file.

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

Step 2: Get the first worksheet.

Worksheet sheet = workbook.Worksheets[0];

Step 3: Hide or show the headers of rows and columns in the worksheet.

//Hide the headers of rows and columns
sheet.RowColumnHeadersVisible = false;

//Show the headers of rows and columns
//sheet.RowColumnHeadersVisible = true;

Step 4: Save the file.

workbook.SaveToFile("Output.xlsx");

The screenshot after hiding the row and column headers:

Hide or Show Row Column Headers in Excel with C#

Full code:

// Instantiate a Workbook instance
Workbook workbook = new Workbook();
//Load the Excel file
workbook.LoadFromFile("Input.xlsx");

//Get the first worksheet
Worksheet sheet = workbook.Worksheets[0];

//Hide the headers of rows and columns
sheet.RowColumnHeadersVisible = false;

//Show the headers of rows and columns
//sheet.RowColumnHeadersVisible = true;
            
//Save the file
workbook.SaveToFile("Output.xlsx");
Wednesday, 30 August 2017 02:53

Expand and Collapse Groups in Excel with C#

When we group rows or columns in Excel, we can use the expand/collapse button to show/hide the grouped data. This article demonstrates how to expand and collapse the groups in an Excel file programmatically using Spire.XLS.

Below screenshot shows the sample Excel file with rows 3 and 4 grouped:

Expand and Collapse Groups in Excel with C#

Detail steps:

Step 1: Create a Workbook instance and load the Excel file.

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

Step 2: Get the first worksheet.

Worksheet sheet = workbook.Worksheets[0];

Step 3: Expand or Collapse the grouped rows with ExpandCollapseFlags set to expand parent.

//Expand group
sheet.Range["A3:B4"].ExpandGroup(GroupByType.ByRows, ExpandCollapseFlags.ExpandParent);

//Collapse group
//sheet.Range["A3:B4"].CollapseGroup(GroupByType.ByRows);

Step 4: Save the file.

workbook.SaveToFile("Output.xlsx");

The screenshot after running the project:

Expand and Collapse Groups in Excel with C#

Full code:

//Create Workbook instance
Workbook workbook = new Workbook();
//Load the Excel file
workbook.LoadFromFile("Input.xlsx");

//Get the first worksheet
Worksheet sheet = workbook.Worksheets[0];

//Expand the grouped rows with ExpandCollapseFlags set to expand parent
sheet.Range["A3:B4"].ExpandGroup(GroupByType.ByRows, ExpandCollapseFlags.ExpandParent);

//Collapse the grouped rows
//sheet.Range["A3:B4"].CollapseGroup(GroupByType.ByRows);

//Save the file
workbook.SaveToFile("Output.xlsx");
Wednesday, 23 August 2017 06:30

C# Convert PDF to HTML

From Spire.PDF for .NET 3.9.285, it is possible to convert PDF files to HTML in C# and VB.NET. The output format for saving images and texts is SVG when converting PDF to HTML. This article will demonstrate how to use Spire.PDF to save PDF file as HTML format.

The sample PDF file includes image, text and hyperlink.

C# Convert PDF to HTML

We can realize our requirement of converting PDF to HTML in several lines of code. Here are the steps:

Step 1: Create a PDF document and load sample PDF.

PdfDocument pdf = new PdfDocument();
pdf.LoadFromFile("Test.pdf");

Step 2: Use SaveToFile method and set conversion target parameter as FileFormat.HTML.

pdf.SaveToFile("Result.html", FileFormat.HTML);

Here are the screenshot:

C# Convert PDF to HTML

Full codes:

[C#]
PdfDocument pdf = new PdfDocument();
pdf.LoadFromFile("Test.pdf");

pdf.SaveToFile("Result.html", FileFormat.HTML);
[VB.NET]
Dim pdf As New PdfDocument()
pdf.LoadFromFile("Test.pdf")
pdf.SaveToFile("Result.html", FileFormat.HTML)

This article presents how to import Spire.Barcode.jar in Java application and create barcode image using the classes involved.

Import Spire.Barcode.jar file

Step 1: Download Spire.Barcode for Java from the following URL. Unzip the package into a directory, you'll get Spire.Barcode.jar and Spire.Common.jar in the lib folder.

Step 2: Create a Java project in Eclipse.

Step 3: Right click the project name, select "New" - "Folder" to create a folder named "Lib".

How to Create Barcode Using Spire.Barcode for Java

Step 4: Copy the Spire.Barcode.jar file and Spire.Common.jar file to this folder.

How to Create Barcode Using Spire.Barcode for Java

Step 5: Select all the jar files, then right click on one of them and select "Build Path" – "Add to Build Path".

How to Create Barcode Using Spire.Barcode for Java

Until now, Spire.Barcode.jar and Spire.Common.jar have been referenced in your Java project. Expand the specific jar file in the “Package Explore” pane, and you’ll be able to view the classes, methods, properties, etc. inside the jar file.

How to Create Barcode Using Spire.Barcode for Java

Using the code

Following code snippet provides an example of creating Code 128 barcode using Spire.Barcode for Java.

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

import com.spire.barcode.BarCodeGenerator;
import com.spire.barcode.BarCodeType;
import com.spire.barcode.BarcodeSettings;

public class CODE_128 {

	public static void main(String[] args) throws IOException {
		
		//create an instance of BarcodeSetteings
        BarcodeSettings settings = new BarcodeSettings();
        //set barcode type
        settings.setType(BarCodeType.CODE_128);       
        //set barcode data
        settings.setData("123456789");
        //set the display text
        settings.setData2D("123456789");     
        //show text on bottom
        settings.setShowTextOnBottom(true);
        //set the border invisible
        settings.hasBorder(false);
        //create BarCodeGenerator object based on settings
        BarCodeGenerator barCodeGenerator = new BarCodeGenerator(settings);
        //generate image data and store in BufferedImage instance
        BufferedImage bufferedImage = barCodeGenerator.generateImage();
        //save to .png file format
        ImageIO.write(bufferedImage, "png", new File("CODE128.png"));
        System.out.println("Complete!");
	}
}

Output:

How to Create Barcode Using Spire.Barcode for Java