When working with a Word document, we can encrypt the document to ensure its confidentiality. As an alternative, we can also choose to hide specific text content to prevent others from seeing them. This article will demonstrate how to programmatically hide a specific paragraph in a Word document using Java codes.
DEPENDENCY
In order to realize the function
of hiding a specific paragraph in Word, we’ll need to use a free third-party
library called Free Spire.Doc for Java.
First of all, we can get the library from the link, and then add Spire.Doc.jar
as a dependency in Java program. Or directly import it by adding the following
Maven configuration in the 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>3.9.0</version>
</dependency>
</dependencies>
USING THE CODE
Free Spire.Doc for Java provides TextRange.getCharacterFormat().setHidden(boolean value) method to hide a specific paragraph in a Word document. The following are detailed steps.
l Create
a Document instance.
l Load
a sample Word document using Document.loadFromFile()
method.
l Get
a specific section of the Word document using Document.getSections().get() method.
l Get
a specific paragraph of the section using Section.getParagraphs().get()
method.
l Loop
through the child objects of the paragraph, and convert each child object as a
text range if it is plain text. Then hide the text range using TextRange.getCharacterFormat().setHidden(boolean
value) method.
l Save the document to another file using Document.saveToFile() method.
import com.spire.doc.*;import com.spire.doc.documents.*;
import com.spire.doc.fields.*;
public class HideParagraph {
public static void main(String[] args) {
//Create a Document instance
Document document = new Document();
//Load a sample Word document
document.loadFromFile("C:\\Users\\Test1\\Desktop\\sample.docx");
//Get a specific section of Word
Section sec = document.getSections().get(0);
//Get a specific paragraph of the section
Paragraph para = sec.getParagraphs().get(1);
//Loop through the child objects
for (Object docObj : para.getChildObjects()) {
DocumentObject obj = (DocumentObject)docObj;
//Determine if a child object is an instance of TextRange
if ((obj instanceof TextRange)) {
TextRange range = ((TextRange)(obj));
//Hide the text range
range.getCharacterFormat().setHidden(true);
}
}
//Save the document to another file
document.saveToFile("output/hideParagraph.docx", FileFormat.Docx_2013);
}
}
No comments:
Post a Comment