C#/VB.NET: Change or AutoFit Column Widths and Row Heights in Excel

In Microsoft Excel, the row height and column width of a cell are set as 15 and 8.43 inches by default. Sometimes you may need to resize the row heights and column widths to ensure that all data in your report displays clearly. Microsoft Excel offers several ways to manipulate the row height and column width, for instance, manually changing the row height and column width to a specific value or having them adjusted automatically to fit the data. In this article, I will demonstrate how to programmatically achieve these tasks in C# and VB.NET using Free Spire.XLS for .NET library.

Installation

You can install Free Spire.XLS for .NET via NuGet by selecting Tools > NuGet Package Manager > Package Manager Console, and then executing the following command:

PM> Install-Package FreeSpire.XLS

Alternatively, you can also download the API from this website and install it, then add the DLL files under the Bin folder to your project as references.

Change the Column Width and Row Height in Excel in C# and VB.NET

The following are the steps to change the width of a column and the height of a row:

  • Initialize an instance of the Workbook class.
  • Load an Excel file using Workbook.LoadFromFile(string fileName) method.
  • Get the desired worksheet by its index (zero-based) through Workbook.Worksheets[sheetIndex] property.
  • Change the height of a specific row using Worksheet.SetRowHeight(int rowIndex, double height) method. Note the row index here is 1-based.
  • Change the width of a specific column using Worksheet.SetColumnWidth(int columnIndex, double width) method. Note the column index here is 1-based.
  • Save the result file using Workbook.SaveToFile(string filename, ExcelVersion version) method.

C#

using Spire.Xls;

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

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

            //Change the height of the first row
            sheet.SetRowHeight(1, 108);
            //Change the width of the first column
            sheet.SetColumnWidth(1, 26.7);

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

VB.NET

Imports Spire.Xls

Namespace ChangeColumnWidthAndRowHeight
    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("Test.xlsx")

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

            'Change the height of the first row
            sheet.SetRowHeight(1, 108)
            'Change the width of the first column
            sheet.SetColumnWidth(1, 26.7)

            'Save the result file
            workbook.SaveToFile("ChangeColumnWidthAndRowHeight.xlsx", ExcelVersion.Version2013)
        End Sub
    End Class
End Namespace
Change Column Width and Row Height in Excel using C# and VB.NET

AutoFit the Column Width and Row Height in Excel in C# and VB.NET

You can autofit the column widths and row heights of a specific cell range or the used cell range in an Excel worksheet. The steps are as follows:

  • Initialize an instance of the Workbook class.
  • Load an Excel file using Workbook.LoadFromFile(string fileName) method.
  • Get the desired worksheet by its index (zero-based) through Workbook.Worksheets[sheetIndex] property.
  • Get a specific cell range through Worksheet.Range[int row, int column, int lastRow, int lastColumn] property. Or get the used cell range through Worksheet.AllocatedRange property.
  • AutoFit the column widths and the row heights of the cell range using CellRange.AutoFitColumns() and CellRange.AutoFitRows() methods.
  • Save the result file using Workbook.SaveToFile(string filename, ExcelVersion version) method.

C#

using Spire.Xls;

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

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

            //Get a specific cell range in the worksheet
            //CellRange range = sheet.Range[1, 1, 10, 5];

            //Get the used cell range in the worksheet
            CellRange usedRange = sheet.AllocatedRange;
            
            //AutoFit the column widths and row heights of the used cell range
            usedRange.AutoFitColumns();
            usedRange.AutoFitRows();

            //Save the result file
            workbook.SaveToFile("AutoFitColumnWidthAndRowHeight.xlsx", FileFormat.Version2013);
        }
    }
}

VB.NET

Imports Spire.Xls

Namespace AutoFitColumnWidthAndRowHeight
    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("Test1.xlsx")

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

            'Get a specific cell range in the worksheet
            'CellRange range = sheet.Range[1, 1, 10, 5];

            'Get the used cell range in the worksheet
            Dim usedRange As CellRange = sheet.AllocatedRange

            'AutoFit the column widths and row heights of the used cell range
            usedRange.AutoFitColumns()
            usedRange.AutoFitRows()

            'Save the result file
            workbook.SaveToFile("AutoFitColumnWidthAndRowHeight.xlsx", FileFormat.Version2013)
        End Sub
    End Class
End Namespace
AutoFit Column Width and Row Height in Excel using C# and VB.NET

C#/VB.NET: Replace Text in PowerPoint

Replace is a handy feature in PowerPoint which allows users to quickly change all occurrences of a specific text or phrase to another. This feature is very useful if you have mistyped a word many times throughout a lengthy PowerPoint document. In this article, I will demonstrate how to programmatically replace text in PowerPoint documents using C# and VB.NET.

The following topics are covered in this article:

  • Replace Text in PowerPoint
  • Replace Text in PowerPoint using Regular Expression

Installation

To replace text in PowerPoint, this article uses Spire.Presentation for .NET, which is a multi-functional library designed for generating, editing, converting and printing PowerPoint documents within .NET applications.

You can install Spire.Presentation for .NET via NuGet by selecting Tools > NuGet Package Manager > Package Manager Console, and then executing the following command:

PM> Install-Package Spire.Presentation

Alternatively, you can also download the DLL files of Spire.Presentation for .NET from the official website, extract the package and then add the DLL files under the Bin folder to your project as references.

Replace Text in PowerPoint in C# and VB.NET

Spire.Presentation provides ISlide.ReplaceFirstText() and ISlide.ReplaceAllText() methods for replacing text on a specific PowerPoint slide. The first method replaces the first occurrence of a specific text, while the second method replaces all occurrences of a specific text.

The following steps explain how to replace all occurrences of a specific text in a PowerPoint document:

  • Initialize an instance of the Presentation class.
  • Load a PowerPoint document using Presentation.LoadFromFile() method.
  • Get the desired slide through Presentation.Slides[slideIndex] property.
  • Replace all occurrences of a specific text on the slide using ISlide.ReplaceAllText(string matchedString, string newValue, bool caseSensitive) method.
  • Save the result document using Presentation.SaveToFile() method.

C#

using Spire.Presentation;

namespace ReplaceTextInPPT
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a Presentation instance
            Presentation ppt = new Presentation();
            //Load a PowerPoint document
            ppt.LoadFromFile("Sample1.pptx");

            //Get the first slide
            ISlide slide = ppt.Slides[0];

            //Replace the first occurrence of "C#" with "VB.NET"
            //slide.ReplaceFirstText("C#", "VB.NET", false);

            //Replace all occurrences of "C#" with "VB.NET"
            slide.ReplaceAllText("C#", "VB.NET", false);

            //Save the result document
            ppt.SaveToFile("ReplaceText.pptx", FileFormat.Pptx2013);
        }
    }
}

VB.NET

Imports Spire.Presentation

Namespace ReplaceTextInPPT
    Friend Class Program
        Private Shared Sub Main(ByVal args As String())
            'Create a Presentation instance
            Dim ppt As Presentation = New Presentation()
            'Load a PowerPoint document
            ppt.LoadFromFile("Sample1.pptx")

            'Get the first slide
            Dim slide As ISlide = ppt.Slides(0)

            'Replace the first occurrence of "C#" with "VB.NET"
            'slide.ReplaceFirstText("C#", "VB.NET", false);

            'Replace all occurrences of "C#" with "VB.NET"
            slide.ReplaceAllText("C#", "VB.NET", False)

            'Save the result document
            ppt.SaveToFile("ReplaceText.pptx", FileFormat.Pptx2013)
        End Sub
    End Class
End Namespace
Replace Text in PowerPoint in C# and VB.NET

Replace Text in PowerPoint using Regular Expression in C# and VB.NET

If you want to replace text using a regular expression, you can use the IShape.ReplaceTextWithRegex() method.

Here are the detailed steps:

  •  Initialize an instance of the Presentation class.
  • Load a PowerPoint document using Presentation.LoadFromFile() method.
  • Get the desired slide through Presentation.Slides[slideIndex] property.
  • Loop through the shapes on the slide.
  • Call IShape.ReplaceTextWithRegex() method to replace specific text using a regular expression .
  • Save the result document using Presentation.SaveToFile() method.

C#

using Spire.Presentation;
using System.Text.RegularExpressions;

namespace ReplaceTextWithRegexInPPT
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a Presentation instance
            Presentation ppt = new Presentation();
            //Load a PowerPoint document
            ppt.LoadFromFile("Sample2.pptx");

            //Get the first slide
            ISlide slide = ppt.Slides[0];

            //Loop through the shapes on the slide
            foreach (IShape shape in slide.Shapes)
            {
                //Replace all text starting with # in the shapes to "Monitor"
                shape.ReplaceTextWithRegex(new Regex(@"\#\w+\b"), "Monitor");
            }

            //Save the result document
            ppt.SaveToFile("ReplaceTextWithRegex.pptx", FileFormat.Pptx2013);
        }
    }
}

VB.NET

Imports Spire.Presentation
Imports System.Text.RegularExpressions

Namespace ReplaceTextWithRegexInPPT
    Friend Class Program
        Private Shared Sub Main(ByVal args As String())
            'Create a Presentation instance
            Dim ppt As Presentation = New Presentation()
            'Load a PowerPoint document
            ppt.LoadFromFile("Sample2.pptx")

            'Get the first slide
            Dim slide As ISlide = ppt.Slides(0)

            'Loop through the shapes on the slide
            For Each shape As IShape In slide.Shapes
                'Replace all text starting with # on the slide to "Monitor"
                shape.ReplaceTextWithRegex(New Regex("\#\w+\b"), "Monitor")
            Next

            'Save the result document
            ppt.SaveToFile("ReplaceTextWithRegex.pptx", FileFormat.Pptx2013)
        End Sub
    End Class
End Namespace
Replace Text using Regular Expression in PowerPoint in C# and VB.NET

Java: Generate or Scan QR Code

About QR Code

QR Code, short for Quick Response Code, is a two-dimensional barcode that stores information as a series of pixels in a square grid. A QR code can contain a lot of data, but when it is scanned, the user can immediately access the information, which is why it is called a quick response code.

The QR code system was first invented in 1994 by a Japanese company and now it has become the most commonly used two-dimensional barcode in the world.

Java Library to Generate or Scan QR Code

To generate or scan QR code using Java, this article uses a third-party library called Spire.Barcode for Java.

If you are using maven, you can install Spire.Barcode for Java from maven by adding the following configurations to your project’s pom.xml.

<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.barcode</artifactId>    
        <version>5.1.0</version>    
    </dependency>    
</dependencies>

If you are not using maven, you can download the latest version of Spire.Barcode for Java from the official website, extract the package and then import Spire.Barcode.jar in the lib folder into your project as a dependency.

Generate QR Code using Java

The following are the main steps to generate a QR Code using Java:

  • Instantiate a BarcodeSettings object.
  • Specify the barcode type, data, and other properties such as error correction level and barcode module width using BarcodeSettings.setType()BarcodeSetting.setData()BarcodeSettings.setQRCodeECL(), and BarcodeSettings.setX() methods.
  • Instantiate a BarCodeGenerator object.
  • Generate QR code image using BarCodeGenerator.generateImage() method.
  • Save the image to a .png file using ImageIO.write() method.
import com.spire.barcode.BarCodeGenerator;
import com.spire.barcode.BarCodeType;
import com.spire.barcode.BarcodeSettings;
import com.spire.barcode.QRCodeECL;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

public class GenerateQRCode {
    public static void main(String[] args) throws IOException {
        //Apply a license key if you have one
        com.spire.license.LicenseProvider.setLicenseKey("License Key");

        //Instantiate a BarcodeSettings object
        BarcodeSettings settings = new BarcodeSettings();

        //Set barcode type
        settings.setType(BarCodeType.QR_Code);
        String data = "https://google.com";
        //Set barcode data
        settings.setData(data);
        //Set display text
        settings.setData2D(data);
        //Set text invisible
        settings.setShowText(false);
        //Set border invisible
        settings.hasBorder(false);
        //Set width for the barcode module
        settings.setX(2);
        //Set the error correction level
        settings.setQRCodeECL(QRCodeECL.M);

        //Instantiate a BarCodeGenerator object based on the specific settings
        BarCodeGenerator barCodeGenerator = new BarCodeGenerator(settings);
        //Generate QR code image
        BufferedImage bufferedImage = barCodeGenerator.generateImage();
        //save the image to a .png file
        ImageIO.write(bufferedImage,"png",new File("QR_Code.png"));
    }
}

The generated QR code image:

Generate QR Code using Java

Scan QR Code using Java

The following are the main steps to scan a QR Code using Java:

  • Scan the QR Codes within an image using BarcodeScanner.scan(String fileName, BarCodeType barcodeType) method, and save the results into a String array.
  • Loop through the array and print out the data.
import com.spire.barcode.BarCodeType;
import com.spire.barcode.BarcodeScanner;

public class ScanQRCode {
    public static void main(String[] args) throws Exception {
        //Apply a license key if you have one
        com.spire.license.LicenseProvider.setLicenseKey("License Key");
        //Scan the QR codes within an image and store the results into a String array
        String[] datas = BarcodeScanner.scan("QR_Code.png", BarCodeType.QR_Code);

        //Loop through the array
        for(String data : datas){
            //Print out the result
            System.out.print(data);
        }
    }
}

Output:

Scan QR Code using Java

Get a Free Trial License

The library will generate an evaluation watermark on the generated QR code image, if you would like to remove the watermark or to scan a QR code image, you can request a free 30 days trial license.

Besides, it also provides a free version called Free Spire.Barcode for Java, which supports generating QR code without any watermark. But note that it doesn’t include the ability to scan QR code.

C#/VB.NET: Count the Number of Pages, Words, Characters, Paragraphs and Lines in Word Documents

When writing an academic document, you might want to check the number of words in the document to make sure it meets a certain length requirement. Microsoft Word includes a built-in function to count words within a document, and it also provides the ability to count other elements like pages, characters, paragraphs and lines. In this article, I will explain how to programmatically count the number of pages, words, characters, paragraphs and lines in Word documents using C# and VB.NET.

Installation

To count the pages, words, characters, paragraphs and lines in Word documents, this article uses Spire.Doc for .NET, which is a multi-functional library designed for generating, editing, converting and printing Word documents within .NET applications.

You can install Spire.Doc for .NET via NuGet by selecting Tools > NuGet Package Manager > Package Manager Console, and then executing the following command:

PM> Install-Package Spire.Doc

Alternatively, you can also download the DLL files of Spire.Doc for .NET from the official website, extract the package and then add the DLL files under the Bin folder to your project as references.

Count the Number of Pages, Words, Characters, Paragraphs and Lines in Word Documents using C# and VB.NET

The following are the main steps to count the number of pages, words, characters, paragraphs and lines in a Word document:

  • Create an instance of Document class.
  • Load a Word document using Document.LoadFromFile() method.
  • Create an instance of StringBuilder class.
  • Use Document.BuiltinDocumentProperties.PageCount, Document.BuiltinDocumentProperties.WordCount, Document.BuiltinDocumentProperties.CharCount, Document.BuiltinDocumentProperties.CharCountWithSpace, Document.BuiltinDocumentProperties.ParagraphCount, and Document.BuiltinDocumentProperties.LinesCount properties to get the count of pages, words, characters, paragraphs and lines in the document, and append the results to the string builder.
  • Save the data in the string builder to a .txt file using File.WriteAllText() method.

C#

using Spire.Doc;
using System.IO;
using System.Text;

namespace CountWordsInWord
{
    internal class Program
    {
        static void Main(string[] args)
        {
            //Create an instance of Document class
            Document doc = new Document();
            //Load a Word document
            doc.LoadFromFile("Sample.docx");

            //Create an instance of StringBuilder class
            StringBuilder sb = new StringBuilder();

            //Count the number of pages, words, characters, paragraphs and lines in the document, and append the results to the string builder
            sb.AppendLine("Pages: " + doc.BuiltinDocumentProperties.PageCount);
            sb.AppendLine("Words: " + doc.BuiltinDocumentProperties.WordCount);
            sb.AppendLine("Characters with No Spaces: " + doc.BuiltinDocumentProperties.CharCount);
            sb.AppendLine("Characters with Spaces: " + doc.BuiltinDocumentProperties.CharCountWithSpace);          
            sb.AppendLine("Paragraphs: " + doc.BuiltinDocumentProperties.ParagraphCount);
            sb.AppendLine("Lines: " + doc.BuiltinDocumentProperties.LinesCount);


            //Save the data in the string builder to a .txt file
            File.WriteAllText("WordCount.txt", sb.ToString());
        }
    }
}

VB.NET

Imports Spire.Doc
Imports System.IO
Imports System.Text

Namespace CountWordsInWord
    Friend Class Program
        Private Shared Sub Main(ByVal args As String())
            'Create an instance of Document class
            Dim doc As Document = New Document()
            'Load a Word document
            doc.LoadFromFile("Sample.docx")

            'Create an instance of StringBuilder class
            Dim sb As StringBuilder = New StringBuilder()

            'Count the number of pages, words, characters, paragraphs and lines in the document, and append the results to the string builder
            sb.AppendLine("Pages: " & doc.BuiltinDocumentProperties.PageCount)
            sb.AppendLine("Words: " & doc.BuiltinDocumentProperties.WordCount)
            sb.AppendLine("Characters with No Spaces: " & doc.BuiltinDocumentProperties.CharCount)
            sb.AppendLine("Characters with Spaces: " & doc.BuiltinDocumentProperties.CharCountWithSpace)
            sb.AppendLine("Paragraphs: " & doc.BuiltinDocumentProperties.ParagraphCount)
            sb.AppendLine("Lines: " & doc.BuiltinDocumentProperties.LinesCount)

            'Save the data in the string builder to a .txt file
            Call File.WriteAllText("WordCount.txt", sb.ToString())
        End Sub
    End Class
End Namespace
Count the Number of Pages, Words, Characters, Paragraphs and Lines in Word Documents using C# and VB.NET

Java – Read or Remove Document Properties (Metadata) in Word

If you are going to share a document with others, you may want to review the document properties and remove those that contain your personal information. In this article, I will explain how to read or remove document properties in a Word document in Java using Free Spire.Doc for Java.

The following topics are covered in this article:

  • Read Standard Document Properties in Word
  • Read Custom Document Properties in Word
  • Remove Standard Document Properties from Word
  • Remove Custom Document Properties from Word

Add Dependencies

Method 1: If you are using maven, you can easily import the JAR file of Free Spire.Doc for Java into 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 Free Spire.Doc for Java 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.

Read Standard Document Properties in Word using Java

The following are the main steps to read the standard document properties in a Word document:

  • Create an instance of Document class.
  • Load the Word document using Document.loadFromFile() method.
  • Create an instance of StringBuilder class.
  • Get the standard document properties collection of the document using Document.getBuiltinDocumentProperties() method.
  • Get the specific standard document properties such as title, subject, author from the collection using BuiltinDocumentProperties.getTitle(), BuiltinDocumentProperties.getSubject(), BuiltinDocumentProperties.getAuthor()methods, and append the results to the string builder.
  • Write the data in the string builder into a .txt file.
import com.spire.doc.BuiltinDocumentProperties;
import com.spire.doc.Document;

import java.io.FileWriter;
import java.io.IOException;

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

        //Create a StringBuilder instance
        StringBuilder sb = new StringBuilder();

        //Get the standard document properties in the Word document and save them into the string builder
        BuiltinDocumentProperties standardProperties = document.getBuiltinDocumentProperties();
        sb.append("Title: " + standardProperties.getTitle() + "\n");
        sb.append("Subject: " + standardProperties.getSubject() + "\n");
        sb.append("Author: " + standardProperties.getAuthor() + "\n");
        sb.append("Manager: " + standardProperties.getManager() + "\n");
        sb.append("Company: " + standardProperties.getCompany() + "\n");
        sb.append("Category: " + standardProperties.getCategory() + "\n");
        sb.append("KeyWords: " + standardProperties.getKeywords() + "\n");
        sb.append("Comments: " + standardProperties.getComments() + "\n");

        //Write the data in the string builder into a .txt document
        FileWriter writer;
        try {
            writer = new FileWriter("StandardProperties.txt");
            writer.write(sb.toString());
            writer.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
Read Standard Document Properties in Word using Java

Read Custom Document Properties in Word using Java

The following are the main steps to read the custom document properties in a Word document:

  • Create an instance of Document class.
  • Load the Word document using Document.loadFromFile() method.
  • Create an instance of StringBuilder class.
  • Get the custom document properties collection of the document using Document.getCustomDocumentProperties() method.
  • Loop through the collection.
  • Within the loop, get the name of each custom document property using CustomDocumentProperties.get(propertyIndex).getName() method, and append the result to the string builder.
  • Get the value of each custom document property using CustomDocumentProperties.get(propertyIndex).getValue() method, and append the result to the string builder.
  • Write the data in the string builder into a .txt file.
import com.spire.doc.CustomDocumentProperties;
import com.spire.doc.Document;

import java.io.FileWriter;
import java.io.IOException;

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

        //Create a StringBuilder instance
        StringBuilder sb = new StringBuilder();

        //Get the custom document properties collection of the Word document        
        CustomDocumentProperties customProperties = document.getCustomDocumentProperties();

        //Loop through the collection, get the name and value of each custom property and save the results into the string builder
        for(int i = 0; i < customProperties.getCount(); i++)
        {
            sb.append("Name: " + customProperties.get(i).getName() + "\n");
            sb.append("Value: " + customProperties.get(i).getValue() + "\n");
        }

        //Write the data in the string builder into a .txt document
        FileWriter writer;
        try {
            writer = new FileWriter("CustomProperties.txt");
            writer.write(sb.toString());
            writer.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
Read Custom Document Properties in Word using Java

Remove Standard Document Properties from Word using Java

The following are the steps to remove the standard document properties from a Word document:

  • Create an instance of Document class.
  • Load a Word document using Document.loadFromFile() method.
  • Get the standard document properties collection of the document using Document.getBuiltinDocumentProperties() method.
  • Set the value of specific standard document properties such as title, subject and author to null using the BuiltinDocumentProperties.getTitle(), BuiltinDocumentProperties.getSubject(), BuiltinDocumentProperties.getAuthor() methods.
  • Save the result document using Document.saveToFile() method.
import com.spire.doc.BuiltinDocumentProperties;
import com.spire.doc.Document;
import com.spire.doc.FileFormat;

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

        //Remove the standard document properties from the Word document by setting their values to null
        BuiltinDocumentProperties standardProperties = document.getBuiltinDocumentProperties();
        standardProperties.setTitle(" ");
        standardProperties.setSubject(" ");
        standardProperties.setAuthor(" ");
        standardProperties.setCompany(" ");
        standardProperties.setManager(" ");
        standardProperties.setCategory(" ");
        standardProperties.setKeywords(" ");
        standardProperties.setComments(" ");

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

Remove Custom Document Properties from Word using Java

The following are the steps to remove custom document properties from a Word document:

  • Create an instance of Document class.
  • Load the Word document using Document.loadFromFile() method.
  • Create an instance of StringBuilder class.
  • Get the custom document properties collection of the document using Document.getCustomDocumentProperties() method.
  • Loop through the collection, remove each custom document properties by its name using CustomDocumentProperties.remove(String name) method.
  • Save the result document.
import com.spire.doc.CustomDocumentProperties;
import com.spire.doc.Document;
import com.spire.doc.FileFormat;

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

        //Get the standard document properties collection of the Word document
        CustomDocumentProperties customProperties = document.getCustomDocumentProperties();

        //Loop through the collection
        for(int i = 0; i < customProperties.getCount(); i++)
        {
            //Remove each custom properties
            customProperties.remove(customProperties.get(i).getName());
        }

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

See Also

Java: Add Document Properties to Word Documents

C#/VB.NET Convert HTML or HTML String to PDF

Occasionally, you may need to convert HTML to PDF. For example, when you want to read the content of a web page offline anywhere and anytime. In this article, I will demonstrate how to convert HTML or HTML string to PDF in C# and VB.NET using Spire.PDF for .NET.

The following topics are covered in this article:

  • Convert HTML Web Page to PDF
  • Convert HTML String to PDF

Installation

You can install Spire.PDF for .NET via NuGet by selecting Tools > NuGet Package Manager > Package Manager Console, and then executing the following command:

PM> Install-Package Spire.PDF

Alternatively, you can also download the API from this website and install it, then add the DLL files under the Bin folder to your project as references.

Download QT Plugin

Spire.PDF supports converting HTML to PDF with QT Web engine. Before using the code, you need to download the appropriate QT plugin that works for your operating system from one of the links below:

Then, extract the package and you will find the “plugins” folder, remember the path of this folder which will then be used when converting HTML to PDF. In this article, the path is D:\\Download\\plugins-windows-x64\\plugins.

Convert HTML Web Page to PDF in C# and VB.NET

The following are the main steps to convert a html webpage to PDF:

  • Specify the HTML web page URL.
  • Specify the path of the converted PDF file.
  • Specify the QT plugin path, and assign it as the value of  the HtmlConverter.PluginPath property.
  • Convert the HTML webpage URL to PDF using HtmlConverter.Convert(string url, string fileName, bool enableJavaScript, int timeout, SizeF pageSize, PdfMargins margins) method.

C#

using Spire.Pdf.Graphics;
using Spire.Pdf.HtmlConverter.Qt;
using System.Drawing;

namespace ConvertHtmlToPdf
{
    internal class Program
    {
        static void Main(string[] args)
        {
            //Specify the HTML URL
            string url = "https://medium.com/";

            //Specify the path of the converted PDF file
            string fileName = "HtmlToPdf.pdf";

            //Specify the plugin path
            string pluginPath = "D:\\Download\\plugins-windows-x64\\plugins";

            //Set the plugin path
            HtmlConverter.PluginPath = pluginPath;

            //Convert the HTML URL to PDF
            HtmlConverter.Convert(url, fileName, true, 100000, new Size(1080, 1000), new PdfMargins(0));
        }
    }
}

VB.NET

Imports Spire.Pdf.Graphics
Imports Spire.Pdf.HtmlConverter.Qt
Imports System.Drawing

Namespace ConvertHtmlToPdf
    Friend Class Program
        Private Shared Sub Main(ByVal args As String())
            'Specify the HTML URL
            Dim url = "https://medium.com/"

            'Specify the path of the converted PDF file
            Dim fileName = "HtmlToPdf.pdf"

            'Specify the plugin path
            Dim pluginPath = "D:\Download\plugins-windows-x64\plugins"

            'Set the plugin path
            HtmlConverter.PluginPath = pluginPath

            'Convert the HTML URL to PDF
            HtmlConverter.Convert(url, fileName, True, 100000, New Size(1080, 1000), New PdfMargins(0))
        End Sub
    End Class
End Namespace
Convert HTML URL to PDF using C# and VB.NET

Convert HTML String to PDF in C# and VB.NET

The following are the steps to convert an HTML string to PDF:

  • Specify the HTML string.
  • Specify the path of the converted PDF file.
  • Specify the plugin path, and assign it as the value of the HtmlConverter.PluginPath property.
  • Convert the HTML string to PDF using HtmlConverter.Convert(string htmlString, string fileName, bool enableJavaScript, int timeout, SizeF pageSize, PdfMargins margins, Spire.Pdf.HtmlConverter.LoadHtmlType htmlType) method.

Note: Only inline or internal CSS styles are supported during the HTML to PDF conversion.

C#

using Spire.Pdf.Graphics;
using Spire.Pdf.HtmlConverter.Qt;
using System.Drawing;
using System.IO;

namespace ConvertHtmlToPdf
{
    internal class Program
    {
        static void Main(string[] args)
        {
            string htmlString = @"<!DOCTYPE html>
                <html>
                <head>
                <style>
                body {background-color: powderblue;}
                h1   {color: blue;}
                p    {color: red;}
                </style>
                </head>
                <body>
                <h1>This is a heading</h1>
                <p>This is a paragraph.</p>
                </body>
                </html>"; 

            //Specify the output file path
            string fileName = "HtmlStringToPdf.pdf";

            //Specify the plugin path
            string pluginPath = "D:\\Download\\plugins-windows-x64\\plugins";

            //Set plugin path
            HtmlConverter.PluginPath = pluginPath;

            //Convert HTML string to PDF
            HtmlConverter.Convert(htmlString, fileName, true, 100000, new Size(1080, 1000), new PdfMargins(0), Spire.Pdf.HtmlConverter.LoadHtmlType.SourceCode);
        }
    }
}

VB.NET

Imports Spire.Pdf.Graphics
Imports Spire.Pdf.HtmlConverter.Qt
Imports System.Drawing

Namespace ConvertHtmlToPdf
    Friend Class Program
        Private Shared Sub Main(ByVal args As String())
            Dim htmlString = "<!DOCTYPE html>
                <html>
                <head>
                <style>
                body {background-color: powderblue;}
                h1   {color: blue;}
                p    {color: red;}
                </style>
                </head>
                <body>
                <h1>This is a heading</h1>
                <p>This is a paragraph.</p>
                </body>
                </html>"

            'Specify the output file path
            Dim fileName = "HtmlStringToPdf.pdf"

            'Specify the plugin path
            Dim pluginPath = "D:\Download\plugins-windows-x64\plugins"

            'Set plugin path
            HtmlConverter.PluginPath = pluginPath

            'Convert HTML string to PDF
            HtmlConverter.Convert(htmlString, fileName, True, 100000, New Size(1080, 1000), New PdfMargins(0), Spire.Pdf.HtmlConverter.LoadHtmlType.SourceCode)
        End Sub
    End Class
End Namespace
Convert HTML String to PDF using C# and VB.NET

Java: Add Document Properties to Word Documents

Document properties are details about a file that describe or identify it. In Microsoft Word, you can set standard document properties (like title, author name, keywords and subject) as well as define custom document properties for your file. In this article, I will demonstrate how to programmatically add document properties to Word Documents in Java using Free Spire.Doc for Java library.

  • Add Standard Document Properties to Word
  • Add Custom Document Properties to Word

Add Dependencies

Method 1: If you are using maven, you can easily import the JAR file of Free Spire.Doc for Java into 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 Free Spire.Doc for Java 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.

Add Standard Document Properties to Word in Java

The standard document properties, also known as built-in document properties, is a fixed set of document properties predefined by Microsoft. You can set or change the value of the standard document properties, but you cannot change their names.

The following are the steps to add standard document properties to a Word document using Java:

  • Create an instance of Document class.
  • Load a Word document using Document.loadFromFile() method.
  • Get the standard document properties of the document using Document.getBuiltinDocumentProperties() method.
  • Set the value for specific standard document properties like title, subject and author etc. using the methods setTitle(), setSubject() and setAuthor() etc. provided by BuiltinDocumentProperties class.
  • Save the result document using Document.saveToFile() method.
import com.spire.doc.BuiltinDocumentProperties;
import com.spire.doc.Document;
import com.spire.doc.FileFormat;

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

        //Add standard document properties to the Word document
        BuiltinDocumentProperties standardProperties = document.getBuiltinDocumentProperties();
        standardProperties.setTitle("Add Document Properties");
        standardProperties.setSubject("Java Example");
        standardProperties.setAuthor("Alice");
        standardProperties.setCompany("X Company");
        standardProperties.setManager("Jackson");
        standardProperties.setCategory("Document Manipulation");
        standardProperties.setKeywords("Java, Word, Document Properties");
        standardProperties.setComments("Thanks for your reading");

        //Save the result document
        document.saveToFile("AddStandardProperties.docx", FileFormat.Docx_2013);
    }
}
Add Standard Document Properties to Word using Java

Add Custom Document Properties to Word

The custom document properties are a set of properties that defined by a document author or user. You can define the name as well as the value of the custom document properties.

The following are the steps to add custom document properties to a Word document using Java:

  • Create an instance of Document class.
  • Load a Word document using Document.loadFromFile() method.
  • Get the custom document properties of the document using Document.getCustomDocumentProperties() method.
  • Set the name and value for custom document properties using CustomDocumentProperties.add(String name, String value) method.
  • Save the result document using Document.saveToFile() method.
import com.spire.doc.CustomDocumentProperties;
import com.spire.doc.Document;
import com.spire.doc.FileFormat;

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

        //Add custom document properties to the Word document
        CustomDocumentProperties customProperties = document.getCustomDocumentProperties();
        customProperties.add("Tracking ID", "10031");
        customProperties.add("Checked By", "Wilson");

        //Save the result document
        document.saveToFile("AddCustomProperties.docx", FileFormat.Docx_2013);
    }
}
Add Custom Document Properties to Word using Java
Design a site like this with WordPress.com
Get started