News Category

Java: Remove Hyperlinks in Word Documents

2022-05-20 03:42:14 Written by  support iceblue
Rate this item
(3 votes)

Hyperlinks usually appear on texts. By clicking on a hyperlink, we can access a website, a document, an email address, or other elements. Some Word documents, especially those that are generated from web content, may contain irritating hyperlinks, such as advertisements. This article shows you how to programmatically remove one hyperlink or all hyperlinks in a Word document using Spire.Doc for Java.

Install Spire.Doc for Java

First, you're required to add the Spire.Doc.jar file as a dependency in your Java program. The JAR file can be downloaded from this link. If you use 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</artifactId>
        <version>12.4.1</version>
    </dependency>
</dependencies>
    

Remove a Specified Hyperlink in a Word Document

The detailed steps to remove a specified hyperlink in a Word file are as follows:

  • Create a Document object and load a Word document from disk using Document.loadFromFile() method.
  • Find all the hyperlinks using custom method FindAllHyperlinks().
  • Flatten the first hyperlink using custom method FlattenHyperlinks().
  • Save the document using Document.saveToFile() method.
  • Java
import com.spire.doc.*;
import com.spire.doc.documents.DocumentObjectType;
import com.spire.doc.documents.Paragraph;
import com.spire.doc.documents.UnderlineStyle;
import com.spire.doc.fields.Field;
import com.spire.doc.fields.TextRange;

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

public class removeHyperlink {
    public static void main(String[] args) {
        //Create a Document object and load a Word document from disk
        String input = "D:/testp/test.docx";
        Document doc = new Document();
        doc.loadFromFile(input);

        //Find all hyperlinks
        ArrayList hyperlinks = FindAllHyperlinks(doc);

        //Flatten the first hyperlink
        FlattenHyperlinks(hyperlinks.get(0));

        //Save the document to file
        String output = "D:/javaOutput/RemoveHyperlinks.docx";
        doc.saveToFile(output, FileFormat.Docx);
    }

    //Create a method FindAllHyperlinks() to get all the hyperlinks from the sample document
    private static ArrayList FindAllHyperlinks(Document document)
    {
        ArrayList hyperlinks = new ArrayList();

        //Iterate through the items in the sections to find all hyperlinks
        for (Section section : (Iterable)document.getSections())
        {
            for (DocumentObject object : (Iterable)section.getBody().getChildObjects())
            {
                if (object.getDocumentObjectType().equals(DocumentObjectType.Paragraph))
                {
                    Paragraph paragraph = (Paragraph) object;
                    for (DocumentObject cObject : (Iterable)paragraph.getChildObjects())
                    {
                        if (cObject.getDocumentObjectType().equals(DocumentObjectType.Field))
                        {
                            Field field = (Field) cObject;
                            if (field.getType().equals(FieldType.Field_Hyperlink))
                            {
                                hyperlinks.add(field);
                            }
                        }
                    }
                }
            }
        }
        return hyperlinks;
    }

    //Create a method FlattenHyperlinks() to flatten the hyperlink field
    public 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);
            }
        }
    }

    //Create a method FormatFieldResultText() to 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));
                }
            }
        }
    }

    //Create a method FormatText() to change the color of the text to black and remove the underline
    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);
    }
}

Java: Remove Hyperlinks in Word Documents

Remove All the Hyperlinks in a Word Document

The detailed steps to remove all the hyperlinks in a Word file are as follows:

  • Create a Document object and load a Word document from disk using Document.loadFromFile() method.
  • Find all the hyperlinks using custom method FindAllHyperlinks().
  • Loop through the hyperlinks, and invoke the custom method FlattenHyperlinks() to flatten the specific hyperlink.
  • Save the document using Document.saveToFile() method.
  • Java
import com.spire.doc.*;
import com.spire.doc.documents.DocumentObjectType;
import com.spire.doc.documents.Paragraph;
import com.spire.doc.documents.UnderlineStyle;
import com.spire.doc.fields.Field;
import com.spire.doc.fields.TextRange;

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

public class removeHyperlink {
    public static void main(String[] args) {
        //Create a Document object and load a Word document from disk
        String input = "D:/testp/test.docx";
        Document doc = new Document();
        doc.loadFromFile(input);

        //Find all the hyperlinks
        ArrayList hyperlinks = FindAllHyperlinks(doc);

        //Loop through the hyperlinks, and flatten the specific hyperlink.
        for (int i = hyperlinks.size() -1; i >= 0; i--)
        {
            FlattenHyperlinks(hyperlinks.get(i));
        }

        //Save the document to file
        String output = "D:/javaOutput/RemoveHyperlinks.docx";
        doc.saveToFile(output, FileFormat.Docx);
    }

    //Create a method FindAllHyperlinks() to get all the hyperlinks from the sample document
    private static ArrayList FindAllHyperlinks(Document document)
    {
        ArrayList hyperlinks = new ArrayList();

        //Iterate through the items in the sections to find all hyperlinks
        for (Section section : (Iterable)document.getSections())
        {
            for (DocumentObject object : (Iterable)section.getBody().getChildObjects())
            {
                if (object.getDocumentObjectType().equals(DocumentObjectType.Paragraph))
                {
                    Paragraph paragraph = (Paragraph) object;
                    for (DocumentObject cObject : (Iterable)paragraph.getChildObjects())
                    {
                        if (cObject.getDocumentObjectType().equals(DocumentObjectType.Field))
                        {
                            Field field = (Field) cObject;
                            if (field.getType().equals(FieldType.Field_Hyperlink))
                            {
                                hyperlinks.add(field);
                            }
                        }
                    }
                }
            }
        }
        return hyperlinks;
    }

    //Create a method FlattenHyperlinks() to flatten the hyperlink field
    public 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);
            }
        }
    }

    //Create a method FormatFieldResultText() to format the texts
    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));
                }
            }
        }
    }

    //Create a method FormatText() to change the color of the text to black and remove the underline
    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);
    }
}

Java: Remove Hyperlinks in Word Documents

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

Additional Info

  • tutorial_title:
Last modified on Monday, 19 June 2023 01:53