C#, VB.NET Replace Bookmarks in Word

Bookmarks can be used as placeholders in Word templates. By replacing the contents of bookmarks in the templates, developers can quickly generate a batch of Word documents with preset formatting and layout. In this article, I will explain how to replace bookmarks in Word documents in C# and VB.NET using a .NET Word API – Free Spire.Doc for .NET.

  • Replace Bookmark with Text
  • Replace Bookmark with Image
  • Replace Bookmark with HTML

Installation

You can download the DLL file of the API from this website or install it via NuGet by selecting Tools > NuGet Package Manager > Package Manager Console and then execute the following command:

Install-Package FreeSpire.Doc

Using the Code

Free Spire.Doc provides a BookmarksNavigator class which enables developers to easily navigate to a specific bookmark in a Word document and replace the content of it. The following code examples show how to replace bookmarks with text, image and html respectively using C# and VB.NET.

Example 1. Replace Bookmark with Text

C#

using Spire.Doc;
using Spire.Doc.Documents;
using System.Collections.Generic;

namespace ReplaceBookmarkWithText
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a Document instance
            Document document = new Document();
            //Load the template document
            document.LoadFromFile("Template.docx");

            //Create a Dictionary instance
            Dictionary<string, string> values = new Dictionary<string, string>()
            {
                {"Name", "Michael"  },
                {"Email", "Michael@outlook.com"},
                {"Address", "Canton, OH 44704"}
            };

            //Replace bookmark content with text
            foreach (KeyValuePair<string, string> item in values)
            {
                //Create a BookmarksNavigator instance
                BookmarksNavigator bookmarkNavigator = new BookmarksNavigator(document);
                //Locate the bookmark
                bookmarkNavigator.MoveToBookmark(item.Key);
                //Replace the bookmark content with text
                bookmarkNavigator.ReplaceBookmarkContent(item.Value, true);
                //Remove the bookmark
                document.Bookmarks.Remove(bookmarkNavigator.CurrentBookmark);
            }           

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

VB.NET

Imports Spire.Doc
Imports Spire.Doc.Documents
Imports System.Collections.Generic

Namespace ReplaceBookmarkWithText
    Friend Class Program
        Private Shared Sub Main(ByVal args As String())
            'Create a Document instance
            Dim document As Document = New Document()
            'Load the template document
            document.LoadFromFile("Template.docx")

            'Create a Dictionary instance
            Dim values As Dictionary(Of String, String) = New Dictionary(Of String, String)() From {
                {"Name", "Michael"},
                {"Email", "Michael@outlook.com"},
                {"Address", "Canton, OH 44704"}
            }

            'Replace bookmark content with text
            For Each item In values
                'Create a BookmarksNavigator instance
                Dim bookmarkNavigator As BookmarksNavigator = New BookmarksNavigator(document)
                'Locate the bookmark
                bookmarkNavigator.MoveToBookmark(item.Key)
                'Replace the bookmark content with text
                bookmarkNavigator.ReplaceBookmarkContent(item.Value, True)
                'Remove the bookmark
                document.Bookmarks.Remove(bookmarkNavigator.CurrentBookmark)
            Next

            'Save the result document
            document.SaveToFile("ReplaceBookmarkWithText.docx", FileFormat.Docx2013)
        End Sub
    End Class
End Namespace

The input Word template:

The template Word document

The result document:

Replace bookmark with text in C# and VB.NET

Example 2. Replace Bookmark with Image

C#

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

namespace ReplaceBookmarkWithImage
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a Document instance
            Document document = new Document();
            //Load the template document
            document.LoadFromFile("ReplaceBookmarkWithText.docx");

            //Replace bookmark with image              
            BookmarksNavigator bookmarkNavigator = new BookmarksNavigator(document);
            //Locate the bookmark  
            bookmarkNavigator.MoveToBookmark("Photo");
            //Add a paragraph
            Paragraph para = document.Sections[0].AddParagraph();
            //Add an image to the paragraph
            Image image = Image.FromFile("photo.png");
            para.AppendPicture(image);
            //Insert the paragraph to the bookmark
            bookmarkNavigator.InsertParagraph(para);
            //Remove the bookmark
            document.Bookmarks.Remove(bookmarkNavigator.CurrentBookmark);

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

VB.NET

Imports Spire.Doc
Imports Spire.Doc.Documents

Namespace ReplaceBookmarkWithImage
    Friend Class Program
        Private Shared Sub Main(ByVal args As String())
            'Create a Document instance
            Dim document As Document = New Document()
            'Load the template document
            document.LoadFromFile("ReplaceBookmarkWithText.docx")

            'Replace bookmark with image              
            Dim bookmarkNavigator As BookmarksNavigator = New BookmarksNavigator(document)
            'Locate the bookmark  
            bookmarkNavigator.MoveToBookmark("Photo")
            'Add a paragraph
            Dim para As Paragraph = document.Sections(0).AddParagraph()
            'Add an image to the paragraph
            Dim image As Image = Image.FromFile("photo.png")
            para.AppendPicture(image)
            'Insert the paragraph to the bookmark
            bookmarkNavigator.InsertParagraph(para)
            'Remove the bookmark
            document.Bookmarks.Remove(bookmarkNavigator.CurrentBookmark)

            'Save the result document
            document.SaveToFile("ReplaceBookmarkWithImage.docx", FileFormat.Docx2013)
        End Sub
    End Class
End Namespace

The result document:

Replace bookmark with image in C# and VB.NET

Example 3. Replace Bookmark with HTML

C#

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

namespace ReplaceBookmarkWithHtml
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a Document instance
            Document document = new Document();
            //Load the template document
            document.LoadFromFile("ReplaceBookmarkWithImage.docx");

            //Create a BookmarksNavigator instance            
            BookmarksNavigator bookmarkNavigator = new BookmarksNavigator(document);
            //Locate the bookmark  
            bookmarkNavigator.MoveToBookmark("Education");
            //Add a paragraph
            Paragraph para = document.Sections[0].AddParagraph();
            //Add HTML string to the paragraph
            para.AppendHTML("<p>University of South Florida, <font color=\"#ff0000\">September 2013 - June 2017</font></p>");
            //Insert the paragraph to the bookmark
            bookmarkNavigator.InsertParagraph(para);
            //Remove the bookmark
            document.Bookmarks.Remove(bookmarkNavigator.CurrentBookmark);

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

VB.NET

Imports Spire.Doc
Imports Spire.Doc.Documents

Namespace ReplaceBookmarkWithHtml
    Friend Class Program
        Private Shared Sub Main(ByVal args As String())
            'Create a Document instance
            Dim document As Document = New Document()
            'Load the template document
            document.LoadFromFile("ReplaceBookmarkWithImage.docx")

            'Create a BookmarksNavigator instance            
            Dim bookmarkNavigator As BookmarksNavigator = New BookmarksNavigator(document)
            'Locate the bookmark  
            bookmarkNavigator.MoveToBookmark("Education")
            'Add a paragraph
            Dim para As Paragraph = document.Sections(0).AddParagraph()
            'Add HTML string to the paragraph
            para.AppendHTML("<p>University of South Florida, <font color=""#ff0000"">September 2013 - June 2017</font></p>")
            'Insert the paragraph to the bookmark
            bookmarkNavigator.InsertParagraph(para)
            'Remove the bookmark
            document.Bookmarks.Remove(bookmarkNavigator.CurrentBookmark)

            'Save the result document
            document.SaveToFile("ReplaceBookmarkWithHtml.docx", FileFormat.Docx2013)
        End Sub
    End Class
End Namespace

The result document:

Replace bookmark with Html in C# and VB.NET

Apply Superscript or Subscript formatting to Text in Word using Java

Superscript or subscript is a kind of text formatting used to place characters (such as letters, numbers or symbols) slightly above or below the main line of text. They are often used in footnotes, endnotes and mathematical or scientific formulas, but have many other uses as well. In this article, I will demonstrate how to apply superscript or subscript formatting to text in a Word document in Java using Free Spire.Doc for Java API.

Add Dependencies

Method 1: If you are using maven, you can easily import the JAR file in your application by adding the following code to your project’s pom.xml file.

<repositories>
    <repository>
        <id>com.e-iceblue</id>
        <name>e-iceblue</name>
        <url>https://repo.e-iceblue.com/nexus/content/groups/public/</url>
    </repository>
</repositories>
<dependencies>
    <dependency>
        <groupId>e-iceblue</groupId>
        <artifactId>spire.doc.free</artifactId>
        <version>5.2.0</version>
    </dependency>
</dependencies>

Method 2: If you are not using maven, you can download the JAR file from this link, extract the zip file and then import the Spire.Doc.jar file under the lib folder into your project as a dependency.

Apply Superscript or Subscript Formatting to Text in Word using Java

To apply superscript or subscript formatting to text, you need to call Paragraph.appendText() method to add text that you want to format as superscript or subscript and get its reference into a TextRange object. Next, apply superscript or subscript formatting to the text using TextRange.getCharacterFormat().setSubSuperScript(SubSuperScript) method.

The following steps show how to add text and apply superscript or subscript formatting to the text in a Word document in Java:

  • Create an instance of Document class.
  • Add a section to the document using Document.addSection() method.
  • Add a paragraph to the section using Section.addParagraph() method.
  • Add regular text to the paragraph using Paragraph.appendText() method.
  • Add text that you want to format as superscript or subscript to the paragraph using Paragraph.appendText() method.
  • Apply superscript or subscript formatting to the text using TextRange.getCharacterFormat().setSubSuperScript(SubSuperScript) method.
  • Loop through the paragraph items and set font size for text.
  • Save the result document using Document.saveToFile() method.

Code example:

import com.spire.doc.Document;
import com.spire.doc.FileFormat;
import com.spire.doc.Section;
import com.spire.doc.documents.BreakType;
import com.spire.doc.documents.Paragraph;
import com.spire.doc.documents.SubSuperScript;
import com.spire.doc.fields.TextRange;

public class InsertSuperscriptAndSubscript {
    public static void main(String []args){
        //Create an instance of Document class
        Document document = new Document();
        //Add a section to the document
        Section section = document.addSection();

        //Add a paragraph to the section
        Paragraph paragraph = section.addParagraph();

        //Add regular text to the paragraph
        paragraph.appendText("E = mc");

        //Add text that you want to format as superscript to the paragraph 
        TextRange superscriptText = paragraph.appendText("2");
        //Apply superscript formatting to the text
        superscriptText.getCharacterFormat().setSubSuperScript(SubSuperScript.Super_Script);

        //Insert a line break to start a new line
        paragraph.appendBreak(BreakType.Line_Break);

        //Add regular text to the paragraph
        paragraph.appendText("H");
        //Add text that you want to format as subscript to the paragraph
        TextRange subscriptText = paragraph.appendText("2");
        //Apply subscript formatting to the text
        subscriptText.getCharacterFormat().setSubSuperScript(SubSuperScript.Sub_Script);
        //Add regular text to the paragraph
        paragraph.appendText("O");

        //Loop through paragraph items and set font size for text
        for(int i = 0; i < paragraph.getItems().getCount(); i++)
        {
            if(paragraph.getItems().get(i) instanceof  TextRange) {
                TextRange textRange = (TextRange) paragraph.getItems().get(i);
                textRange.getCharacterFormat().setFontSize(20f);
            }
        }

        //Save the result document
        document.saveToFile("InsertSuperscriptAndSubscript.docx", FileFormat.Docx_2013);
    }
}

The result document:

Insert Superscript or Subscript in Word using Java

Convert Excel to CSV and Vice Versa in Java

CSV files are comma separated values files in which data are stored as plain text. They are generally faster and consume less memory than Excel files. In some cases, you may be asked to convert Excel files to CSV for quick data import. This article will demonstrate how to convert Excel to CSV and vice versa in Java using Free Spire.XLS for Java API.

Add Dependencies

Method 1: If you are using maven, you can easily import the JAR file in your application by adding the following code to your project’s pom.xml file.

<repositories>
    <repository>
        <id>com.e-iceblue</id>
        <name>e-iceblue</name>
        <url>https://repo.e-iceblue.com/nexus/content/groups/public/</url>
    </repository>
</repositories>
<dependencies>
    <dependency>
        <groupId>e-iceblue</groupId>
        <artifactId>spire.xls.free</artifactId>
        <version>5.1.0</version>
    </dependency>
</dependencies>

Method 2: If you are not using maven, you can download the JAR file from this link, extract the zip file and then import the Spire.Xls.jar file under the lib folder into your project as a dependency.

Convert Excel to CSV in Java

The Worksheet class of Free Spire.XLS exposes a saveToFile() method which allows developers to easily convert a specific Excel worksheet as CSV.

The following are the steps to convert a specific worksheet as CSV:

  • Create an instance of a Workbook class.
  • Load the Excel file using Workbook.loadFromFile() method.
  • Get the desired worksheet by its index.
  • Call Worksheet.saveToFile() method to save the worksheet as CSV.

Code example:

import com.spire.xls.Workbook;
import com.spire.xls.Worksheet;

public class ConvertAWorksheetToCsv {
    public static void main(String []args){
        //Create an instance of Workbook class
        Workbook workbook = new Workbook();
        //Load an Excel file
        workbook.loadFromFile("Sample.xlsx");

        //Get the first worksheet
        Worksheet sheet = workbook.getWorksheets().get(0);

        //Save the worksheet as CSV
        sheet.saveToFile("ExcelToCSV.csv", ",");
    }
}
Convert Excel worksheet to CSV using Java

If you want to save multiple worksheets in an Excel file as separate CSV files, you need to loop through the worksheets and then save each worksheet as a CSV file. Refer to the code example below:

import com.spire.xls.Workbook;
import com.spire.xls.Worksheet;

public class ConvertAWorksheetToCsv {
    public static void main(String []args){
        //Create an instance of Workbook class
        Workbook workbook = new Workbook();
        //Load an Excel file
        workbook.loadFromFile("Sample.xlsx");

        //Loop through the worksheets in the file
        for(int i = 0; i< workbook.getWorksheets().getCount(); i++) {
            Worksheet sheet = workbook.getWorksheets().get(i);
            //Save each worksheet as separate CSV 
            sheet.saveToFile("ExcelToCSV_" + i + ".csv", ",");
        }
    }
}

Convert CSV to Excel in Java

To convert a CSV file to Excel file, you will need to load the CSV file using loadFromFile() method of Workbook class, then call the saveToFile() method of Workbook class to save it as Excel.

The following are the steps to convert a CSV to Excel:

  •  Create an instance of a Workbook class.
  • Load the CSV file using Workbook.loadFromFile() method.
  • Loop through the worksheets in the CSV file. Get the used range of each worksheet using Worksheet.getAllocatedRange() method, then ignore errors when setting numbers in the range of cells as text using CellRange.setIgnoreErrorOptions() method.
  • Save the CSV file as an Excel .xlsx file using Workbook.saveToFile() method.

Code example:

import com.spire.xls.*;

import java.util.EnumSet;

public class ConvertCsvToExcel {
    public static void main(String []args) {
        //Create an instance of Workbook class
        Workbook workbook = new Workbook();
        //Load a CSV file
        workbook.loadFromFile("ExcelToCSV.csv", ",");

        //Loop through the worksheets in the CSV file
        for (int i = 0; i < workbook.getWorksheets().getCount(); i++)
        {
            Worksheet sheet = workbook.getWorksheets().get(i);
            //Access the used range in each worksheet
            CellRange usedRange = sheet.getAllocatedRange();
            //Ignore errors when setting numbers in the used range as text
            usedRange.setIgnoreErrorOptions(EnumSet.of(IgnoreErrorType.NumberAsText));
            //Autofit columns and rows
            usedRange.autoFitColumns();
            usedRange.autoFitRows();
        }

        //Save the CSV file as Excel .xlsx file
        workbook.saveToFile("CSVToExcel.xlsx", ExcelVersion.Version2013);
    }
}
Convert CSV to Excel using Java

C#/VB.NET: Insert Superscripts and Subscripts in Word

A superscript or a subscript is a number, letter or symbol that appears slightly above (superscript) or below (subscript) the regular text line. If you are creating a document containing chemical expressions or scientific formulas, you will probably need to insert superscripts and subscripts. This article illustrates how to insert superscripts and subscripts in a Word document using C# and VB.NET.

API Installation

This article uses Free Spire.Doc for .NET API. You can download the DLL file of the API from this website or install it via NuGet by selecting Tools > NuGet Package Manager > Package Manager Console and then execute the following command:

Install-Package FreeSpire.Doc

Insert Superscript and Subscript in Word using C# and VB.NET

To insert a superscript or a subscript in Word, you need to use the Paragraph.AppendText() method to add a text, then apply superscript or subscript formatting to the text by setting the TextRange.CharacterFormat.SubSuperScript property as SubSuperScript.SuperScript or SubSuperScript.SubScript.

The following are the detailed steps for your reference:

  • Initialize an instance of Document class.
  • Add a section using Document.AddSection() method.
  • Add a paragraph using Section.AddParagraph() method.
  • Add regular text to the paragraph using Paragraph.AppendText() method.
  • Add superscript or subscript text to the paragraph using Paragraph.AppendText() method.
  • Apply superscript or subscript formatting to the superscript or subscript text by setting the TextRange.CharacterFormat.SubSuperScript property as SubSuperScript.SuperScript or SubSuperScript.SubScript.
  • Loop through the paragraph items and set font size for text.
  • Save the result document using Document.SaveToFile() method.

C#

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

namespace SuperscriptAndSubscript
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a Document instance
            Document document = new Document();
            //Add a section
            Section section = document.AddSection();

            //Add a paragraph
            Paragraph paragraph = section.AddParagraph();

            //Add regular text to the paragraph
            paragraph.AppendText("E = mc");
            //Add superscript text to the paragraph
            TextRange superscriptText = paragraph.AppendText("2");
            //Apply superscript formatting to the superscript text
            superscriptText.CharacterFormat.SubSuperScript = SubSuperScript.SuperScript;

            //Start a new line
            paragraph.AppendBreak(BreakType.LineBreak);

            //Add regular text to the paragraph
            paragraph.AppendText("H");
            //Add subscript text to the paragraph
            TextRange subscriptText = paragraph.AppendText("2");
            //Apply subscript formatting to the superscript text
            subscriptText.CharacterFormat.SubSuperScript = SubSuperScript.SubScript;
            paragraph.AppendText("O");

            //Loop through paragraph items
            foreach (var item in paragraph.Items)
            {
                if (item is TextRange)
                {
                    TextRange textRange = item as TextRange;
                    //Set font size for text
                    textRange.CharacterFormat.FontSize = 20f;
                }
            }

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

VB.NET

Imports Spire.Doc
Imports Spire.Doc.Documents
Imports Spire.Doc.Fields

Namespace SuperscriptAndSubscript
    Friend Class Program
        Private Shared Sub Main(ByVal args As String())
            'Create a Document instance
            Dim document As Document = New Document()
            'Add a section
            Dim section As Section = document.AddSection()

            'Add a paragraph
            Dim paragraph As Paragraph = section.AddParagraph()

            'Add regular text to the paragraph
            paragraph.AppendText("E = mc")
            'Add superscript text to the paragraph
            Dim superscriptText As TextRange = paragraph.AppendText("2")
            'Apply superscript formatting to the superscript text
            superscriptText.CharacterFormat.SubSuperScript = SubSuperScript.SuperScript

            'Start a new line
            paragraph.AppendBreak(BreakType.LineBreak)

            'Add regular text to the paragraph
            paragraph.AppendText("H")
            'Add subscript text to the paragraph
            Dim subscriptText As TextRange = paragraph.AppendText("2")
            'Apply subscript formatting to the superscript text
            subscriptText.CharacterFormat.SubSuperScript = SubSuperScript.SubScript
            paragraph.AppendText("O")

            'Loop through paragraph items
            For Each item In paragraph.Items

                If TypeOf item Is TextRange Then
                    Dim textRange As TextRange = TryCast(item, TextRange)
                    'Set font size for text
                    textRange.CharacterFormat.FontSize = 20F
                End If
            Next

            'Save the result document
            document.SaveToFile("ApplySuperscriptAndSubscript.docx", FileFormat.Docx2013)
        End Sub
    End Class
End Namespace

Output:

See More

Documentation | Examples | Forum 

C#: 10 Ways to Print PDF Documents

Printing is a common operation when working with PDF files. In this article, you will see 10 ways to print a PDF document using C# and VB.NET.

It consists of the following sections:

  • Print a PDF with the Default Printer
  • Print a PDF with a Specific Printer
  • Print a PDF Silently
  • Print Specific Pages of a PDF
  • Print a PDF on Both Sides of Papers (Duplex)
  • Print a PDF in Black and White (Grayscale)
  • Print Multiple Copies of a PDF
  • Print Multiple PDF Pages on One Page
  • Print a PDF as Booklet
  • Print a PDF at a Different Size

Installation

Spire.PDF for .NET is used here to print PDF documents. It’s a commercial library for creating, editing, converting and printing PDF documents. A free version of Spire.PDF for .NET is also available, but it should be pointed out that it’s limited to 10 pages while loading PDF files.

You can install either of them via NuGet:

Commercial version: Install-Package Spire.PDF

Free version: Install-Package FreeSpire.PDF

Print a PDF with the Default Printer in C#

Print a PDF with the default printer is extremely easy. You just need to follow two steps below:

  • Load the PDF document using PdfDocument class.
  • Call PdfDocument.Print() method to print the document.
using Spire.Pdf;

namespace PrintPdf
{
    class Program
    {
        static void Main(string[] args)
        {
            //Load a PDF document
            PdfDocument doc = new PdfDocument(@"C:\Users\Administrator\Desktop\sample.pdf");

            //Print the document with the default printer 
            doc.Print();
        }
    }
}

Print a PDF with a Specific Printer in C#

If you have multiple printers, you can print the PDF to a specific printer by referring to the steps below:

  • Load the PDF document using PdfDocument class.
  • Specify the printer’s name through PdfDocument.PrintSettings.PrinterName property.
  • Call PdfDocument.Print() method to print the document.
using Spire.Pdf;

namespace PrintPdfToSpecificPrinter
{
    class Program
    {
        static void Main(string[] args)
        {
            //Load a PDF document
            PdfDocument doc = new PdfDocument(@"C:\Users\Administrator\Desktop\sample.pdf");

            //Specify printer name
            doc.PrintSettings.PrinterName = "Printer Name";

            //Print the document
            doc.Print();
        }
    }
}

Print a PDF Silently in C#

It’s also possible to print a PDF document silently without showing the printer dialog. The following steps show how to implement silent printing:

  • Load the PDF document using PdfDocument class.
  • Specify the printer’s name through PdfDocument.PrintSettings.PrinterName property.
  • Prevent the printer dialog from displaying by setting the value of PdfDocument.PrintSettings.PrintController property to an instance of System.Drawing.Printing.StandardPrintController class.
  • Call PdfDocument.Print() method to print the document.
using Spire.Pdf;
using System.Drawing.Printing;

namespace PrintPdfSilently
{
    class Program
    {
        static void Main(string[] args)
        {
            //Load a PDF document
            PdfDocument doc = new PdfDocument(@"C:\Users\Administrator\Desktop\sample.pdf");

            //Specify printer name
            doc.PrintSettings.PrinterName = "Printer Name";

            //Prevent the printer dialog from displaying
            doc.PrintSettings.PrintController = new StandardPrintController();

            //Print the document
            doc.Print();
        }
    }
}

Print Specific Pages of a PDF in C#

At some point, you may want to print just specific pages instead of the entire PDF document. The following steps show how to print a specific page range by specifying the from and to page numbers. Furthermore, you will also see how to print discontinuous pages by giving the desired page numbers.

  • Load a PDF document using PdfDocument class.
  • Specify the printer’s name through PdfDocument.PrintSettings.PrinterName property.
  • Specify the page range using PdfDocument.PrintSettings.SelectPageRange(fromPageNumber, toPageNumber) method.

(If you want to print discontinuous pages, you can use the PdfDocument.PrintSettings.SelectSomePages() method and pass an int array of page numbers as a parameter.)

  • Call PdfDocument.Print() method to print the document.
using Spire.Pdf;

namespace PrintPdfPages
{
    class Program
    {
        static void Main(string[] args)
        {
            //Load a PDF document
            PdfDocument doc = new PdfDocument(@"C:\Users\Administrator\Desktop\sample.pdf");

            //Specify printer name
            doc.PrintSettings.PrinterName = "Printer Name";

            //Select a page range to print
            doc.PrintSettings.SelectPageRange(1, 5);

            //Select discontinuous pages to print
            //doc.PrintSettings.SelectSomePages(new int[] { 1, 3, 5, 7 });

            //Print the document
            doc.Print();
        }
    }
}

Print a PDF on Both Sides of Papers (Duplex) in C#

You can print a PDF on both sides of papers if your printer supports duplex printing. The following are the steps to do so:

  • Load a PDF document using PdfDocument class.
  • Specify the printer’s name through PdfDocument.PrintSettings.PrinterName property.
  • Determine if the printer supports duplex printing through PdfDocument.PrintSettings.CanDuplex property.
  • If the result is true, set the duplex printing mode through PdfDocument.PrintSettings.Duplex property and print the document using PdfDocument.Print() method.
using Spire.Pdf;
using System.Drawing.Printing;

namespace PrintPDFDocuments
{
    class Program
    {
        static void Main(string[] args)
        {
            //Load a PDF document
            PdfDocument doc = new PdfDocument(@"C:\Users\Administrator\Desktop\sample.pdf");

            //Specify printer name
            doc.PrintSettings.PrinterName = "Printer Name";

            //Determine if the printer supports duplex printing 
            if (doc.PrintSettings.CanDuplex)
            {
                //Set duplex printing mode
                doc.PrintSettings.Duplex = Duplex.Default;
                //Print the document
                doc.Print();
            }
        }
    }
}

Print a PDF in Black and White (Grayscale) in C#

Printing a color PDF in black and white can help you save the colored ink – in other words, you can print the document at a lower cost. The following steps explain how to print a PDF in black and white:

  • Load a PDF document using PdfDocument class.
  • Specify the printer’s name through PdfDocument.PrintSettings.PrinterName property.
  • Allow the document to be printed in black and while by setting the value of PdfDocument.PrintSettings.Color property to false.
  • Call PdfDocument.Print() method to print the document.  
using Spire.Pdf;

namespace PrintPdfInGrayscale
{
    class Program
    {
        static void Main(string[] args)
        {

            //Load a PDF document
            PdfDocument doc = new PdfDocument(@"C:\Users\Administrator\Desktop\sample.pdf");

            //Specify printer name
            doc.PrintSettings.PrinterName = "Printer Name";

            //Allow printing in black and white
            doc.PrintSettings.Color = false;

            //Print the document
            doc.Print();
        }
    }
}

Print Multiple Copies of a PDF in C#

Multiple- copy printing is often required when printing contracts. The following steps explain how to print multiple copies of a PDF document:

  • Load a PDF document using PdfDocument class.
  • Specify the printer’s name through PdfDocument.PrintSettings.PrinterName property.
  • Set the number of copies to print through PdfDocument.PrintSettings.Copies property.
  • Call PdfDocument.Print() method to print the document.  
using Spire.Pdf;

namespace PrintMultipleCopiesOfPdf
{
    class Program
    {
        static void Main(string[] args)
        {
            //Load a PDF document
            PdfDocument doc = new PdfDocument(@"C:\Users\Administrator\Desktop\sample.pdf");

            //Specify printer name
            doc.PrintSettings.PrinterName = "Printer Name";

            //Set the number of copies to print
            doc.PrintSettings.Copies = 2;

            //Print document
            doc.Print();
        }
    }
}

Print Multiple PDF Pages on One Page in C#

You can print two or more pages of a PDF on a single sheet of paper. Moreover, you can also specify how the pages are ordered (horizontal/horizontal reversed/vertical/vertical reversed).

The steps below explain how to print multiple PDF pages on a single sheet:

  • Load a PDF document using PdfDocument class.
  • Specify the printer’s name through PdfDocument.PrintSettings.PrinterName property.
  • Print desired number of pages on one sheet using PdfDocument.PrintSettings.SelectMultiPageLayout(rowCount, columnCount, hasPageBorder, PdfMultiPageOrder) method.
  • Call PdfDocument.Print() method to print the document.
using Spire.Pdf;
using Spire.Pdf.Print;

namespace PrintMultiplePdfPagesOnOnePage
{
    class Program
    {
        static void Main(string[] args)
        {
            //Load a PDF document
            PdfDocument doc = new PdfDocument(@"C:\Users\Administrator\Desktop\sample.pdf");

            //Specify printer name
            doc.PrintSettings.PrinterName = "Printer Name";

            //Print every two pages of the PDF document on one sheet
            doc.PrintSettings.SelectMultiPageLayout(1, 2, false, PdfMultiPageOrder.Horizontal);

            //Print the document
            doc.Print();
        }
    }
}

Print a PDF using Different Paper Trays in C#

In some cases, you may want to print different pages using different paper trays. You can follow the steps below to implement this task:

  • Load a PDF document using PdfDocument class.
  • Specify the printer’s name through PdfDocument.PrintSettings.PrinterName property.
  • Use paper settings event to set different paper trays for different page ranges.
  • Call PdfDocument.Print() method to print the document.
using Spire.Pdf;
using Spire.Pdf.Print;

namespace PrintPagesToDifferentPaperTrays
{
    class Program
    {
        static void Main(string[] args)
        {
            //Load a PDF document
            PdfDocument doc = new PdfDocument(@"C:\Users\Administrator\Desktop\sample.pdf");

            //Specify printer name
            doc.PrintSettings.PrinterName = "Printer Name";


            //Use paper settings event to set paper trays for different pages
            doc.PrintSettings.PaperSettings += delegate (object sender, PdfPaperSettingsEventArgs e)
            {
                //Set paper tray 1 for page 1-10
                if (1 <= e.CurrentPaper && e.CurrentPaper <= 10) 
                {
                    e.CurrentPaperSource = e.PaperSources[0]; 
                }
                //Set paper tray 2 for the rest of pages
                else
                {
                    e.CurrentPaperSource = e.PaperSources[1]; 
                }
            };

            //Print the document
            doc.Print();
        }
    }
}

Print a PDF as Booklet in C#

You can print a multi-page PDF as booklet by referring to the steps below:

  • Load a PDF document using PdfDocument class.
  • Specify the printer’s name through PdfDocument.PrintSettings.PrinterName property.
  • Set booklet layout using PdfDocument.PrintSettings.SelectBookletLayout(PdfBookletSubsetMode, PdfBookletBindingMode) method.
  • Call PdfDocument.Print() method to print the document.
using Spire.Pdf;
using Spire.Pdf.Print;

namespace PrintPdfAsBooklet
{
    class Program
    {
        static void Main(string[] args)
        {
            //Load the PDF document
            PdfDocument doc = new PdfDocument(@"C:\Users\Administrator\Desktop\sample.pdf");

            //Specify printer name
            doc.PrintSettings.PrinterName = "Printer Name";

            //Set booklet layout 
            doc.PrintSettings.SelectBookletLayout(PdfBookletSubsetMode.BothSides, PdfBookletBindingMode.Left);

            //Print the document            
            doc.Print();
        }
    }
}

Print a PDF at a Different Size

You can print a PDF at the actual size, or scale to fit the paper automatically or scale by a specific value. The following steps show how to print a PDF at the actual size.

  • Load a PDF document using PdfDocument class.
  • Specify the printer’s name through PdfDocument.PrintSettings.PrinterName property.
  • Set page scaling mode using PdfDocument.PrintSettings. SelectSinglePageLayout(PdfSinglePageScalingMode.ActualSize) method.
  • Call PdfDocument.Print() method to print the document.
using Spire.Pdf;
using Spire.Pdf.Print;

namespace PrintPDFDocuments
{
    class Program
    {
        static void Main(string[] args)
        {

            //Load the sample document
            PdfDocument doc = new PdfDocument(@"C:\Users\Administrator\Desktop\sample.pdf");

            //Specify printer name
            doc.PrintSettings.PrinterName = "Printer Name";

            //Set page scaling mode
            doc.PrintSettings.SelectSinglePageLayout(PdfSinglePageScalingMode.ActualSize);

            //Print the document            
            doc.Print();
        }
    }
}

C#/VB.NET: Insert or Delete Rows and Columns in Excel

Inserting or deleting rows and columns is a common manipulation while working on Excel worksheets. In this article, I will demonstrate how to insert or delete rows and columns in Excel in C# and VB.NET.

The following topics are covered:

  • Insert a Row and a Column
  • Insert Multiple Rows and Columns
  • Insert Rows and Columns with Formatting
  • Delete a Row and a Column
  • Delete Multiple Rows and Columns

Installation

In order to work with Excel files, this article uses Free Spire.XLS for .NET, which is a free and easy-to-use library for creating, editing and converting Excel files.

You can download the DLL files of Free Spire.XLS for .NET from this website or install them via NuGet by selecting Tools > NuGet Package Manager > Package Manager Console and then execute the following command:

PM> Install-Package FreeSpire.XLS

Insert a Row and a Column into Excel in C# and VB.NET

You can insert a row and a column at a specific index in a worksheet by using the XlsWorksheet.InsertRow(rowIndex) and XlsWorksheet.InsertColumn(columnIndex) methods.

The following example shows how to insert a row and a column into an Excel worksheet using C# and VB.NET:

C#

using Spire.Xls;

namespace InsertRowAndColumn
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a Workbook instance
            Workbook workbook = new Workbook();
            //Load an Excel file
            workbook.LoadFromFile("Sample.xlsx");

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

            //Insert a row at the 2nd row index
            sheet.InsertRow(2);
            //Insert a column at the 2nd column index
            sheet.InsertColumn(2);

            //Save the result file
            workbook.SaveToFile("InsertRowAndColumn.xlsx", ExcelVersion.Version2016);
        }
    }
}

VB.NET

Imports Spire.Xls

Namespace InsertRowAndColumn
    Friend Class Program
        Private Shared Sub Main(ByVal args As String())
            'Create a Workbook instance
            Dim workbook As Workbook = New Workbook()
            'Load an Excel file
            workbook.LoadFromFile("Sample.xlsx")

            'Get the first worksheet 
            Dim sheet As Worksheet = workbook.Worksheets(0)

            'Insert a row at the 2nd row index
            sheet.InsertRow(2)
            'Insert a column at the 2nd column index
            sheet.InsertColumn(2)

            'Save the result file
            workbook.SaveToFile("InsertRowAndColumn.xlsx", ExcelVersion.Version2016)
        End Sub
    End Class
End Namespace

Output:

Insert row and column into Excel in C# and VB.NET

Insert Multiple Rows and Columns into Excel in C# and VB.NET

Sometimes, you may want to insert multiple rows and columns at once. To achieve that, you can use the XlsWorksheet.InsertRow(rowIndex, rowCount) and XlsWorksheet.InsertColumn(columnIndex, columnCount) methods.

The following example shows how to insert multiple rows and columns into an Excel worksheet using C# and VB.NET:

C#

using Spire.Xls;

namespace InsertRowsAndColumns
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a Workbook instance
            Workbook workbook = new Workbook();
            //Load an Excel file
            workbook.LoadFromFile("Sample.xlsx");

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

            //Insert 3 rows at the 5th row index
            sheet.InsertRow(5, 3);
            //Insert 3 columns at the 2nd column index
            sheet.InsertColumn(2, 3);

            //Save the result file
            workbook.SaveToFile("InsertMultipleRowsAndColumns.xlsx", ExcelVersion.Version2016);
        }
    }
}

VB.NET

Imports Spire.Xls

Namespace InsertRowsAndColumns
    Friend Class Program
        Private Shared Sub Main(ByVal args As String())
            'Create a Workbook instance
            Dim workbook As Workbook = New Workbook()
            'Load an Excel file
            workbook.LoadFromFile("Sample.xlsx")

            'Get the first worksheet 
            Dim sheet As Worksheet = workbook.Worksheets(0)

            'Insert 3 rows at the 5th row index
            sheet.InsertRow(5, 3)
            'Insert 3 columns at the 2nd column index
            sheet.InsertColumn(2, 3)

            'Save the result file
            workbook.SaveToFile("InsertMultipleRowsAndColumns.xlsx", ExcelVersion.Version2016)
        End Sub
    End Class
End Namespace

Output:

Insert multiple rows and columns into Excel in C# and VB.NET

Insert Rows and Columns with Formatting into Excel in C# and VB.NET

You can insert rows and columns with formatting by using the XlsWorksheet.InsertRow(rowIndex, rowCount, InsertOptionsType) and XlsWorksheet.InsertColumn(columnIndex, columnCount, InsertOptionsType) methods.

The following are the formatting type you can set while inserting rows and columns:

InsertOptionsType.FormatAsBefore: Indicates the inserted row/column has the same format as the above row or left column.

InsertOptionsType.FormatAsAfter: Indicates the inserted row/column has the same format as the below row or right column.

InsertOptionsType.FormatDefault: Indicates the inserted row/column has default format.

The following example shows how to insert rows and columns with formatting using C# and VB.NET:

C#

using Spire.Xls;

namespace InsertRowsAndColumnsWithFormatting
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a Workbook instance
            Workbook workbook = new Workbook();
            //Load an Excel file
            workbook.LoadFromFile("Sample.xlsx");

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

            //Insert 3 rows at the 5th row index with the same formatting of the above row
            sheet.InsertRow(5, 3, InsertOptionsType.FormatAsBefore);
            //Insert 3 columns at the 2nd column index with the same formatting of the right column
            sheet.InsertColumn(2, 3, InsertOptionsType.FormatAsAfter);

            //Save the result file
            workbook.SaveToFile("InsertRowsAndColumnsWithFormatting.xlsx", ExcelVersion.Version2016);
        }
    }
}

VB.NET

Imports Spire.Xls

Namespace InsertRowsAndColumnsWithFormatting
    Friend Class Program
        Private Shared Sub Main(ByVal args As String())
            'Create a Workbook instance
            Dim workbook As Workbook = New Workbook()
            'Load an Excel file
            workbook.LoadFromFile("Sample.xlsx")

            'Get the first worksheet 
            Dim sheet As Worksheet = workbook.Worksheets(0)

            'Insert 3 rows at the 5th row index with the same formatting of the above row
            sheet.InsertRow(5, 3, InsertOptionsType.FormatAsBefore)
            'Insert 3 columns at the 2nd column index with the same formatting of the right column
            sheet.InsertColumn(2, 3, InsertOptionsType.FormatAsAfter)

            'Save the result file
            workbook.SaveToFile("InsertRowsAndColumnsWithFormatting.xlsx", ExcelVersion.Version2016)
        End Sub
    End Class
End Namespace

Output:

Insert rows and columns with formatting into Excel in C# and VB.NET

Delete a Row and a Column from Excel in C# and VB.NET

To delete a row and a column, you can use the XlsWorksheet.DeleteRow(rowIndex) and XlsWorksheet.DeleteColumn(columnIndex) methods.

The following example shows how to delete a row and a column from an Excel worksheet using C# and VB.NET:

C#

using Spire.Xls;

namespace DeleteRowAndColumn
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a Workbook instance
            Workbook workbook = new Workbook();
            //Load an Excel file
            workbook.LoadFromFile("Sample.xlsx");

            //Get the first worksheet 
            Worksheet sheet = workbook.Worksheets[0];
            //Delete the 9th row
            sheet.DeleteRow(9);
            //Delete the 3rd column
            sheet.DeleteColumn(3);

            //Save the result file
            workbook.SaveToFile("DeleteRowAndColumn.xlsx", ExcelVersion.Version2016);
        }
    }
}

VB.NET

Imports Spire.Xls

Namespace DeleteRowAndColumn
    Friend Class Program
        Private Shared Sub Main(ByVal args As String())
            'Create a Workbook instance
            Dim workbook As Workbook = New Workbook()
            'Load an Excel file
            workbook.LoadFromFile("Sample.xlsx")

            'Get the first worksheet 
            Dim sheet As Worksheet = workbook.Worksheets(0)
            'Delete the 9th row
            sheet.DeleteRow(9)
            'Delete the 3rd column
            sheet.DeleteColumn(3)

            'Save the result file
            workbook.SaveToFile("DeleteRowAndColumn.xlsx", ExcelVersion.Version2016)
        End Sub
    End Class
End Namespace

Output:

Delete row and column from Excel in C# and VB.NET

Delete Multiple Rows and Columns from Excel in C# and VB.NET

To delete multiple rows and columns at once, you can use the XlsWorksheet.DeleteRow(rowIndex, rowCount) and XlsWorksheet.DeleteColumn(columnIndex, columnCount) methods.

The following code example shows how to delete multiple rows and columns from an Excel worksheet using C# and VB.NET:

C#

using Spire.Xls;

namespace DeleteMultipleRowsAndColumns
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a Workbook instance
            Workbook workbook = new Workbook();
            //Load an Excel file
            workbook.LoadFromFile(@"Sample.xlsx");

            //Get the first worksheet 
            Worksheet sheet = workbook.Worksheets[0];
            //Delete 3 rows from the worksheet starting from the 7th row
            sheet.DeleteRow(7, 3);
            //Delete 3 columns from the worksheet starting from the 3rd column
            sheet.DeleteColumn(3, 3);

            //Save the result file
            workbook.SaveToFile("DeleteMultipleRowsAndColumns.xlsx", ExcelVersion.Version2016);
        }
    }
}

VB.NET

Imports Spire.Xls

Namespace DeleteMultipleRowsAndColumns
    Friend Class Program
        Private Shared Sub Main(ByVal args As String())
            'Create a Workbook instance
            Dim workbook As Workbook = New Workbook()
            'Load an Excel file
            workbook.LoadFromFile("Sample.xlsx")

            'Get the first worksheet 
            Dim sheet As Worksheet = workbook.Worksheets(0)
            'Delete 3 rows from the worksheet starting from the 7th row
            sheet.DeleteRow(7, 3)
            'Delete 3 columns from the worksheet starting from the 3rd column
            sheet.DeleteColumn(3, 3)

            'Save the result file
            workbook.SaveToFile("DeleteMultipleRowsAndColumns.xlsx", ExcelVersion.Version2016)
        End Sub
    End Class
End Namespace

Output:

Delete multiple rows and columns from Excel in C# and VB.NET

See More

Product Page | Documentation | Examples | Forum |

Indent Paragraphs in Word Documents using Java

Indentation is a type of paragraph formatting. In Microsoft Word, there are four paragraph indentation options, they are: left line indentation, right line indentation, first line indentation and Hanging indentation. In this article, I will demonstrate how to set paragraph indentations in Word documents in Java using Free Spire.Doc for Java library.

Add Dependencies

If you are using maven, you can install the jar of Free Spire.Doc for Java into your project by adding the following code to your project’s pom.xml file.

<repositories>    
    <repository>    
        <id>com.e-iceblue</id>    
        <name>e-iceblue</name>    
        <url>http://repo.e-iceblue.com/nexus/content/groups/public/</url>    
    </repository>    
</repositories>    
<dependencies>    
    <dependency>    
        <groupId> e-iceblue </groupId>    
        <artifactId>spire.doc.free</artifactId>    
        <version>5.2.0</version>    
    </dependency>    
</dependencies>

If you are not using maven, you can download Free Spire.Doc for Java from this website, unzip the package and then import the Spire.Doc.jar under the lib folder into your project as a dependency.

Indent Paragraphs in Word Documents in Java

The ParagraphFormat class is used to work with paragraph formatting. You can use Paragraph.getFormat() method to return the ParagraphFormat object of a paragraph, and then use the methods below to set indentation options for the paragraph:

Indentation OptionMethodResult
Left line indentationParagraphFormat.setLeftIndent(float value)Indents each line of a paragraph from the left margin by a specific amount.
Right line indentationParagraphFormat.setRightIndent(float value)Indents each line of a paragraph from the right margin by a specific amount.
First line indentationParagraphFormat.setFirstLineIndent(float value)Indents only the first line of a paragraph by a specific amount.
Hanging indentationParagraphFormat.setFirstLineIndent(float negativeValue)Indents all lines of a paragraph from the left margin except the first line.
Paragraph indentation methods in Free Spire.Doc

The steps below show how to indent a paragraph:

  • Create an instance of Document class.
  • Load a Word document using Document.loadFromFile() method.
  • Access the desired section using Document.getSections.get(sectionIndex) method.
  • Get the desired paragraph you want to indent using Section.getParagraphs.get(paraIndex) method.
  • Call Paragraph.getFormat() method to return the ParagraphFormat object of the paragraph.
  • Call the methods listed in above table to set indentation for the paragraph.
  • Save the result document using Document.saveToFile() method.

Now, let’s move to the code part.

import com.spire.doc.Document;
import com.spire.doc.FileFormat;
import com.spire.doc.Section;
import com.spire.doc.documents.Paragraph;
import com.spire.doc.formatting.ParagraphFormat;

public class IndentParagraph {
    public static void main(String[] args) {
        //Create a Document instance
        Document document= new Document();
        //Load a Word document
        document.loadFromFile("Input.docx");

        //Get the first section
        Section section = document.getSections().get(0);

        //Get the second paragraph
        Paragraph para = section.getParagraphs().get(1);
        //Set left line indentation
        ParagraphFormat format = para.getFormat();
        format.setLeftIndent(30);

        //Get the third paragraph
        para = section.getParagraphs().get(2);
        //Set right line indentation
        format = para.getFormat();
        format.setRightIndent(30);

        //Get the fourth paragraph
        para = section.getParagraphs().get(3);
        //Set first line indentation
        format = para.getFormat();
        format.setFirstLineIndent(30);

        //Get the fifth paragraph
        para = section.getParagraphs().get(4);
        //Set hanging indentation
        format = para.getFormat();
        format.setFirstLineIndent(-30);

        //Save the result document
        document.saveToFile("SetParagraphIndents.docx", FileFormat.Docx_2013);
    }
}

Conclusion

In this article, you have seen how to indent paragraphs in Word documents in Java using Free Spire.Doc for Java library. Apart from setting paragraph indentation, you can also apply other paragraph formatting, like setting text alignments, setting paragraph spacing and line spacing and so on. You can explore more functionalities of the library by visiting the documentation.

Design a site like this with WordPress.com
Get started