In the process of manipulating Word documents, it is sometimes necessary to keep some important information from others. For this reason, we can hide them to ensure confidentiality. This article shows how to hide a specific paragraph in a Word document using Spire.Doc for Java.
Install Spire.Doc for Java
First of all, 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.11.0</version> </dependency> </dependencies>
Hide a Specific Paragraph in Word
Spire.Doc for Java supports hiding a specific paragraph in Word by using TextRange.getCharacterFormat().setHidden(boolean value) method. Here are detailed steps to follow.
- Create a Document instance.
- Load a sample Word document using Document.loadFromFile() method.
- Get a specific section of the Word document using Document.getSections().get() method.
- Get a specific paragraph of the section using Section.getParagraphs().get() method.
- 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.
- Save the document to another file using Document.saveToFile() method.
- Java
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); } }
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.