News Category

Adding, inserting, and deleting pages in a Word document are crucial steps in managing and presenting content. By adding or inserting new pages, you can expand the document to accommodate more content, making it more organized and readable. Deleting pages helps simplify the document by removing unnecessary or erroneous information. These operations can enhance the overall quality and clarity of the document. This article will demonstrate how to use Spire.Doc for Java to add, insert, and delete pages in a Word document within a Java project.

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>
    

Add a Page in a Word Document in Java

The steps to add a new page at the end of a Word document include locating the last section, and then inserting a page break at the end of that section's last paragraph. This way ensures that any content added subsequently will start displaying on a new page, maintaining the clarity and coherence of the document structure. The detailed steps are as follows:

  • Create a Document object.
  • Load a Word document using the Document.loadFromFile() method.
  • Get the body of the last section of the document using Document.getLastSection().getBody().
  • Add a page break by calling Paragraph.appendBreak(BreakType.Page_Break) method.
  • Create a new paragraph style ParagraphStyle object.
  • Add the new paragraph style to the document's style collection using Document.getStyles().add(paragraphStyle) method.
  • Create a new paragraph Paragraph object and set the text content.
  • Apply the previously created paragraph style to the new paragraph using Paragraph.applyStyle(paragraphStyle.getName()) method.
  • Add the new paragraph to the document using Body.getChildObjects().add(paragraph) method.
  • Save the resulting document using the Document.saveToFile() method.
  • Java
import com.spire.doc.*;
import com.spire.doc.documents.*;

public class AddOnePage {
    public static void main(String[] args) {
        // Create a new document object
        Document document = new Document();

        // Load a sample document from a file
        document.loadFromFile("Sample.docx");

        // Get the body of the last section of the document
        Body body = document.getLastSection().getBody();

        // Insert a page break after the last paragraph in the body
        body.getLastParagraph().appendBreak(BreakType.Page_Break);

        // Create a new paragraph style
        ParagraphStyle paragraphStyle = new ParagraphStyle(document);
        paragraphStyle.setName("CustomParagraphStyle1");
        paragraphStyle.getParagraphFormat().setLineSpacing(12);
        paragraphStyle.getParagraphFormat().setAfterSpacing(8);
        paragraphStyle.getCharacterFormat().setFontName("Microsoft YaHei");
        paragraphStyle.getCharacterFormat().setFontSize(12);

        // Add the paragraph style to the document's style collection
        document.getStyles().add(paragraphStyle);

        // Create a new paragraph and set the text content
        Paragraph paragraph = new Paragraph(document);
        paragraph.appendText("Thank you for using our Spire.Doc for Java product. The trial version will add a red watermark to the generated result document and only supports converting the first 10 pages to other formats. Upon purchasing and applying a license, these watermarks will be removed, and the functionality restrictions will be lifted.");

        // Apply the paragraph style
        paragraph.applyStyle(paragraphStyle.getName());

        // Add the paragraph to the body's content collection
        body.getChildObjects().add(paragraph);

        // Create another new paragraph and set the text content
        paragraph = new Paragraph(document);
        paragraph.appendText("To fully experience our product, we provide a one-month temporary license for each of our customers for free. Please send an email to sales@e-iceblue.com, and we will send the license to you within one working day.");

        // Apply the paragraph style
        paragraph.applyStyle(paragraphStyle.getName());

        // Add the paragraph to the body's content collection
        body.getChildObjects().add(paragraph);

        // Save the document to a specified path
        document.saveToFile("Add a Page.docx", FileFormat.Docx);

        // Close the document
        document.close();

        // Dispose of the document object's resources
        document.dispose();
    }
}

Java Add, Insert, or Delete Pgaes in Word Documents

Insert a Page in a Word Document in Java

Before inserting a new page, it is necessary to determine the ending position index of the specified page content within the section, and then add the content of the new page to the document one by one. To ensure that the content is separated from the subsequent pages, page breaks need to be inserted at appropriate positions. The detailed steps are as follows:

  • Create a Document object.
  • Load a Word document using the Document.loadFromFile() method.
  • Create a FixedLayoutDocument object.
  • Obtain the FixedLayoutPage object of a page in the document.
  • Get the index position of the last paragraph on the page within the section.
  • Create a new paragraph style ParagraphStyle object.
  • Add the new paragraph style to the document using the Document.getStyles().add(paragraphStyle) method.
  • Create a new paragraph Paragraph object and set the text content.
  • Apply the previously created paragraph style to the new paragraph using the Paragraph.applyStyle(paragraphStyle.getName()) method.
  • Insert the new paragraph at the specified position using the Body.getChildObjects().insert(index, Paragraph) method.
  • Create another new paragraph object, set its text content, add a page break by calling the Paragraph.appendBreak(BreakType.Page_Break) method, apply the previously created paragraph style, and finally insert this paragraph into the 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 InsertOnePage {
    public static void main(String[] args) {
        // Create a new document object
        Document document = new Document();

        // Load a sample document from a 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 body of the document
        Body body = page.getSection().getBody();

        // Get the paragraph at the end of the current page
        Paragraph paragraphEnd = page.getColumns().get(0).getLines().getLast().getParagraph();

        // Initialize the end index
        int endIndex = 0;
        if (paragraphEnd != null) {
            // Get the index of the last paragraph
            endIndex = body.getChildObjects().indexOf(paragraphEnd);
        }

        // Create a new paragraph style
        ParagraphStyle paragraphStyle = new ParagraphStyle(document);
        paragraphStyle.setName("CustomParagraphStyle1");
        paragraphStyle.getParagraphFormat().setLineSpacing(12);
        paragraphStyle.getParagraphFormat().setAfterSpacing(8);
        paragraphStyle.getCharacterFormat().setFontName("Microsoft YaHei");
        paragraphStyle.getCharacterFormat().setFontSize(12);

        // Add the style to the document
        document.getStyles().add(paragraphStyle);

        // Create a new paragraph and set the text content
        Paragraph paragraph = new Paragraph(document);
        paragraph.appendText("Thank you for using our Spire.Doc for Java product. The trial version will add a red watermark to the generated result document and only supports converting the first 10 pages to other formats. Upon purchasing and applying a license, these watermarks will be removed, and the functionality restrictions will be lifted.");

        // Apply the paragraph style
        paragraph.applyStyle(paragraphStyle.getName());

        // Insert the paragraph at the specified position
        body.getChildObjects().insert(endIndex + 1, paragraph);

        // Create another new paragraph and set the text content
        paragraph = new Paragraph(document);
        paragraph.appendText("To fully experience our product, we provide a one-month temporary license for each of our customers for free. Please send an email to sales@e-iceblue.com, and we will send the license to you within one working day.");

        // Apply the paragraph style
        paragraph.applyStyle(paragraphStyle.getName());

        // Add a page break
        paragraph.appendBreak(BreakType.Page_Break);

        // Insert the paragraph at the specified position
        body.getChildObjects().insert(endIndex + 2, paragraph);

        // Save the document to a specified path
        document.saveToFile("Insert a New Page after a Specified Page.docx", FileFormat.Docx);

        // Close and dispose of the document object's resources
        document.close();
        document.dispose();
    }
}

Java Add, Insert, or Delete Pgaes in Word Documents

Delete a Page from a Word Document in Java

To delete the content of a page, you first need to find the position index of the starting and ending elements of that page in the document. Then, by looping through, you can remove these elements one by one to delete the entire content of the page. The detailed steps are as follows:

  • Create a Document object.
  • Load a Word document using the Document.loadFromFile() method.
  • Create a FixedLayoutDocument object.
  • Obtain the FixedLayoutPage object of the first 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.
  • Use a for loop to remove the content of the page one by one.
  • 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 RemoveOnePage {
    public static void main(String[] args) {
        // Create a new document object
        Document document = new Document();

        // Load a sample document from a file
        document.loadFromFile("Sample.docx");

        // Create a fixed layout document object
        FixedLayoutDocument layoutDoc = new FixedLayoutDocument(document);

        // Get the second page
        FixedLayoutPage page = layoutDoc.getPages().get(1);

        // Get the section of the page
        Section section = page.getSection();

        // Get the first paragraph on the first page
        Paragraph paragraphStart = page.getColumns().get(0).getLines().getFirst().getParagraph();
        int startIndex = 0;
        if (paragraphStart != null) {
            // Get the index of the starting paragraph
            startIndex = section.getBody().getChildObjects().indexOf(paragraphStart);
        }

        // Get the last paragraph on the last page
        Paragraph paragraphEnd = page.getColumns().get(0).getLines().getLast().getParagraph();

        int endIndex = 0;
        if (paragraphEnd != null) {
            // Get the index of the ending paragraph
            endIndex = section.getBody().getChildObjects().indexOf(paragraphEnd);
        }

        // Remove paragraphs within the specified range
        for (int i = 0; i <= (endIndex - startIndex); i++) {
            section.getBody().getChildObjects().removeAt(startIndex);
        }

        // Save the document to a specified path
        document.saveToFile("Delete a Page.docx", FileFormat.Docx);

        // Close and dispose of the document object's resources
        document.close();
        document.dispose();
    }
}

Java Add, Insert, or Delete Pgaes 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.

Converting Word documents to XPS, PostScript, and OFD documents is of significant importance. Firstly, this conversion makes it easier to share and display documents across different platforms and applications, as these formats typically have broader compatibility.

Secondly, converting to these formats can preserve the document's formatting, layout, and content, ensuring consistent display across different systems.

Additionally, XPS and OFD formats support high-quality printing, helping to maintain the visual appearance and print quality of the document. The PostScript format is commonly used for printing and graphic processing, converting to PostScript can ensure that the document maintains high quality when printed.

In this article, you will learn how to convert Word to XPS, PostScript, or OFD with Python using Spire.Doc for Python.

Install Spire.Doc for Python

This scenario requires Spire.Doc for Python and plum-dispatch v1.7.4. They can be easily installed in your VS Code through the following pip commands.

pip install Spire.Doc

If you are unsure how to install, please refer to this tutorial: How to Install Spire.Doc for Python in VS Code

Convert Word to XPS in Python

The Document.SaveToFile(filename:str, FileFormat.XPS) method provided by Spire.Doc for Python can convert a Word document to XPS format. The detailed steps are as follows:

  • Create an object of the Document class.
  • Use the Document.LoadFromFile() method to load the Word document.
  • Use the Document.SaveToFile(filename:str, FileFormat.XPS) method to convert the Word document to an XPS document.
  • Python
from spire.doc import *
from spire.doc.common import *

# Create a Document object
doc = Document()

# Load a Word document
doc.LoadFromFile("Sample.docx")

# Save the loaded document as an XPS document
doc.SaveToFile("Result.xps", FileFormat.XPS)

# Close the document object and release the resources occupied by the document object
doc.Close()
doc.Dispose()

Python: Convert Word to XPS, PostScript, or OFD

Convert Word to PostScript in Python

With Document.SaveToFile(filename:str, FileFormat.PostScript) method in Spire.Doc for Python, you can convert a Word document to PostScript format. The detailed steps are as follows:

  • Create an object of the Document class.
  • Use the Document.LoadFromFile() method to load the Word document.
  • Use the Document.SaveToFile(filename:str, FileFormat.PostScript) method to convert the Word document to a PostScript document.
  • Python
from spire.doc import *
from spire.doc.common import *

# Create a Document object
doc = Document()

# Load a Word document
doc.LoadFromFile("Sample.docx")

# # Save the loaded document as a PostScript document
doc.SaveToFile("Result.ps", FileFormat.PostScript)

# Close the document object and release the resources occupied by the document object
doc.Close()
doc.Dispose()

Python: Convert Word to XPS, PostScript, or OFD

Convert Word to OFD in Python

By utilizing the Document.SaveToFile() method in the Spire.Doc for Python library and specifying the file format as FileFormat.OFD, you can save a Word document as an OFD file format. The detailed steps are as follows:

  • Create an object of the Document class.
  • Use the Document.LoadFromFile() method to load the Word document.
  • Use the Document.SaveToFile(filename:str, FileFormat.OFD) method to convert the Word document to an OFD document.
  • Python
from spire.doc import *
from spire.doc.common import *

# Create a Document object
doc = Document()

# Load a Word document
doc.LoadFromFile("Sample.docx")

# Save the loaded document as an OFD document
doc.SaveToFile("Result.ofd", FileFormat.OFD)

# Close the document object and release the resources occupied by the document object
doc.Close()
doc.Dispose()

Python: Convert Word to XPS, PostScript, or OFD

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.

Reading content from a Word document is crucial for many work and study tasks. Reading a page from a Word document helps in quickly browsing and summarizing key information, reading a section from a Word document aids in gaining a deeper understanding of a specific topic or section, while reading the entire document from a Word document allows for a comprehensive grasp of the overall information, facilitating comprehensive analysis and understanding. This article will introduce how to use Spire.Doc for .NET to read a page, a section, and the entire content of a Word document in a C# project.

Install Spire.Doc for .NET

To begin with, you need to add the DLL files included in the Spire.Doc for .NET package as references in your .NET project. The DLL files can be either downloaded from this link or installed via NuGet.

PM> Install-Package Spire.Doc

Read a Page from a Word Document in C#

By using the FixedLayoutDocument class and FixedLayoutPage class, you can easily retrieve the content of a specified page. To facilitate viewing the extracted content, this sample code will store the read content in 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.
  • Retrieve the FixedLayoutPage object of a page in the document.
  • Access the Section where the page is located through the FixedLayoutPage.Section property.
  • 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 the 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.
  • C#
using Spire.Doc;
using Spire.Doc.Pages;
using Spire.Doc.Documents;

namespace SpireDocDemo
{
    internal class Program
    {
        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.Pages[0];

            // Get the section where the page is located
            Section section = page.Section;

            // Get the first paragraph of the page
            Paragraph paragraphStart = page.Columns[0].Lines[0].Paragraph;
            int startIndex = 0;
            if (paragraphStart != null)
            {
                // Get the index of the paragraph in the section
                startIndex = section.Body.ChildObjects.IndexOf(paragraphStart);
            }

            // Get the last paragraph of the page
            Paragraph paragraphEnd = page.Columns[0].Lines[page.Columns[0].Lines.Count - 1].Paragraph;

            int endIndex = 0;
            if (paragraphEnd != null)
            {
                // Get the index of the paragraph in the section
                endIndex = section.Body.ChildObjects.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 page from the original document to the new document
            for (int i = startIndex; i <= endIndex ; i++)
            {
                newSection.Body.ChildObjects.Add(section.Body.ChildObjects[i].Clone());
            }

            // Save the new document to a specified file
            newdoc.SaveToFile("ReadOnePageContent.docx", Spire.Doc.FileFormat.Docx);

            // Close and release the new document
            newdoc.Close();
            newdoc.Dispose();

            // Close and release the original document
            document.Close();
            document.Dispose();
        }
    }
}

C# Read Content from a Word Document

Read a Section from a Word Document in C#

By using Document.Sections[index], you can retrieve a specific Section object that contains the header, footer, and body content. This example provides a simple way to copy all content of a section to another document. The detailed steps are as follows:

  • Create a Document object.
  • Use the Document.LoadFromFile() method to load a Word document.
  • Use Document.Sections[1] to retrieve the second section of the document.
  • Create another new Document object.
  • Use the Document.CloneDefaultStyleTo(newdoc) method to clone the default style of the original document to the new document.
  • Use newdoc.Sections.Add(section.Clone()) to clone the content of the second section of the original document into the new document.
  • Use the Document.SaveToFile() method to save the resulting document.
  • C#
using Spire.Doc;

namespace SpireDocDemo
{
    internal class Program
    {
        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.Sections[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.Sections.Add(section.Clone());

            // Save the new document to a file
            newdoc.SaveToFile("ReadOneSectionContent.docx", Spire.Doc.FileFormat.Docx);

            // Close and release the new document object
            newdoc.Close();
            newdoc.Dispose();

            // Close and release the original document object
            document.Close();
            document.Dispose();
        }
    }
}

C# Read Content from a Word Document

Read the Entire Content from a Word Document in C#

This example demonstrates reading the entire content of a document by iterating through each section of the original document and cloning each section into a new document. The detailed steps are as follows:

  • Create a Document object.
  • Use the Document.LoadFromFile() method to load a Word document.
  • Create another new Document object.
  • Use the Document.CloneDefaultStyleTo(newdoc) method to clone the default style of the original document to the new document.
  • Iterate through each section of the original document using a foreach loop and clone each section into the new document.
  • Use the Document.SaveToFile() method to save the resulting document.
  • C#
using Spire.Doc;

namespace SpireDocDemo
{
    internal class Program
    {
        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
            foreach (Section sourceSection in document.Sections)
            {
                newdoc.Sections.Add(sourceSection.Clone());
            }

            // Save the new document to a file
            newdoc.SaveToFile("ReadEntireDocumentContent.docx", Spire.Doc.FileFormat.Docx);

            // Close and release the new document object
            newdoc.Close();
            newdoc.Dispose();

            // Close and release the original document object
            document.Close();
            document.Dispose();
        }
    }
}

C# Read Content from a Word Document

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.

Page 7 of 288