Java (447)
Adding gutters on Word document pages can assist users in better page layout and design, especially when preparing documents for printing or creating books that require gutter. Gutter can indicate the gutter position on the page, helping users to design with appropriate blank areas to avoid text or images being cut off. By setting gutter, users can have better control over the appearance and layout of the document, ensuring that the final output meets the expected gutter requirements, enhancing the professionalism and readability of the document. This article shows how to add gutters on Word document pages by programming using Spire.Doc for Java.
- Add a Gutter at the Top of a Word Document Page in Java
- Add a Gutter at the Left of a Word Document Page in 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.6</version> </dependency> </dependencies>
Add a Gutter at the Top of a Word Document Page in Java
In a Word document, you can set section.getPageSetup().isTopGutter(true) to place the gutter at the top of the page. By default, the gutter area is displayed as blank without any content. This example also includes steps on how to add content, such as the dash symbol, to the gutter area to customize content around the gutter. Here are the detailed steps:
- Create a Document object.
- Load a document using the Document.loadFromFile() method.
- Iterate through all sections of the document using a for loop and Document.getSections().
- Set Section.getPageSetup().isTopGutter(true) to display the gutter at the top of the page.
- Use Section.getPageSetup().setGutter() to set the width of the gutter.
- Call the custom addTopGutterContent() method to add content to the gutter area.
- Save the document using the Document.saveToFile() method.
- Java
import com.spire.doc.*; import com.spire.doc.documents.*; import com.spire.doc.fields.*; import com.spire.doc.formatting.CharacterFormat; import java.awt.*; public class AddTopGutter { public static void main(String[] args) { // Create a document object Document document = new Document(); // Load the document document.loadFromFile("Sample1.docx"); // Iterate through all sections of the document for (int i = 0; i < document.getSections().getCount(); i++) { // Get the current section Section section = document.getSections().get(i); // Set whether to add a gutter at the top of the page to true section.getPageSetup().isTopGutter(true); // Set the width of the gutter to 100f section.getPageSetup().setGutter(100f); // Call the method to add content to the top gutter addTopGutterContent(section); } // Save the modified document to a file document.saveToFile("AddGutterOnTop.docx", FileFormat.Docx_2016); // Release document resources document.dispose(); } // Method to add content to the top gutter static void addTopGutterContent(Section section) { // Get the header of the section HeaderFooter header = section.getHeadersFooters().getHeader(); // Set the width of the text box to the width of the page float width = (float) section.getPageSetup().getPageSize().getWidth(); // Set the height of the text box to 40 float height = 40; // Add a text box to the header TextBox textBox = header.addParagraph().appendTextBox(width, height); // Set the text box without borders textBox.getFormat().setNoLine(true); // Set the vertical origin of the text box to the top margin area textBox.setVerticalOrigin(VerticalOrigin.Top_Margin_Area); // Set the vertical position of the text box textBox.setVerticalPosition(140); // Set the horizontal alignment of the text box to left textBox.setHorizontalAlignment(ShapeHorizontalAlignment.Left); // Set the horizontal origin of the text box to the left margin area textBox.setHorizontalOrigin(HorizontalOrigin.Left_Margin_Area); // Set the text anchor to the bottom textBox.getFormat().setTextAnchor(ShapeVerticalAlignment.Bottom); // Set the text wrapping style to in front of text textBox.getFormat().setTextWrappingStyle(TextWrappingStyle.In_Front_Of_Text); // Set the text wrapping type to both sides textBox.getFormat().setTextWrappingType(TextWrappingType.Both); // Create a paragraph object Paragraph paragraph = new Paragraph(section.getDocument()); // Set the paragraph alignment to center paragraph.getFormat().setHorizontalAlignment(HorizontalAlignment.Center); // Create a font object Font font = new Font("SimSun", Font.PLAIN, 8); Graphics graphics = new java.awt.image.BufferedImage(1, 1, java.awt.image.BufferedImage.TYPE_INT_ARGB).getGraphics(); graphics.setFont(font); FontMetrics fontMetrics = graphics.getFontMetrics(); String text1 = " - "; int textWidth1 = fontMetrics.stringWidth(text1); int count = (int) (textBox.getWidth() / textWidth1); StringBuilder stringBuilder = new StringBuilder(); for (int i = 1; i < count; i++) { stringBuilder.append(text1); } // Create a character format object CharacterFormat characterFormat = new CharacterFormat(section.getDocument()); characterFormat.setFontName(font.getFontName()); characterFormat.setFontSize(font.getSize()); TextRange textRange = paragraph.appendText(stringBuilder.toString()); textRange.applyCharacterFormat(characterFormat); // Add the paragraph to the text box textBox.getChildObjects().add(paragraph); } }
Add a Gutter at the Left of a Word Document Page in Java
To set the gutter on the left side of the page, the key is to set Section.getPageSetup().isTopGutter(false). Here are the detailed steps:
- Create a Document object.
- Load a document using the Document.loadFromFile() method.
- Iterate through all sections of the document using a for loop and Document.getSections().
- Set Section.getPageSetup().isTopGutter(false) to display the gutter on the left side of the page.
- Use Section.getPageSetup().setGutter() to set the width of the gutter.
- Call the custom addLeftGutterContent() method to add content to the gutter area.
- Save the document using the Document.saveToFile() method.
- Java
import com.spire.doc.*; import com.spire.doc.documents.*; import com.spire.doc.fields.*; import com.spire.doc.formatting.CharacterFormat; import java.awt.*; public class AddLeftGutter { public static void main(String[] args) { // Create a document object Document document = new Document(); // Load the document document.loadFromFile("Sample1.docx"); // Iterate through all sections of the document for (int i = 0; i < document.getSections().getCount(); i++) { // Get the current section Section section = document.getSections().get(i); // Set whether to add a gutter at the top of the page to false, it will be added to the left side of the page section.getPageSetup().isTopGutter(false); // Set the width of the gutter to 100f section.getPageSetup().setGutter(100f); // Call the method to add content to the left gutter AddLeftGutterContent (section); } // Save the modified document to a file document.saveToFile("AddGutterOnLeft.docx", FileFormat.Docx_2016); // Release document resources document.dispose(); } // Method to add content to the left gutter static void AddLeftGutterContent(Section section) { // Get the header of the section HeaderFooter header = section.getHeadersFooters().getHeader(); // Set the width of the text box to 40 float width = 40; // Get the page height float height = (float) section.getPageSetup().getPageSize().getHeight(); // Add a text box to the header TextBox textBox = header.addParagraph().appendTextBox(width, height); // Set the text box without borders textBox.getFormat().setNoLine(true); // Set the text direction in the text box from right to left textBox.getFormat().setLayoutFlowAlt(TextDirection.Right_To_Left); // Set the horizontal starting position of the text box textBox.setHorizontalOrigin(HorizontalOrigin.Left_Margin_Area); // Set the horizontal position of the text box textBox.setHorizontalPosition(140); // Set the vertical alignment of the text box to the top textBox.setVerticalAlignment(ShapeVerticalAlignment.Top); // Set the vertical origin of the text box to the top margin area textBox.setVerticalOrigin(VerticalOrigin.Top_Margin_Area); // Set the text anchor to the top textBox.getFormat().setTextAnchor(ShapeVerticalAlignment.Top); // Set the text wrapping style to in front of text textBox.getFormat().setTextWrappingStyle(TextWrappingStyle.In_Front_Of_Text); // Set the text wrapping type to both sides textBox.getFormat().setTextWrappingType(TextWrappingType.Both); // Create a paragraph object Paragraph paragraph = new Paragraph(section.getDocument()); // Set the paragraph alignment to center paragraph.getFormat().setHorizontalAlignment(HorizontalAlignment.Center); // Create a font object, SimSun, size 8 Font font = new Font("SimSun", Font.PLAIN, 8); Graphics graphics = new java.awt.image.BufferedImage(1, 1, java.awt.image.BufferedImage.TYPE_INT_ARGB).getGraphics(); graphics.setFont(font); FontMetrics fontMetrics = graphics.getFontMetrics(); String text1 = " - "; int textWidth1 = fontMetrics.stringWidth(text1); int count = (int) (textBox.getHeight() / textWidth1); StringBuilder stringBuilder = new StringBuilder(); for (int i = 1; i < count ; i++) { stringBuilder.append(text1); } // Create a character format object CharacterFormat characterFormat = new CharacterFormat(section.getDocument()); characterFormat.setFontName(font.getFontName()); characterFormat.setFontSize(font.getSize()); TextRange textRange = paragraph.appendText(stringBuilder.toString()); textRange.applyCharacterFormat(characterFormat); // Add the paragraph to the text box textBox.getChildObjects().add(paragraph); } }
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.
The Freeze Panes feature in Excel allows users to lock specific rows and columns while scrolling, ensuring that critical information remains visible regardless of the dataset's size. However, there are instances where unfreezing panes becomes necessary. Unfreezing rows and columns grants users the freedom to navigate large datasets seamlessly, facilitating comprehensive data analysis, editing, and formatting. the contents of frozen panes are often important information, and being able to obtain the range of frozen panes can facilitate easier access to this content. This article demonstrates how to use Spire.XLS for Java to unfreeze panes and obtain frozen rows and columns in Excel worksheets with Java code.
- Unfreeze Panes in Excel Worksheets with Java
- Obtain Frozen Rows and Columns in Excel Worksheets with Java
Install Spire.XLS for Java
First of all, you're required to add the Spire.Xls.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.xls</artifactId> <version>14.4.1</version> </dependency> </dependencies>
Unfreeze Panes in Excel Worksheets with Java
With Spire.XLS for Java, developers get a worksheet using Workbook.getWorksheets().get() method and unfreeze the panes using Worksheet.RemovePanes() method. The detailed steps for unfreezing panes in an Excel worksheet are as follows:
- Create an object of Workbook class.
- Load an Excel workbook using Workbook.loadFromFile() method.
- Get a worksheet from the workbook using Workbook.getWorksheets().get() method.
- Unfreeze panes in the worksheet using Worksheet.removePanes() method.
- Save the workbook using Workbook.saveToFile() method.
- Java
import com.spire.xls.Workbook; import com.spire.xls.Worksheet; public class UnfreezePanes { public static void main(String[] args) { // Create an object of Workbook class Workbook wb = new Workbook(); // Load an Excel workbook wb.loadFromFile("Sample.xlsx"); // Get the first worksheet Worksheet sheet = wb.getWorksheets().get(0); // Unfreeze the panes sheet.removePanes(); // Save the workbook wb.saveToFile("output/UnfreezePanes.xlsx"); wb.dispose(); } }
Obtain Frozen Rows and Columns in Excel Worksheets with Java
Spire.XLS for Java provides the Worksheet.getFreezePanes() method to get the row and column indexes of the frozen panes, which allows developers to conveniently extract, remove, or format the content of the frozen panes. The parameters obtained are in the format of an int list: [int rowIndex, int columnIndex]. For example, [1, 0] indicates that the first row is frozen.
The detailed steps for obtaining the row and column parameters of the frozen panes are as follows:
- Create an object of Workbook class.
- Load an Excel workbook using Workbook.loadFromFile() method.
- Get the first worksheet using Workbook.getWorksheets().get() method.
- Get the indexes of the frozen rows and columns using Worksheet.getFreezePanes() method.
- Output the result.
- Java
import com.spire.xls.Workbook; import com.spire.xls.Worksheet; public class GetFrozenCellRange { public static void main(String[] args) { // Create an object of Document clas Workbook wb = new Workbook(); // Load an Excel file wb.loadFromFile("Sample.xlsx"); // Get the first worksheet Worksheet ws = wb.getWorksheets().get(0); // Get the indexes of the frozen rows and columns int[] index = ws.getFreezePanes(); // Output the result System.out.println("Frozen Rows: " + index[0] + "\r\nFrozen Columns: " + index[1]); wb.dispose(); } }
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.
Extracting content from Word documents plays a crucial role in both work and study. Extracting one page of content helps in quickly browsing and summarizing key points, while extracting content from one section aids in in-depth study of specific topics or sections. Extracting the entire document allows you to have a comprehensive understanding of the document content, facilitating deep analysis and comprehensive comprehension. This article will introduce how to use Spire.Doc for Java to read a page, a section, and the entire content of a Word document in a Java project.
- Read a Page from a Word Document in Java
- Read a Section from a Word Document in Java
- Read the Entire Content from a Word Document in 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.6</version> </dependency> </dependencies>
Read a Page from a Word Document in Java
Using the FixedLayoutDocument class and FixedLayoutPage class makes it easy to extract content from a specified page. To facilitate viewing the extracted content, the following example code saves the extracted content to a new Word document. The detailed steps are as follows:
- Create a Document object.
- Load a Word document using the Document.loadFromFile() method.
- Create a FixedLayoutDocument object.
- Obtain a FixedLayoutPage object for a page in the document.
- Use the FixedLayoutPage.getSection() method to get the section where the page is located.
- Get the index position of the first paragraph on the page within the section.
- Get the index position of the last paragraph on the page within the section.
- Create another Document object.
- Add a new section using Document.addSection().
- Clone the properties of the original section to the new section using Section.cloneSectionPropertiesTo(newSection) method.
- Copy the content of the page from the original document to the new document.
- Save the resulting document using the Document.saveToFile() method.
- Java
import com.spire.doc.*; import com.spire.doc.pages.*; import com.spire.doc.documents.*; public class ReadOnePage { public static void main(String[] args) { // Create a new document object Document document = new Document(); // Load document content from the specified file document.loadFromFile("Sample.docx"); // Create a fixed layout document object FixedLayoutDocument layoutDoc = new FixedLayoutDocument(document); // Get the first page FixedLayoutPage page = layoutDoc.getPages().get(0); // Get the section where the page is located Section section = page.getSection(); // Get the first paragraph of the page Paragraph paragraphStart = page.getColumns().get(0).getLines().getFirst().getParagraph(); int startIndex = 0; if (paragraphStart != null) { // Get the index of the paragraph in the section startIndex = section.getBody().getChildObjects().indexOf(paragraphStart); } // Get the last paragraph of the page Paragraph paragraphEnd = page.getColumns().get(0).getLines().getLast().getParagraph(); int endIndex = 0; if (paragraphEnd != null) { // Get the index of the paragraph in the section endIndex = section.getBody().getChildObjects().indexOf(paragraphEnd); } // Create a new document object Document newdoc = new Document(); // Add a new section Section newSection = newdoc.addSection(); // Clone the properties of the original section to the new section section.cloneSectionPropertiesTo(newSection); // Copy the content of the original document's page to the new document for (int i = startIndex; i <=endIndex; i++) { newSection.getBody().getChildObjects().add(section.getBody().getChildObjects().get(i).deepClone()); } // Save the new document to the specified file newdoc.saveToFile("Content of One Page.docx", FileFormat.Docx); // Close and release the new document newdoc.close(); newdoc.dispose(); // Close and release the original document document.close(); document.dispose(); } }
Read a Section from a Word Document in Java
Using Document.Sections[index], you can access specific Section objects that contain the header, footer, and body content of a document. The following example demonstrates a simple method to copy all content from one section to another document. The detailed steps are as follows:
- Create a Document object.
- Load a Word document using the Document.loadFromFile() method.
- Use Document.getSections().get(1) to retrieve the second section of the document.
- Create another new Document object.
- Clone the default style of the original document to the new document using Document.cloneDefaultStyleTo(newdoc) method.
- Use Document.getSections().add(section.deepClone()) to clone the content of the second section of the original document to the new document.
- Save the resulting document using the Document.saveToFile() method.
- Java
import com.spire.doc.*; public class ReadOneSection { public static void main(String[] args) { // Create a new document object Document document = new Document(); // Load a Word document from a file document.loadFromFile("Sample.docx"); // Get the second section of the document Section section = document.getSections().get(1); // Create a new document object Document newdoc = new Document(); // Clone the default style to the new document document.cloneDefaultStyleTo(newdoc); // Clone the second section to the new document newdoc.getSections().add(section.deepClone()); // Save the new document to a file newdoc.saveToFile("Content of One Section.docx", FileFormat.Docx); // Close and release the new document object newdoc.close(); newdoc.dispose(); // Close and release the original document object document.close(); document.dispose(); } }
Read the Entire Content from a Word Document in Java
This example demonstrates how to iterate through each section of the original document to read the entire content of the document and clone each section into a new document. This method can help you quickly replicate both the structure and content of the entire document, preserving the format and layout of the original document in the new document. Such operations are very useful for maintaining the integrity and consistency of the document structure. The detailed steps are as follows:
- Create a Document object.
- Load a Word document using the Document.loadFromFile() method.
- Create another new Document object.
- Clone the default style of the original document to the new document using the Document.cloneDefaultStyleTo(newdoc) method.
- Iterate through each section of the original document using a for loop and clone it into the new document.
- Save the resulting document using the Document.saveToFile() method.
- Java
import com.spire.doc.*; public class ReadOneDocument { public static void main(String[] args) { // Create a new document object Document document = new Document(); // Load a Word document from a file document.loadFromFile("Sample.docx"); // Create a new document object Document newdoc = new Document(); // Clone the default style to the new document document.cloneDefaultStyleTo(newdoc); // Iterate through each section in the original document and clone it to the new document for (Section sourceSection : (Iterable) document.getSections()) { newdoc.getSections().add(sourceSection.deepClone()); } // Save the new document to a file newdoc.saveToFile("Content of the entire document.docx", FileFormat.Docx); // Close and release the new document object newdoc.close(); newdoc.dispose(); // Close and release the original document object document.close(); document.dispose(); } }
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.