Generate PowerPoint Document from Template in Java

Generating a PowerPoint document from scratch is painful and time consuming, but it would be much easier if you use a template with pre-designed formats. In this article, I will introduce how to generate PowerPoint document from existing template in Java using Free Spire.Presentation for Java library.

Add Dependencies

There are two ways to include Free Spire.Presentation for Java in your Java project.

For maven projects, add the following dependencies 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.presentation.free</artifactId>    
        <version>3.9.0</version>    
    </dependency>    
</dependencies>

For non-maven projects, download Free Spire.Presentation for Java pack, extract the zip file, then add Free Spire.Presentation.jar in the lib folder into your project as a dependency.

The following is the input PowerPoint template which contains placeholder text:

In the following example, I will show you how to generate a PowerPoint document from the template by replacing the placeholder text.

import com.spire.presentation.*;

import java.util.HashMap;
import java.util.Map;

public class CreatePptFromTemplate {
    public static void main(String []args) throws Exception {
        //create a Presentation instance
        Presentation presentation = new Presentation();

        //load the template PowerPoint document
        presentation.loadFromFile("C:\\Users\\Administrator\\Desktop\\Sample.pptx");

        //get the first slide
        ISlide slide= presentation.getSlides().get(0);

        //create a map of values for the template
        Map<String, String> map = new HashMap<>();
        map.put("firstName","Alex");
        map.put("lastName","Anderson");
        map.put("gender","Male");
        map.put("mobilePhone","+0044 85430000");
        map.put("email","alex.anderson@myemail.com");
        map.put("homeAddress","123 High Street");
        map.put("dateOfBirth","6th June, 1986");
        map.put("education","University of South Florida, September 2013 - June 2017");
        map.put("employmentHistory","Automation Inc. November 2013 - Present");

        //replace the placeholder text in the template
        for (Map.Entry<String, String> entry : map.entrySet()) {
            slide.replaceAllText("${" + entry.getKey() + "}", entry.getValue(), true);
        }

        //save the result document
        presentation.saveToFile("ReplaceText.pptx", FileFormat.PPTX_2013);
    }
}

The following is the output PowerPoint document:

Conclusion

From this example, you can see it’s very easy to deal with PowerPoint objects with Free Spire.Presentation for Java library. The library provides rich capabilities to work with PowerPoint documents, you can explore more about it by visiting the documentation.

Thanks for reading and happy coding!

Easily Convert Color PDF to Grayscale in C# and VB.NET

Converting PDF to grayscale allows people to print the PDF in a cheaper mode without consuming colored ink. In this article, I will illustrate how to convert a color PDF to grayscale easily with only 2 lines of code in C# and VB.NET using a free library – Free Spire.PDF for .NET.

Add Reference

You can either download Free Spire.PDF DLLs from this website or install Free Spire.PDF using NuGet Package Manager through the following steps:

  • In your project’s Solution Explorer, right-click the project or “Dependencies” and select “Manage NuGet Packages”.
  • Click “Browse” tab and search Free Spire.PDF.
  • Install Free Spire.PDF.

Input PDF

Converted PDF

Convert PDF to Grayscale in C# and VB.NET

The PdfGrayConverter.ToGrayPdf(string) method is used for converting PDF to grayscale.

C# Code

The following example shows how to convert a PDF to grayscale in C# code.

using Spire.Pdf.Conversion;

namespace ConvertPdfToGrayscale
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a PdfGrayConverter instance and load a PDF file
            PdfGrayConverter converter = new PdfGrayConverter(@"Sample.pdf");
            //Convert the PDF to grayscale
            converter.ToGrayPdf("Grayscale.pdf");
            converter.Dispose();
        }
    }
}

VB.NET Code

The following example shows how to convert a PDF to grayscale in VB.NET code.

Imports Spire.Pdf.Conversion

Namespace ConvertPdfToGrayscale
    Class Program
        Private Shared Sub Main(ByVal args As String())
            Dim converter As PdfGrayConverter = New PdfGrayConverter("Sample.pdf")
            converter.ToGrayPdf("Grayscale.pdf")
            converter.Dispose()
        End Sub
    End Class
End Namespace

That’s all. I hope it’s helpful to you. Happy coding!

Read and Write Excel Files without MS Office in C#

Read or write Excel files are common tasks for developers in office document development. In this article, I am going to share a simple approach to read and write Excel files in C# by using Free Spire.XLS for .NET API.

Microsoft Office is not needed

Free Spire.XLS for .NET is a free and independent API for creating, reading, writing, converting and printing Excel files in both XLS (Excel 97-2003) and XLSX (Excel 2007 and above) formats. It has no dependency on Microsoft Office, in other words, you can use it to read and write Excel files without installing Microsoft Office in your system.

Get Free Spire.XLS for .NET

You can either download Free Spire.XLS DLLs from this website or install Free Spire.XLS using NuGet Package Manager through the following steps:

  • In your project’s Solution Explorer, right-click the project or “Dependencies” and select “Manage NuGet Packages”.
  • Click “Browse” tab and search Free Spire.XLS.
  • Install Free Spire.XLS.

Write Excel Files

You can generate an Excel file by writing data cell-by-cell or by importing data from other data sources such as DataTable, DataView, DataColumn, Array, Array List etc.

Write data cell-by-cell

using Spire.Xls;
using System;

namespace WriteExcelFiles
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a Workbook instance
            Workbook workbook = new Workbook();
            //Add a worksheet
            Worksheet sheet = workbook.Worksheets[0];

            //Add text to the worksheet
            sheet.Range["A1"].Text = "ID";
            sheet.Range["B1"].Text = "Name";
            sheet.Range["C1"].Text = "Birthday";
            sheet.Range["D1"].Text = "Age";

            //Add number to the worksheet
            sheet.Range["A2"].NumberValue = 1;
            sheet.Range["A3"].NumberValue = 2;
            sheet.Range["A4"].NumberValue = 3;

            //Add text to the worksheet
            sheet.Range["B2"].Text = "John";
            sheet.Range["B3"].Text = "Glen";
            sheet.Range["B4"].Text = "Amy";

            //Add date time to the worksheet
            sheet.Range["C2"].DateTimeValue = new DateTime(1989, 9, 12);
            sheet.Range["C3"].DateTimeValue = new DateTime(1976, 3, 20);
            sheet.Range["C4"].DateTimeValue = new DateTime(1996, 10, 29);

            //Add formula to the worksheet
            sheet.Range["D2"].Formula = "=INT(YEARFRAC(C2, TODAY()))";
            sheet.Range["D3"].Formula = "=INT(YEARFRAC(C3, TODAY()))";
            sheet.Range["D4"].Formula = "=INT(YEARFRAC(C4, TODAY()))";


            //Set column width
            for (int col = 1; col <= sheet.LastColumn; col++)
            {
                sheet.Columns[col].ColumnWidth = 12;
            }
            
            //Save the result file
            workbook.SaveToFile("WriteExcel.xlsx", FileFormat.Version2013);
        }       
    }
}

Write data from DataTable

using Spire.Xls;
using System.Data;

namespace ReadExcelFiles
{
    class Program
    {
        static void Main(string[] args)
        {
            //Load an Excel file
            Workbook workbook = new Workbook();
            workbook.LoadFromFile("WriteExcel.xlsx");
            //Get the first worksheet
            Worksheet sheet = workbook.Worksheets[0];
            //Import data from DataTable to Excel
            sheet.InsertDataTable(GetDataTable(), true, 1, 1);

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

        private static DataTable GetDataTable()
        {
            DataTable country = new DataTable();
            country.Columns.Add("Name");
            country.Columns.Add("Capital");
            country.Columns.Add("Continent");
            country.Columns.Add("Area");
            country.Columns.Add("Population");

            country.Rows.Add("Argentina", "Buenos Aires", "South America", "2777815", "32300003");
            country.Rows.Add("Bolivia", "La Paz", "South America", "1098575", "7300000");
            country.Rows.Add("Brazil", "Brasilia", "South America", "8511196", "150400000");
            country.Rows.Add("Canada", "Ottawa", "North America", "9976147", "26500000");
            country.Rows.Add("Chile", "Santiago", "South America", "756943", "13200000");

            return country;
        }
    }
}

Read Excel files

You can also read Excel data by cell-to-cell iteration or read Excel data to a DataTable as shown in the following examples.

Read Excel by cell-to-cell iteration      

using Spire.Xls;
using System;

namespace ReadExcelFiles
{
    class Program
    {
        static void Main(string[] args)
        {
            //Load an Excel file
            Workbook workbook = new Workbook();
            workbook.LoadFromFile("sample.xlsx");
            //Get the first worksheet
            Worksheet sheet = workbook.Worksheets[0];

            int maxRow = sheet.LastRow;
            int maxColumn = sheet.LastColumn;

            //Read data by cell-to-cell iteration
            for (int row = 1; row <= maxRow; row++)
            {
                for (int col = 1; col <= maxColumn; col++)
                {
                    Console.Write(sheet[row, col].Value);
                    Console.Write("\t\t");
                }
                Console.Write("\n");
            }

            Console.ReadKey();
        }
    }
}

Read Excel to DataTable

using Spire.Xls;
using System;
using System.Data;

namespace ReadExcelFiles
{
    class Program
    {
        static void Main(string[] args)
        {
            //Load an Excel file
            Workbook workbook = new Workbook();
            workbook.LoadFromFile("sample.xlsx");
            //Get the first worksheet
            Worksheet sheet = workbook.Worksheets[0];

            //Export to DataTable
            DataTable dt = sheet.ExportDataTable();
        }
    }
}

Java Convert Word to PDF and Keep Headings as Bookmarks

A well-structured Word document often contains headings, when converting such Word document to PDF, you may want to preserve the headings in the Word document as bookmarks in the result PDF document.

In this article, I will show you how to convert a Word document to PDF and keep headings as bookmarks programmatically in Java using Spire.Doc for Java library.

Add Dependencies

There are two ways to include Spire.Doc for Java in your Java project.

For maven projects, add the following dependencies 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 </artifactId>    
        <version>4.7.0</version>    
    </dependency>    
</dependencies>

For non-maven projects, download Spire.Doc for Java pack from here: Download- Spire.Doc for Java, extract the zip file, then add Spire.Doc.jar in the lib folder into your project as a dependency.

Sample Code

import com.spire.doc.Document;
import com.spire.doc.ToPdfParameterList;

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

        //Create a ToPdfParameterList instance
        ToPdfParameterList pdfParameterList = new ToPdfParameterList();
        //Specify whether to preserve headings as bookmarks when converting Word to PDF
        pdfParameterList.setCreateWordBookmarks(true);
        pdfParameterList.createWordBookmarksUsingHeadings(true);

        //Save the Word document to PDF
        document.saveToFile("Output.pdf", pdfParameterList);
    }
}

Word Document

Converted PDF

Add Comment to Specific Text and Get Marked Text of Specific Comment in Word in Java

A comment is a note or annotation that an author or reviewer can add to a document. In this article, I will illustrate how to add comment to specific text and get the marked text of a specific comment in a Word document using Java.

Add Dependencies

Free Spire.Doc for Java library are used to achieve the functionality. There are two ways to include Free Spire.Doc for Java in your Java project:

For maven projects, add the following dependencies 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>3.9.0</version>    
    </dependency>    
</dependencies>

The latest version of Free Spire.Doc for Java is 3.9.0 (at the time of writing this article).

For non-maven projects, download Free Spire.Doc for Java pack from here: Download- Free Spire.Doc for Java, extract the zip file, then add Spire.Doc.jar in the lib folder into your project as a dependency.

Add comment to specific text

import com.spire.doc.*;
import com.spire.doc.documents.*;
import com.spire.doc.fields.*;

public class AddCommentToSpecificText {
    public static void main(String[] args){
        //Create word document
        Document document = new Document();
        //Load the document from disk
        document.loadFromFile("Template.docx");

        //Call insertComments method to add comment to the specific text "Dragon Boat Festival"
        insertComments(document, "Dragon Boat Festival");

        //Save the document
        document.saveToFile("addCommentToSpecificText.docx", FileFormat.Docx_2013);
    }
    private static void insertComments(Document doc, String stringToComment) {
        //Find the string
        TextSelection find = doc.findString(stringToComment, false, true);

        //Create comment start mark and comment end mark
        CommentMark commentMarkStart = new CommentMark(doc);
        commentMarkStart.setType(CommentMarkType.Comment_Start);
        CommentMark commentMarkEnd = new CommentMark(doc);
        commentMarkEnd.setType(CommentMarkType.Comment_End);

        //Add content for comment
        Comment comment = new Comment(doc);
        comment.getBody().addParagraph().setText("Also known as Duanwu festival");
        //Set the author of comment
        comment.getFormat().setAuthor("Sierra");

        //Get the textRange
        TextRange range = find.getAsOneRange();

        //Get its paragraph
        Paragraph para = range.getOwnerParagraph();
        //Get the index of textRange
        int index = para.getChildObjects().indexOf(range);
        //Add comment to the paragraph
        para.getChildObjects().add(comment);
        //Insert the comment start mark and comment end mark to the paragraph
        para.getChildObjects().insert(index, commentMarkStart);
        para.getChildObjects().insert(index + 2, commentMarkEnd);
    }
}

Output:

Get the marked text of a specific comment

import com.spire.doc.Document;
import com.spire.doc.documents.CommentMark;
import com.spire.doc.documents.Paragraph;
import com.spire.doc.fields.Comment;
import com.spire.doc.fields.TextRange;


public class GetMarkedTextOfSpecificComment {
    public static void main(String[] args){
        //Load the Word document
        Document doc = new Document();
        doc.loadFromFile("addCommentToSpecificText.docx");

        //Get the first comment in the document
        Comment comment = doc.getComments().get(0);
        
        //get the start mark and end mark of the comment
        Paragraph para = comment.getOwnerParagraph();
        CommentMark start = comment.getCommentMarkStart();
        CommentMark end = comment.getCommentMarkEnd();
        int indexOfStart = para.getChildObjects().indexOf(start);
        int indexOfEnd = para.getChildObjects().indexOf(end);

        String markedText = "";
        //Get the marked text between the comment start mark and comment end mark
        for (int i = indexOfStart + 1; i < indexOfEnd; i++) {
            if (para.getChildObjects().get(i) instanceof TextRange) {
                TextRange range = (TextRange) para.getChildObjects().get(i);
                markedText += range.getText();
            }
        }
        
        //Print out the marked text
        System.out.println(markedText);
    }
}

Output:

Read or Extract Form Field Values from PDF in Java

Form fields are data fields that let you collect data from the filled forms. There are many types of form fields available in PDF, such as text fields, list boxes, radio buttons, combo boxes and check boxes. In this article, I will introduce how to read values of these PDF form fields programmatically in Java.

Add Dependencies

In order to read form fields, I used Free Spire.PDF for Java library. There are two ways to include Free Spire.PDF for Java in your Java project:

For maven projects:

Add the following dependency 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.pdf.free</artifactId>    
        <version>4.4.1</version>    
    </dependency>    
</dependencies>

For non-maven projects:

Download Free Spire.PDF for Java pack from here: Download- Free Spire.PDF for Java, extract the zip file, then add Spire.Pdf.jar in the lib folder into your project as a dependency.

Read Form Field values

You can either read all of the form fields or read a particular form field as shown in the following examples.

The input PDF:

Example 1. Read values of all form fields

import com.spire.pdf.PdfDocument;
import com.spire.pdf.fields.PdfField;
import com.spire.pdf.widget.*;

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

public class ReadFormFields {
    public static void main(String []args){
        //Load PDF document
        PdfDocument pdf = new PdfDocument();
        pdf.loadFromFile("FormFields.pdf");

        //Get form fields
        PdfFormWidget formWidget = (PdfFormWidget)pdf.getForm();

        StringBuilder sb = new StringBuilder();
        //Loop through the form field widget collection and extract the value of each field
        for (int i = 0; i < formWidget.getFieldsWidget().getCount(); i++)
        {
            PdfField field = (PdfField)formWidget.getFieldsWidget().getList().get(i);
            if (field instanceof PdfTextBoxFieldWidget)
            {
                PdfTextBoxFieldWidget textBoxField = (PdfTextBoxFieldWidget)field ;
                //Get text of textbox
                String text = textBoxField.getText();
                sb.append("The text in textbox is: " + text + "\r\n");
            }

            if (field instanceof PdfListBoxWidgetFieldWidget)
            {
                PdfListBoxWidgetFieldWidget listBoxField = (PdfListBoxWidgetFieldWidget)field;
                sb.append("Listbox items are: \r\n");
                //Get values of listbox
                PdfListWidgetItemCollection items = listBoxField.getValues();

                for (PdfListWidgetItem item : (Iterable<PdfListWidgetItem>) items)
                {
                    sb.append(item.getValue() + "\r\n");
                }
                //Get selected value
                String selectedValue = listBoxField.getSelectedValue();
                sb.append("The selected value in the listbox is: " + selectedValue + "\r\n");
            }

            if (field instanceof PdfComboBoxWidgetFieldWidget)
            {
                PdfComboBoxWidgetFieldWidget comBoxField = (PdfComboBoxWidgetFieldWidget)field ;
                sb.append("comBoxField items are: \r\n");
                //Get values of comboBox
                PdfListWidgetItemCollection items = comBoxField.getValues();

                for (PdfListWidgetItem item : (Iterable<PdfListWidgetItem>) items)
                {
                    sb.append(item.getValue() + "\r\n");
                }
                //Get selected value
                String selectedValue = comBoxField.getSelectedValue();
                sb.append("The selected value in the comBoxField is: " + selectedValue + "\r\n");
            }

            if (field instanceof PdfRadioButtonListFieldWidget)
            {
                PdfRadioButtonListFieldWidget radioBtnField = (PdfRadioButtonListFieldWidget)field;
                //Get value of radio button
                String value = radioBtnField.getValue();

                sb.append("The text in radioButtonField is: " + value + "\r\n");
            }

            if (field instanceof PdfCheckBoxWidgetFieldWidget)
            {
                PdfCheckBoxWidgetFieldWidget checkBoxField = (PdfCheckBoxWidgetFieldWidget)field;
                //Get the checked state of the checkbox
                boolean state = checkBoxField.getChecked();
                sb.append("Is the checkBox checked? " + state + "\r\n");
            }
        }

        try {
            //Write text into a .txt file
            FileWriter writer = new FileWriter("GetAllValues.txt");
            writer.write(sb.toString());
            writer.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }

        pdf.close();
    }
}

Output:

Example 2. Read values of a particular form field

import com.spire.pdf.PdfDocument;
import com.spire.pdf.widget.PdfFormWidget;
import com.spire.pdf.widget.PdfTextBoxFieldWidget;

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

public class ReadParticularFormField {
    public static void main(String[] args){
        //Load PDF document
        PdfDocument pdf = new PdfDocument();
        pdf.loadFromFile("FormFields.pdf");

        //Get form fields
        PdfFormWidget formWidget = (PdfFormWidget)pdf.getForm();

        //Get the textbox by index or by name
        PdfTextBoxFieldWidget textbox = ( PdfTextBoxFieldWidget)formWidget.getFieldsWidget().get(0);
        //PdfTextBoxFieldWidget textbox = ( PdfTextBoxFieldWidget)formWidget.getFieldsWidget().get("Text1");

        //Get the text of the textbox
        String text = textbox.getText();

        try {
            //Write text into a .txt file
            FileWriter writer = new FileWriter("GetSpecificFieldValue.txt");
            writer.write(text);
            writer.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }

        pdf.close();
    }
}

Output:

Remove Multiple Hyperlinks from Word Document in Java

When you get a document that contains multiple hyperlinks that you don’t want to jump to, you may want to remove the hyperlinks from the document. In this article, I will introduce how to remove all the hyperlinks in a Word document at once but keep the text programmatically in Java.

Add Dependencies

In order to remove hyperlinks from a Word document, I used Free Spire.Doc for Java library. There are two ways to include Free Spire.Doc for Java in your Java project:

For maven projects:

Add the following dependencies 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>3.9.0</version>    
    </dependency>    
</dependencies>

The latest version of Free Spire.Doc for Java is 3.9.0 (at the time of writing this article).

For non-maven projects:

Download Free Spire.Doc for Java pack from here: Download- Free Spire.Doc for Java, extract the zip file, then add Spire.Doc.jar in the lib folder into your project as a dependency.

Using the code

The following example shows how to remove all the hyperlinks in a Word document.

import com.spire.doc.*;
import com.spire.doc.documents.*;
import com.spire.doc.fields.*;

import java.awt.*;
import java.util.ArrayList;

public class RemoveHyperlinks {

    private static ArrayList<Field> hyperlinks = new ArrayList<>();

    public static void main(String []args){
        //Load document
        Document doc = new Document();
        doc.loadFromFile("Input.docx");

        //Get all hyperlinks
        for(int i = 0;i<doc.getSections().getCount();i++)
        {
            Section section = doc.getSections().get(i);
            //Get the hyperlinks in section body
            iterateTextBody(section.getBody());
            //Get the hyperlinks in header or footer
            HeaderFooter header = section.getHeadersFooters().getHeader();
            HeaderFooter footer = section.getHeadersFooters().getFooter();
            iterateTextBody(header);
            iterateTextBody(footer);
        }

        //Remove all the hyperlinks
        for (int i = hyperlinks.size() - 1; i >= 0; i--)
        {
            flattenHyperlinks(hyperlinks.get(i));
        }

        hyperlinks.clear();

        //Save the document
        doc.saveToFile("RemoveHyperlinks.docx", FileFormat.Docx);
    }

    //Get hyperlinks from Body object
    private static void iterateTextBody(Body body)
    {
        for(int i = 0;i< body.getChildObjects().getCount();i++)
        {
             DocumentObject obj = body.getChildObjects().get(i);
             if(obj.getDocumentObjectType().equals(DocumentObjectType.Paragraph))
             {
                 iterateParagraph((Paragraph)obj);
             }
             if(obj.getDocumentObjectType().equals(DocumentObjectType.Table))
             {
                 iterateTable((Table)obj);
             }
        }
    }

    private static void iterateParagraph(Paragraph paragraph)
    {
        for (DocumentObject cObject : (Iterable<DocumentObject>)paragraph.getChildObjects())
        {
            if (cObject.getDocumentObjectType().equals(DocumentObjectType.Field))
            {
                Field field = (Field)cObject;
                if (field.getType().equals( FieldType.Field_Hyperlink))
                {
                    hyperlinks.add(field);
                }
            }
        }
    }

    private static void iterateTable(Table table)
    {
        for(TableRow row:(Iterable<TableRow>)table.getRows()){
            for(TableCell cell : (Iterable<TableCell>)row.getCells()){
                for(Paragraph para : (Iterable<Paragraph>)cell.getParagraphs()){
                    iterateParagraph(para);
                }
            }
        }
    }

    //Flatten the hyperlink fields
    private static void flattenHyperlinks(Field field)
    {
        int ownerParaIndex = field.getOwnerParagraph().ownerTextBody().getChildObjects().indexOf(field.getOwnerParagraph());
        int fieldIndex = field.getOwnerParagraph().getChildObjects().indexOf(field);
        Paragraph sepOwnerPara = field.getSeparator().getOwnerParagraph();
        int sepOwnerParaIndex = field.getSeparator().getOwnerParagraph().ownerTextBody().getChildObjects().indexOf(field.getSeparator().getOwnerParagraph());
        int sepIndex = field.getSeparator().getOwnerParagraph().getChildObjects().indexOf(field.getSeparator());
        int endIndex = field.getEnd().getOwnerParagraph().getChildObjects().indexOf(field.getEnd());
        int endOwnerParaIndex = field.getEnd().getOwnerParagraph().ownerTextBody().getChildObjects().indexOf(field.getEnd().getOwnerParagraph());

        formatFieldResultText(field.getSeparator().getOwnerParagraph().ownerTextBody(), sepOwnerParaIndex, endOwnerParaIndex, sepIndex, endIndex);

        field.getEnd().getOwnerParagraph().getChildObjects().removeAt(endIndex);

        for (int i = sepOwnerParaIndex; i >= ownerParaIndex; i--)
        {
            if (i == sepOwnerParaIndex && i == ownerParaIndex)
            {
                for (int j = sepIndex; j >= fieldIndex; j--)
                {
                    field.getOwnerParagraph().getChildObjects().removeAt(j);
                }
            }
            else if (i == ownerParaIndex)
            {
                for (int j = field.getOwnerParagraph().getChildObjects().getCount()-1; j >= fieldIndex; j--)
                {
                    field.getOwnerParagraph().getChildObjects().removeAt(j);
                }

            }
            else if (i == sepOwnerParaIndex)
            {
                for (int j = sepIndex; j >= 0; j--)
                {
                    sepOwnerPara.getChildObjects().removeAt(j);
                }
            }
            else
            {
                field.getOwnerParagraph().ownerTextBody().getChildObjects().removeAt(i);
            }
        }
    }

    //Remove the font color and underline format of the hyperlinks
    private static void formatFieldResultText(Body ownerBody, int sepOwnerParaIndex, int endOwnerParaIndex, int sepIndex, int endIndex)
    {
        for (int i = sepOwnerParaIndex; i <= endOwnerParaIndex; i++)
        {
            Paragraph para = (Paragraph)ownerBody.getChildObjects().get(i);
            if (i == sepOwnerParaIndex && i == endOwnerParaIndex)
            {
                for (int j = sepIndex + 1; j < endIndex; j++)
                {
                    formatText((TextRange)para.getChildObjects().get(j));
                }
            }
            else if (i == sepOwnerParaIndex)
            {
                for (int j = sepIndex + 1; j < para.getChildObjects().getCount(); j++)
                {
                    formatText((TextRange)para.getChildObjects().get(j));
                }
            }
            else if (i == endOwnerParaIndex)
            {
                for (int j = 0; j < endIndex; j++)
                {
                    formatText((TextRange)para.getChildObjects().get(j));
                }
            }
            else
            {
                for (int j = 0; j < para.getChildObjects().getCount(); j++)
                {
                    formatText((TextRange)para.getChildObjects().get(j));
                }
            }
        }
    }
    private static void formatText(TextRange tr)
    {
        //Set the text color to black
        tr.getCharacterFormat().setTextColor(Color.black);
        //Set the text underline style to none
        tr.getCharacterFormat().setUnderlineStyle(UnderlineStyle.None);
    }
}

The following is the screenshot of the input Word document:

The following is the output Word document:

Add Vertical Text to Word in Java

You can add vertical text in Microsoft Word by adding a textbox, typing your text in the textbox and then setting the direction of the text. Another way to add vertical text is to type it into a table cell. In this article, I am going to show you how to achieve the same programmatically in Java.

Add Dependencies

In order to add vertical text to Word, I use Free Spire.Doc for Java library. There are two ways to include Free Spire.Doc for Java in your Java project:

For maven projects:

Add the following dependency 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>3.9.0</version>    
    </dependency>    
</dependencies>

The latest version of Free Spire.Doc for Java is 3.9.0 (at the time of writing this article).

For non-maven projects:

Download Free Spire.Doc for Java pack from here: Download- Free Spire.Doc for Java, extract the zip file, then add Spire.Doc.jar in the lib folder into your project as a dependency.

Add vertical text in textbox

import com.spire.doc.Document;
import com.spire.doc.FileFormat;
import com.spire.doc.Section;
import com.spire.doc.ShapeVerticalAlignment;
import com.spire.doc.documents.*;
import com.spire.doc.fields.TextBox;
import com.spire.doc.fields.TextRange;

import java.awt.*;
import java.io.IOException;

public class AddVerticalTextToTextBox {
    public static void main(String []args) throws IOException {
        //Create a Document instance
        Document document = new Document();
        //Add a section
        Section section = document.addSection();
        //Add a paragraph to the section
        Paragraph paragraph = section.addParagraph();

        //Add a texbox to the paragraph
        TextBox textBox = paragraph.appendTextBox(50, 100);

        //Fix the position of the textbox
        textBox.getFormat().setNoLine(true);
        textBox.getFormat().setHorizontalOrigin(HorizontalOrigin.Page);
        textBox.getFormat().setHorizontalPosition(250);
        textBox.getFormat().setVerticalOrigin(VerticalOrigin.Page);
        textBox.getFormat().setVerticalPosition(50);
        
        textBox.getFormat().setTextAnchor(ShapeVerticalAlignment.Center);
        //Set text direction
        textBox.getFormat().setLayoutFlowAlt(TextDirection.Left_To_Right);

        //Add text to the textbox
        Paragraph textboxPara = textBox.getBody().addParagraph();
        TextRange textRange = textboxPara.appendText("This is sample text.");
        textRange.getCharacterFormat().setFontName("Calibri");
        textRange.getCharacterFormat().setFontSize(11);
        textRange.getCharacterFormat().setTextColor(Color.black);

        //Save the document
        document.saveToFile("AddVerticalTextToTextbox.docx", FileFormat.Docx_2013);
        document.dispose();
    }
}

Output:

Add Vertical Text To Textbox

Add vertical text in table cell

import com.spire.doc.*;
import com.spire.doc.documents.RowAlignment;
import com.spire.doc.documents.TextDirection;
import com.spire.doc.fields.TextRange;

import java.awt.*;
import java.io.IOException;

public class AddVerticalTextToTableCell {
    public static void main(String []args) throws IOException {
        //Create a Document instance
        Document document = new Document();
        //Add a section
        Section section = document.addSection();
        //Set text direction for all text in a section
        //section.setTextDirection( TextDirection.Left_To_Right);
        
        //Add a table
        Table table = section.addTable();
        table.resetCells(1, 1);
        table.getTableFormat().setHorizontalAlignment(RowAlignment.Center);
        TableCell cell = table.getRows().get(0).getCells().get(0);
        table.getRows().get(0).setHeight(150);
        table.getRows().get(0).getCells().get(0).setWidth(50);
        //Set text direction
        cell.getCellFormat().setTextDirection(TextDirection.Left_To_Right);
        //Add text to table cell
        TextRange textRange = cell.addParagraph().appendText("This is sample text.");
        textRange.getCharacterFormat().setFontName("Calibri");
        textRange.getCharacterFormat().setFontSize(11);
        textRange.getCharacterFormat().setTextColor(Color.black);
        
        //Save the document
        document.saveToFile("AddVerticalTextToTableCell.docx", FileFormat.Docx_2013);
        document.dispose();
    }
}

Output:

Add Vertical Text To Table Cell
Design a site like this with WordPress.com
Get started