Page borders can be a useful design element in Microsoft Word documents. They can help to frame the content and provide a polished, professional. Page borders draw the reader's eye to the main content area and create a sense of structure and cohesion. Conversely, you may want to remove page borders if they are not needed or if they distract from the content.

In this article, you will learn how to add, adjust, and remove page borders in a Word document using Java and 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>14.6.0</version>
    </dependency>
</dependencies>

Add Page Borders to a Word Document in Java

Spire.Doc for Java includes the Borders class, which enables developers to manage the page borders in a Word document. This class provides a collection of methods that allow you to control various aspects of the page border, such as the border type, color, and line width.

To add borders to all pages in a Word document using Java, the general steps are as follows:

  • Create a Document object.
  • Load a Word file from the given file path.
  • Iterate through the sections in the document.
    • Get a specific section.
    • Get the PageSetup object of the section.
    • Apply borders to all page by passing PageBordersApplyType.All_Pages as the parameter of PageSetup.setPageBordersApplyType() method.
    • Get the Borders object using PageSetup.getBorders() method.
    • Set the border type, color, line width and other attributes using the methods under the Borders object.
  • Save the updated document to a different Word file.
  • Java
import com.spire.doc.*;
import com.spire.doc.documents.BorderStyle;

import java.awt.*;

public class AddPageBorder {

    public static void main(String[] args) {

        // Create a Document object
        Document doc = new Document();

        // Load a Word file
        doc.loadFromFile("C:\\Users\\Administrator\\Desktop\\Input.docx");

        // Iterate through the sections in the document
        for (int i = 0; i < doc.getSections().getCount(); i++)
        {
            // Get a specific section
            Section section = doc.getSections().get(i);

            // Get page setup object
            PageSetup pageSetup = section.getPageSetup();

            // Apply page border to all pages
            pageSetup.setPageBordersApplyType(PageBordersApplyType.All_Pages);

            // Set the border type
            pageSetup.getBorders().setBorderType(BorderStyle.Dash_Large_Gap);

            // Set the border width
            pageSetup.getBorders().setLineWidth(2);

            // Set the border color
            pageSetup.getBorders().setColor(Color.RED);

            // Set the spacing between borders and text within them
            pageSetup.getBorders().getTop().setSpace(30);
            pageSetup.getBorders().getBottom().setSpace(30);
            pageSetup.getBorders().getLeft().setSpace(30);
            pageSetup.getBorders().getRight().setSpace(30);
        }

        // Save the updated document to a different file
        doc.saveToFile("AddPageBorder.docx", FileFormat.Docx);

        // Dispose resources
        doc.dispose();
    }
}

Java: Add, Adjust, or Remove Page Borders in Word

Adjust Page Borders in a Word Document in Java

The page borders of an existing Word document can be obtained using the PageSetup.getBorders() method. You can change the appearance of the page borders using the setBorderType(), setColor(), and setLineWidth() methods.

The steps to adjust page borders in a Word document using Java are as follows.

  • Create a Document object.
  • Load a Word file from the given file path.
  • Iterate through the sections in the document.
    • Get a specific section.
    • Get the PageSetup object of the section.
    • Get the Borders object using PageSetup.getBorders() method.
    • Set the border type, color, line width and other attributes using the methods under the Borders object.
  • Save the updated document to a different Word file.
  • Java
import com.spire.doc.Document;
import com.spire.doc.FileFormat;
import com.spire.doc.PageSetup;
import com.spire.doc.Section;
import com.spire.doc.documents.BorderStyle;

import java.awt.*;

public class AdjustPageBorders {

    public static void main(String[] args) {

        // Create a Document object
        Document doc = new Document();

        // Load a Word file
        doc.loadFromFile("C:\\Users\\Administrator\\Desktop\\Borders.docx");

        // Iterate through the sections in the document
        for (int i = 0; i < doc.getSections().getCount(); i++)
        {
            // Get a specific section
            Section section = doc.getSections().get(i);

            // Get page setup of the section
            PageSetup pageSetup = section.getPageSetup();

            // Change the border type
            section.getPageSetup().getBorders().setBorderType(BorderStyle.Double);

            // Change the border color
            section.getPageSetup().getBorders().setColor(Color.DARK_GRAY);

            // Change the border width
            section.getPageSetup().getBorders().setLineWidth(3);
        }

        // Save the updated document to a different file
        doc.saveToFile("AdjustBorder.docx", FileFormat.Docx);

        // Dispose resources
        doc.dispose();
    }
}

Java: Add, Adjust, or Remove Page Borders in Word

Remove Page Borders from a Word Document in Java

To move page borders from a Word document, pass the BorderStyle.None as the parameter of the Borders.setBorderType() method. By setting the border type as none, you are instructing the document to remove any existing page borders, resulting in a clean, border-free document layout.

The steps to remove page borders from a Word document using Java are as follows:

  • Create a Document object.
  • Load a Word file from the given file path.
  • Iterate through the sections in the document.
    • Get a specific section.
    • Get the PageSetup object of the section.
    • Get the Borders object using PageSetup.getBorders() method.
    • Set the border type as BorderStyle.None using Borders.setBorderType() method.
  • Save the updated document to a different Word file.
  • Java
import com.spire.doc.Document;
import com.spire.doc.FileFormat;
import com.spire.doc.PageSetup;
import com.spire.doc.Section;
import com.spire.doc.documents.BorderStyle;

public class RemovePageBorders {

    public static void main(String[] args) {

        // Create a Document object
        Document doc = new Document();

        // Load a Word file
        doc.loadFromFile("C:\\Users\\Administrator\\Desktop\\Borders.docx");

        // Iterate through the sections in the document
        for (int i = 0; i < doc.getSections().getCount(); i++)
        {
            // Get a specific section
            Section section = doc.getSections().get(i);

            // Get page setup object
            PageSetup pageSetup = section.getPageSetup();

            // Set the border type to none
            pageSetup.getBorders().setBorderType(BorderStyle.None);
        }

        // Save the updated document to a different file
        doc.saveToFile("RemovePageBorders.docx", FileFormat.Docx);

        // Dispose resources
        doc.dispose();
    }
}

Java: Add, Adjust, or Remove Page Borders in Word

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.

Adjusting the column widths in a Word table is crucial for making the document look neat and easy to read. Particularly in tables with a lot of text, appropriate column widths can facilitate smoother reading. Word offers two approaches: percentage-based and fixed widths. Setting column widths by percentage can adapt to various screen sizes, keeping content neatly formatted and more pleasant to read. Using fixed widths stabilizes the table structure, precisely aligning each section, which is especially suitable for tables requiring strict alignment of numbers or complex designs. This article will introduce how to set Word table column widths based on percentage or fixed values using Spire.Doc for Java in Java projects.

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>14.6.0</version>
    </dependency>
</dependencies>

Set Column Width Based on Percentage in Java

To set column widths in a Word table using percentage values, you first need to define the table's width type as percentage. This can be achieved with Table.SetPreferredWidth(new PreferredWidth(WidthType.Percentage, (short)100)). Then, iterate through each column and set their widths to either the same or different percentage values. Here are the detailed steps:

  • Create a Document object.
  • Load a document using the Document.loadFromFile() method.
  • Retrieve the first section of the document using Document.getSections().get(0).
  • Get the first table within the section using Section.getTables().get(0).
  • Use a for loop to iterate through all rows in the table.
  • Set the column width for cells in different columns to percentage values using the TableRow.getCells().get(index).setCellWidth(value, CellWidthType.Percentage) method, where value is the percentage width you wish to apply.
  • Save the changes to the Word document using the Document.saveToFile() method.
  • Java
import com.spire.doc.*;

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

        // Load the document
        doc.loadFromFile("Sample.docx");

        // Get the first Section of the document
        Section section = doc.getSections().get(0);

        // Cast the first Table in the Section to a Table type
        Table table = section.getTables().get(0);

        // Create a PreferredWidth object, set the width type to Percentage, and set the width value to 100%
        PreferredWidth percentageWidth = new PreferredWidth(WidthType.Percentage, (short) 100);

        // Set the Table's preferred width to the PreferredWidth object created above
        table.setPreferredWidth(percentageWidth);

        // Define a variable of type TableRow
        TableRow tableRow;

        // Iterate over all rows in the Table
        for (int i = 0; i < table.getRows().getCount(); i++) {
            // Get the current row
            tableRow = table.getRows().get(i);

            // Set the width of the first cell to 34%, type as Percentage
            tableRow.getCells().get(0).setCellWidth(34, CellWidthType.Percentage);

            // Set the width of the second cell to 33%, type as Percentage
            tableRow.getCells().get(1).setCellWidth(33, CellWidthType.Percentage);

            // Set the width of the third cell to 33%, type as Percentage
            tableRow.getCells().get(2).setCellWidth(33, CellWidthType.Percentage);
        }

        // Save the modified document, specifying the file format as Docx2016
        doc.saveToFile("SetColumnWidthsWithPercentageValues.docx", FileFormat.Docx_2016);

        // Close the document
        doc.close();
    }
}

Java: Set the Column Width of a Word Table

Set Column Width Based on Fixed Value in Java

When setting column widths in a Word table using fixed values, you first need to set the table to a fixed layout. This is done with Table.getTableFormat().setLayoutType(LayoutType.Fixed), then iterate through each column and set the width to the same or different fixed values as required. Here are the detailed steps:

  • Create a Document object.
  • Load a document using the Document.loadFromFile() method.
  • Retrieve the first section of the document using Document.getSections().get(0).
  • Get the first table within the section using Section.getTables().get(0).
  • Use a for loop to iterate through all rows in the table.
  • Set the column width for cells in different columns to fixed values using the TableRow.getCells().get(index).setCellWidth(value, CellWidthType.Point) method.
  • Save the changes to the Word document using the Document.saveToFile() method.
  • Java
import com.spire.doc.*;

public class FixedColumnWidth {
    public static void main(String[] args) {

        // Create a new Document object
        Document doc = new Document();

        // Load the document
        doc.loadFromFile("Sample.docx");

        // Get the first Section of the document
        Section section = doc.getSections().get(0);

        // Cast the first Table in the Section to a Table type
        Table table = section.getTables().get(0);

        // Set the table layout type to Fixed
        table.getFormat().setLayoutType(LayoutType.Fixed);

        // Set the table resizing method to not Auto
        table.getFormat().setAllowAutoFit(false);

        // Get the left margin
        float leftMargin = section.getPageSetup().getMargins().getLeft();

        // Get the right margin
        float rightMargin = section.getPageSetup().getMargins().getRight();

        // Calculate the page width minus left and right margins
        double pageWidth = section.getPageSetup().getPageSize().getWidth() - leftMargin - rightMargin;

        // Define a variable of type TableRow
        TableRow tableRow;

        // Iterate through all rows in the Table
        for (int i = 0; i < table.getRows().getCount(); i++) {
            // Get the current row
            tableRow = table.getRows().get(i);

            // Set the first column cell width to 34% of the page width
            tableRow.getCells().get(0).setCellWidth((float) (pageWidth * 0.34), CellWidthType.Point);

            // Set the second column cell width to 33% of the page width
            tableRow.getCells().get(1).setCellWidth((float) (pageWidth * 0.33), CellWidthType.Point);

            // Set the third column cell width to 33% of the page width
            tableRow.getCells().get(2).setCellWidth((float) (pageWidth * 0.33), CellWidthType.Point);
        }

        // Save the modified document, specifying the file format as Docx2016
        doc.saveToFile("SetColumnWidthsWithFixedValues.docx", FileFormat.Docx_2016);

        // Close the document
        doc.close();
    }
}

Java: Set the Column Width of a Word Table

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.

Adding and removing watermarks in PDF documents play a crucial role in document management, copyright protection, and information security. A watermark can serve as a visual marker, such as a company logo, copyright notice, or the word "Confidential", indicating the source, status, or ownership of the document.

Spire.PDF provides a method for adding watermarks by embedding watermark annotations within the PDF document. This approach affords the flexibility to remove the watermark post-insertion, offering users greater control and options. This article will introduce how to add or remove watermark annotations in PDF documents using Spire.PDF for Java in Java projects.

Install Spire.PDF for Java

First of all, you're required to add the Spire.Pdf.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.pdf</artifactId>
        <version>12.6.1</version>
    </dependency>
</dependencies>

Add Watermark Annotations to PDF in Java

Spire.PDF provides a method to add watermark annotations to PDF pages using the PdfWatermarkAnnotation object. Notably, watermarks added by this method can be easily removed later. Here are the key steps involved:

  • Initialize an instance of the PdfDocument class.
  • Load a PDF document using the PdfDocument.loadFromFile() method.
  • Create a PdfTrueTypeFont font object to draw the watermark text.
  • Create a Rectangle2D type object to define the boundary of the page.
  • Use a for loop to iterate over all PdfPageBase objects in the PDF document.
  • Create a PdfTemplate object for drawing the watermark, setting its size to match the current page.
  • Call a custom insertWatermark() method to draw the watermark content onto the PdfTemplate object.
  • Create a PdfWatermarkAnnotation object and define the position where the watermark should be placed.
  • Create a PdfAppearance object to configure the visual effects of the watermark.
  • Use the PdfAppearance.setNormal(PdfTemplate) method to associate the PdfTemplate object with the PdfAppearance object.
  • Use the PdfWatermarkAnnotation.setAppearance(PdfAppearance) method to associate the PdfAppearance object with the PdfWatermarkAnnotation object.
  • Add the watermark annotation to the page by calling PdfPageBase.getAnnotationsWidget().add(PdfWatermarkAnnotation).
  • Save the changes to a file using the PdfDocument.saveToFile() method.
  • Java
import com.spire.pdf.*;
import com.spire.pdf.annotations.*;
import com.spire.pdf.annotations.appearance.*;
import com.spire.pdf.graphics.*;
import java.awt.*;
import java.awt.geom.*;

public class AddWatermarkInPDF {
    public static void main(String[] args) {
        // Create a PdfDocument object
        PdfDocument pdfDocument = new PdfDocument();

        // Load the PDF document from a file
        pdfDocument.loadFromFile("Sample1.pdf");

        // Set the font style
        Font font = new Font("Arial", Font.PLAIN, 22);

        // Create a PdfTrueTypeFont object for subsequent text rendering
        PdfTrueTypeFont trueTypeFont = new PdfTrueTypeFont(font);

        // Get the page object
        PdfPageBase page;

        // Define the watermark text
        String watermarkAnnotationText = "ID_0";

        // Create a size object
        Dimension2D dimension2D = new Dimension();

        // Create a rectangle object
        Rectangle2D loRect = new Rectangle2D.Float();

        // Iterate through each page in the PDF
        for (int i = 0; i < pdfDocument.getPages().getCount(); i++) {
            // Get the current page
            page = pdfDocument.getPages().get(i);

            // Set the size object to the size of the current page
            dimension2D.setSize(page.getClientSize().getWidth(), page.getClientSize().getHeight());

            // Set the rectangle object frame, which is the entire page range
            loRect.setFrame(new Point2D.Float(0, 0), dimension2D);

            // Create a PdfTemplate object to draw the watermark
            PdfTemplate template = new PdfTemplate(page.getClientSize().getWidth(), page.getClientSize().getHeight());

            // Insert the watermark
            insertWatermark(template, trueTypeFont, "Non Editable");

            // Create a PdfWatermarkAnnotation object to define the watermark position
            PdfWatermarkAnnotation watermarkAnnotation = new PdfWatermarkAnnotation(loRect);

            // Create a PdfAppearance object to set the watermark appearance
            PdfAppearance appearance = new PdfAppearance(watermarkAnnotation);

            // Set the normal state template of the watermark
            appearance.setNormal(template);

            // Set the appearance to the watermark object
            watermarkAnnotation.setAppearance(appearance);

            // Set the watermark text
            watermarkAnnotation.setText(watermarkAnnotationText);

            // Set the watermark print matrix to control the watermark's position and size
            watermarkAnnotation.getFixedPrint().setMatrix(new float[]{1, 0, 0, 1, 0, 0});

            // Set the horizontal offset
            watermarkAnnotation.getFixedPrint().setHorizontalTranslation(0.5f);

            // Set the vertical offset
            watermarkAnnotation.getFixedPrint().setVerticalTranslation(0.5f);

            // Add the watermark to the page's annotation widget
            page.getAnnotationsWidget().add(watermarkAnnotation);
        }

        // Save the PDF document to a file
        pdfDocument.saveToFile("AddWatermark.pdf");

        // Close and release the PDF document resources
        pdfDocument.dispose();
    }

    static void insertWatermark(PdfTemplate template, PdfTrueTypeFont font, String watermark) {
        // Create a Dimension2D object to set the size of the watermark
        Dimension2D dimension2D = new Dimension();

        // Set the size of the watermark to half the width and one third the height of the template
        dimension2D.setSize(template.getWidth() / 2, template.getHeight() / 3);

        // Create a PdfTilingBrush object for repeating pattern fill of the watermark
        PdfTilingBrush brush = new PdfTilingBrush(dimension2D);

        // Set the transparency of the watermark to 0.3
        brush.getGraphics().setTransparency(0.3F);

        // Start a group of graphic state saves
        brush.getGraphics().save();

        // Translate the graphics context so its center aligns with the center of the watermark tile
        brush.getGraphics().translateTransform((float) brush.getSize().getWidth() / 2, (float) brush.getSize().getHeight() / 2);

        // Rotate the graphics context to tilt the watermark at 45 degrees
        brush.getGraphics().rotateTransform(-45);

        // Draw the watermark text in the graphics context using the specified font, color, and centered alignment
        brush.getGraphics().drawString(watermark, font, PdfBrushes.getGray(), 0, 0, new PdfStringFormat(PdfTextAlignment.Center));

        // End the group of graphic state saves and restore
        brush.getGraphics().restore();

        // Reset the watermark transparency to 1, i.e., completely opaque
        brush.getGraphics().setTransparency(1);

        // Create a Rectangle2D object to define the area for filling the watermark
        Rectangle2D loRect = new Rectangle2D.Float();

        // Set the fill area for the watermark to cover the entire size of the template
        loRect.setFrame(new Point2D.Float(0, 0), template.getSize());

        // Draw the watermark on the template using the watermark tile
        template.getGraphics().drawRectangle(brush, loRect);
    }
}

Java: Add or Remove Watermark Annotations in PDF Documents

Remove Watermark Annotations from PDF in Java

Spire.PDF can remove watermark annotations added to PDF pages via the PdfWatermarkAnnotation object. Here are the detailed steps:

  • Initialize an instance of the PdfDocument class.
  • Load a PDF document using the PdfDocument.loadFromFile() method.
  • Iterate over every PdfPageBase object in the PDF document using a for loop.
  • Retrieve all annotations on the current page using the PdfPageBase.getAnnotationsWidget() method.
  • Again, use a for loop to iterate over every annotation object on the current page, filtering out annotations of type PdfWatermarkAnnotationWidget.
  • Determine the target watermark annotation by invoking the PdfWatermarkAnnotationWidget.getText() method and perform the deletion operation.
  • Save the changes to a file using the PdfDocument.saveToFile() method.
  • Java
import com.spire.pdf.*;
import com.spire.pdf.annotations.*;

public class RemoveWatermarkFromPDF {
    public static void main(String[] args) {
        // Create a PdfDocument object
        PdfDocument pdfDocument = new PdfDocument();

        // Load the PDF document from a file
        pdfDocument.loadFromFile("Sample2.pdf");

        // Define a string ID to match and remove a specific watermark
        String id = "ID_0";

        // Iterate through every page in the PDF document
        for (int i = 0; i < pdfDocument.getPages().getCount(); i++) {
            // Get all annotations on the current page
            PdfAnnotationCollection annotationWidget = pdfDocument.getPages().get(i).getAnnotationsWidget();

            // Iterate through all annotations on the current page
            for (int j = 0; j < annotationWidget.getCount(); j++) {
                // Check if the current annotation is a watermark annotation
                if (annotationWidget.get(j) instanceof PdfWatermarkAnnotationWidget) {
                    // If the watermark text equals the ID, remove the watermark
                    if (annotationWidget.get(j).getText().equals(id)) {
                        annotationWidget.remove(annotationWidget.get(j));
                    }
                }
            }
        }

        // Save the modified PDF document to a new file
        pdfDocument.saveToFile("RemoveWatermark.pdf");

        // Dispose of the PdfDocument object resources
        pdfDocument.dispose();
    }
}

Java: Add or Remove Watermark Annotations in PDF 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.

Page 7 of 81
page 7