Monday, 30 January 2023 08:50

Java: Add, Edit, or Delete Bookmarks in PDF

A bookmark in a PDF document consists of formatted text linking to a specific section of the document. Readers can navigate through pages by simply clicking on the bookmarks displayed on the side of the page instead of scrolling up and down, which is very helpful for those huge documents. Moreover, well-organized bookmarks can also serve as contents. When you create a PDF document with a lot of pages, it’s better to add bookmarks to link to significant content. This article is going to show how to add, modify, and remove bookmarks in PDF documents using Spire.PDF for Java through programming.

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

Add Bookmarks to a PDF Document

Spire.PDF for Java provides PdfDocument.getBookmarks().add() method to add bookmarks to a PDF document. In addition to adding primary bookmarks, we can use PdfBookmark.add() method to add a sub-bookmark to a primary bookmark. There are also many other methods under PdfBookmark class which are used to set the destination, text color, and text style of bookmarks. The detailed steps of adding bookmarks to a PDF document are as follows.

  • Create a PdfDocument class instance.
  • Load a PDF document using PdfDocument.loadFromFile() method.
  • Loop through the pages in the PDF document to add bookmarks and set their styles.
  • Add a primary bookmark to the document using PdfDocument.getBookmarks().add() method.
  • Create a PdfDestination class object and set the destination of the primary bookmark using PdfBookmark.setAction() method.
  • Set the text color of the primary bookmark using PdfBookmark.setColor() method.
  • Set the text style of the Primary bookmark using PdfBookmark.setDisplayStyle() method.
  • Add a sub-bookmark to the primary bookmark using PdfBookmark.add() method.
  • Use the above methods to set the destination, text color, and text style of the sub-bookmark.
  • Save the document using PdfDocument.saveToFile() method.
  • Java
import com.spire.pdf.PdfDocument;
import com.spire.pdf.PdfPageBase;
import com.spire.pdf.actions.PdfGoToAction;
import com.spire.pdf.bookmarks.PdfBookmark;
import com.spire.pdf.bookmarks.PdfTextStyle;
import com.spire.pdf.general.PdfDestination;
import com.spire.pdf.graphics.PdfRGBColor;

import java.awt.*;
import java.awt.geom.Point2D;

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

        //Create a PdfDocument class instance
        PdfDocument pdf = new PdfDocument();

        //Load a PDF file
        pdf.loadFromFile("There's No Planet B.pdf");

        //Loop through the pages in the PDF file
        for(int i = 0; i< pdf.getPages().getCount();i++) {
            PdfPageBase page = pdf.getPages().get(i);
            //Add a bookmark
            PdfBookmark bookmark = pdf.getBookmarks().add(String.format("Bookmark-%s", i + 1));
            //Set the destination page and location
            PdfDestination destination = new PdfDestination(page, new Point2D.Float(0, 0));
            bookmark.setAction(new PdfGoToAction(destination));
            //Set the text color
            bookmark.setColor(new PdfRGBColor(new Color(139, 69, 19)));
            //Set the text style
            bookmark.setDisplayStyle(PdfTextStyle.Bold);
            //Add a child bookmark
            PdfBookmark childBookmark = bookmark.add(String.format("Sub-Bookmark-%s", i + 1));
            //Set the destination page and location
            PdfDestination childDestination = new PdfDestination(page, new Point2D.Float(0, 100));
            childBookmark.setAction(new PdfGoToAction(childDestination));
            //Set the text color
            childBookmark.setColor(new PdfRGBColor(new Color(255, 127, 80)));
            //Set the text style
            childBookmark.setDisplayStyle(PdfTextStyle.Italic);
        }

        //Save the result file
        pdf.saveToFile("AddBookmarks.pdf");
    }
}

Java: Add, Edit, or Delete Bookmarks in PDF

Edit Bookmarks in a PDF Document

We can also use methods of PdfBookmark class in Spire.PDF for Java to edit existing PDF bookmarks. The detailed steps are as follows.

  • Create a PdfDocument class instance.
  • Load a PDF document using PdfDocument.loadFromFile() method.
  • Get the first bookmark using PdfDocument.getBookmarks().get() method.
  • Change the title of the bookmark using PdfBookmark.setTitle() method.
  • Change the font color of the bookmark using PdfBookmark.setColor() method.
  • Change the outline text style of the bookmark using PdfBookmark.setDisplayStyle() method.
  • Change the text color and style of the sub-bookmark using the above methods.
  • Save the document using PdfDocument.saveToFile() method.
  • Java
import com.spire.pdf.PdfDocument;
import com.spire.pdf.bookmarks.PdfBookmark;
import com.spire.pdf.bookmarks.PdfTextStyle;
import com.spire.pdf.graphics.PdfRGBColor;

import java.awt.*;

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

        //Create a PdfDocument class instance
        PdfDocument doc = new PdfDocument();

        //Load a PDF file
        doc.loadFromFile("AddBookmarks.pdf");

        //Get the first bookmark
        PdfBookmark bookmark = doc.getBookmarks().get(0);
        //Change the title of the bookmark
        bookmark.setTitle("New Title");
        //Change the font color of the bookmark
        bookmark.setColor(new PdfRGBColor(new Color(255,0,0)));
        //Change the outline text style of the bookmark
        bookmark.setDisplayStyle(PdfTextStyle.Italic);

        //Edit sub-bookmarks of the first bookmark
        for (PdfBookmark childBookmark : (Iterable) bookmark) {
            childBookmark.setColor(new PdfRGBColor(new Color(0,0,255)));
            childBookmark.setDisplayStyle(PdfTextStyle.Bold);
        }

        //Save the result file
        doc.saveToFile("EditBookmarks.pdf");
        doc.close();
    }
}

Java: Add, Edit, or Delete Bookmarks in PDF

Delete Bookmarks from a PDF Document

We can use Spire.PDF for Java to delete any bookmark in a PDF document. PdfDocument.getBookmarks().removeAt() is used to remove a specific primary bookmark, PdfDocument.getBookmarks().clear() method is used to remove all bookmarks, and PdfBookmark.removeAt() method is used to remove a specific sub-bookmark of a primary bookmark. The detailed steps of removing bookmarks form a PDF document are as follows.

  • Create PdfDocument class instance.
  • Load a PDF document using PdfDocument.loadFromFile() method.
  • Get the first bookmark using PdfDocument.getBookmarks().get() method.
  • Remove the sub-bookmark of the first bookmark using PdfBookmark.removeAt() method.
  • Save the document using PdfDocument.saveToFile() method.
  • Java
import com.spire.pdf.PdfDocument;
import com.spire.pdf.bookmarks.PdfBookmark;

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

        //Create a PdfDocument instance
        PdfDocument pdf = new PdfDocument();

        //Load the PDF file
        pdf.loadFromFile("AddBookmarks.pdf");

        //Get the first bookmark
        PdfBookmark pdfBookmark = pdf.getBookmarks().get(0);

        //Delete the sub-bookmark of the first bookmark
        pdfBookmark.removeAt(0);

        //Delete the first bookmark along with its child bookmark
        //pdf.getBookmarks().removeAt(0);

        //Delete all the bookmarks
        //pdf.getBookmarks().clear();

        //Save the result file
        pdf.saveToFile("DeleteBookmarks.pdf");
    }
}

Java: Add, Edit, or Delete Bookmarks in PDF

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.

Thursday, 16 July 2020 07:13

Add Borders to Some Text in Word in Java

This article demonstrates how to apply a border around a set of charaters and how to apply a border around a whole paragraph, by using Spire.Doc for Java.

import com.spire.doc.Document;
import com.spire.doc.FileFormat;
import com.spire.doc.Section;
import com.spire.doc.documents.BorderStyle;
import com.spire.doc.documents.BreakType;
import com.spire.doc.documents.Paragraph;
import com.spire.doc.fields.TextRange;

import java.awt.*;

public class AddBorders {

    public static void main(String[] args) {

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

        //Add a section
        Section section = doc.addSection();

        //Add a border to a set of characters
        Paragraph para = section.addParagraph();
        TextRange tr = para.appendText("Spire.Doc for Java");
        tr.getCharacterFormat().getBorder().setBorderType(BorderStyle.Single);
        tr.getCharacterFormat().getBorder().setColor(Color.BLACK);
        String text = " is a professional Java library specifically designed for developers to create, read, " +
                "write, convert and print Word document files on Java platform.";
        para.appendText(text);
        para.appendBreak(BreakType.Line_Break);

        //Add a border to a paragraph
        para = section.addParagraph();
        String text2 = "A plenty of Word document processing tasks can be performed by Spire.Doc for Java, such as " +
                "creating, reading, editing, converting and printing Word documents." ;
        para.appendText(text2);
        para.getFormat().getBorders().setBorderType(BorderStyle.Single);
        para.getFormat().getBorders().setColor(Color.BLACK);

        //Save the document
        doc.saveToFile("AddBorder.docx", FileFormat.Docx_2013);
    }
}

Add Borders to Some Text in Word in Java

Tuesday, 16 August 2022 08:35

Java: Flatten Form Fields in PDF

Form fields are often used in PDF documents to collect information from users. In some cases, you may need to flatten form fields in a PDF. For instance, when you want to prevent other viewers from editing the information you entered in the form fields of a PDF questionnaire. This article will introduce how to flatten form fields in PDF in Java using Spire.PDF for Java.

Install Spire.PDF for Java

First of all, you need 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 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>10.3.4</version>
    </dependency>
</dependencies>
    

Flatten a Specific Form Field in PDF in Java

The following are the steps to flatten a specific form field in a PDF document using Spire.PDF for Java:

  • Initialize an instance of PdfDocument class.
  • Load a PDF document using PdfDocument.loadFromFile() method.
  • Get the form widget collection from the document.
  • Get a specific form field from the widget collection by its name or index through PdfFormWidget.getFieldsWidget().get() method.
  • Flatten the form field through PdfField.setFlatten() method.
  • Save the result document using PdfDocument.saveToFile() method.
  • Java
import com.spire.pdf.PdfDocument;
import com.spire.pdf.fields.PdfField;
import com.spire.pdf.widget.PdfFormWidget;

public class FlattenSpecificFormField {
    public static void main(String[] args){
        //Create a PdfDocument instance
        PdfDocument pdf = new PdfDocument();
        //Load a PDF document
        pdf.loadFromFile("Form.pdf");

        //Get the form widget collection
        PdfFormWidget formWidget = (PdfFormWidget)pdf.getForm();
        //Get a specific form field by its name
        PdfField form = formWidget.getFieldsWidget().get("Address");
        //Get a specific form field by its index
        //PdfField form = formWidget.getFieldsWidget().get(2);
        //Flatten the form
        form.setFlatten(true);

        //Save the result document
        pdf.saveToFile("FlattenSpecific.pdf");
    }
}

Java:  Flatten Form Fields in PDF

Flatten All Form Fields in PDF in Java

The following are the steps to flatten all the form fields in a PDF document using Spire.PDF for Java:

  • Initialize an instance of PdfDocument class.
  • Load a PDF document using PdfDocument.loadFromFile() method.
  • Flatten all the form fields in the document through PdfDocument.getForm().isFlatten() method.
  • Save the result document using PdfDocument.saveToFile() method.
  • Java
import com.spire.pdf.PdfDocument;

public class FlattenAllFormFields {
    public static void main(String[] args){        
        //Create a PdfDocument instance
        PdfDocument pdf = new PdfDocument();
        //Load a PDF document
        pdf.loadFromFile("Form.pdf");

        //Flatten all the forms in the document
        pdf.getForm().isFlatten(true);

        //Save the result document
        pdf.saveToFile("FlattenAll.pdf");
    }
}

Java:  Flatten Form Fields in PDF

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.

This article demonstrates how to insert images to table cells in a Word document using Spire.Doc for Java.

import com.spire.doc.AutoFitBehaviorType;
import com.spire.doc.Document;
import com.spire.doc.Section;
import com.spire.doc.Table;
import com.spire.doc.fields.DocPicture;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;

public class InsertImageToTableCell {

    public static void main(String[] args) throws FileNotFoundException {

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

        //Add a section
        Section section  = document.addSection();

        //Add a table
        Table table = section.addTable(true);
        table.resetCells(2,2);
        table.autoFit(AutoFitBehaviorType.Auto_Fit_To_Contents);

        //Load an image to InputStream
        InputStream inputStream = new FileInputStream("C:\\Users\\Administrator\\Desktop\\company-logo.png");
        
        //Insert the image to the cell(0,0)
        DocPicture picture = table.get(0,0).addParagraph().appendPicture(inputStream);
        
        //Set the width and height of the image
        picture.setWidth(100);
        picture.setHeight(100);

        //Insert another image to the cell(1,1)
        inputStream = new FileInputStream("C:\\Users\\Administrator\\Desktop\\intro.png");
        picture = table.get(1,1).addParagraph().appendPicture(inputStream);
        picture.setWidth(100);
        picture.setHeight(100);

        //Save the document
        document.saveToFile("InsertImgToCell.docx");
    }
}

Insert Images to a Table in Word in Java

Thursday, 09 June 2022 03:58

C#/VB.NET: Convert PDF to Excel

PDF is a versatile file format, but it is difficult to edit. If you want to modify and calculate PDF data, converting PDF to Excel would be an ideal solution. In this article, you will learn how to convert PDF to Excel in C# and VB.NET using Spire.PDF for .NET.

Install Spire.PDF for .NET

To begin with, you need to add the DLL files included in the Spire.PDF 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.PDF

Convert PDF to Excel in C# and VB.NET

The following are the steps to convert a PDF document to Excel:

  • Initialize an instance of PdfDocument class.
  • Load the PDF document using PdfDocument.LoadFromFile(filePath) method.
  • Save the document to Excel using PdfDocument.SaveToFile(filePath, FileFormat.XLSX) method.
  • C#
  • VB.NET
using Spire.Pdf;
using Spire.Pdf.Conversion;

namespace ConvertPdfToExcel
{
    class Program
    {
        static void Main(string[] args)
        {
            //Initialize an instance of PdfDocument class
            PdfDocument pdf = new PdfDocument();
            //Load the PDF document
            pdf.LoadFromFile("Sample.pdf");

            //Save the PDF document to XLSX
            pdf.SaveToFile("PdfToExcel.xlsx", FileFormat.XLSX);
        }
    }
}

C#/VB.NET: Convert PDF to Excel

Convert a Multi-Page PDF to One Excel Worksheet in C# and VB.NET

The following are the steps to covert a multi-page PDF to one Excel worksheet:

  • Initialize an instance of PdfDocument class.
  • Load the PDF document using PdfDocument.LoadFromFile(filePath) method.
  • Initialize an instance of XlsxLineLayoutOptions class, in the class constructor, setting the first parameter - convertToMultipleSheet as false.
  • Set PDF to XLSX convert options using PdfDocument.ConvertOptions.SetPdfToXlsxOptions(XlsxLineLayoutOptions) method.
  • Save the document to Excel using PdfDocument.SaveToFile(filePath, FileFormat.XLSX) method.
  • C#
  • VB.NET
using Spire.Pdf;
using Spire.Pdf.Conversion;

namespace ConvertPdfToExcel
{
    class Program
    {
        static void Main(string[] args)
        {
            //Initialize an instance of PdfDocument class
            PdfDocument pdf = new PdfDocument();
            //Load the PDF document
            pdf.LoadFromFile("Sample1.pdf");

            //Initialize an instance of XlsxLineLayoutOptions class, in the class constructor, setting the first parameter - convertToMultipleSheet as false.
            //The four parameters represent: convertToMultipleSheet, showRotatedText, splitCell, wrapText
            XlsxLineLayoutOptions options = new XlsxLineLayoutOptions(false, true, true, true);
            //Set PDF to XLSX convert options
            pdf.ConvertOptions.SetPdfToXlsxOptions(options);

            //Save the PDF document to XLSX
            pdf.SaveToFile("PdfToOneExcelSheet.xlsx", FileFormat.XLSX);
        }
    }
}

C#/VB.NET: Convert PDF to Excel

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.

Thursday, 02 July 2020 08:54

Create a Nested Table in Word in Java

This article demonstrates how to insert a nested table in a table cell using Spire.Doc for Java.

import com.spire.doc.*;

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

        //Create a Document object
        Document doc = new Document();
        
        //Add a section
        Section section = doc.addSection();

        //Add a table
        Table table = section.addTable(true);
        table.resetCells(2, 3);

        //Set column width
        table.getRows().get(0).getCells().get(0).setWidth(50f);
        table.getRows().get(0).getCells().get(2).setWidth(50f);
        table.getRows().get(1).getCells().get(0).setWidth(50f);
        table.getRows().get(1).getCells().get(2).setWidth(50f);
        table.autoFit(AutoFitBehaviorType.Auto_Fit_To_Window);

        //Insert content to cells
        table.get(0,0).addParagraph().appendText("SI.No.");
        String text = "Earthwork excavation for foundation of buildings, water supply, "
                + "sanitary lines and electrical conduits either in pits or in "
                + "trenches 1.5m and above in width, in ordinary soil not exceeding "
                + "1.5m in depth including dressing the bottom and sides of pits and  "
                + "trenches, stacking the excavated soil clear.";
        table.get(0,1).addParagraph().appendText(text);
        table.get(0,2).addParagraph().appendText("Qty");

        //Add a nested table to cell(0,1)
        Table nestedTable = table.get(0,1).addTable();
        nestedTable.resetCells(3, 4);
        nestedTable.autoFit(AutoFitBehaviorType.Auto_Fit_To_Contents);

        //Add content to the cells of nested table
        nestedTable.get(0,0).addParagraph().appendText("SI.No.");
        nestedTable.get(0,1).addParagraph().appendText("Item");
        nestedTable.get(0,2).addParagraph().appendText("Qty");
        nestedTable.get(0,3).addParagraph().appendText("Rate");
        nestedTable.get(1,0).addParagraph().appendText("1");
        nestedTable.get(1,1).addParagraph().appendText("Sand");
        nestedTable.get(1,2).addParagraph().appendText("30");
        nestedTable.get(1,3).addParagraph().appendText("45");
        nestedTable.get(2,0).addParagraph().appendText("2");
        nestedTable.get(2,1).addParagraph().appendText("Cement");
        nestedTable.get(2,2).addParagraph().appendText("30");
        nestedTable.get(2,3).addParagraph().appendText("50");

        //Save the document
        doc.saveToFile("NestedTable.docx", FileFormat.Docx_2013);
    }
}

Create a Nested Table in Word in Java

Friday, 14 January 2022 03:47

Java: Add or Delete Page Breaks in Excel

Page breaks in Excel are dividers that separate a large worksheet into individual pages for printing. In this article, you will learn how to add or delete page breaks in Excel in Java using Spire.XLS for Java library.

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>
    

Add Page Breaks to Excel in Java

Using Spire.XLS for Java, you can add horizontal and vertical page breaks to an Excel worksheet. Below are the steps to do so:

  • Create an instance of Workbook class.
  • Load an Excel file using Workbook.loadFromFile() method.
  • Get the desired worksheet by its index using Workbook.getWorksheets().get() method.
  • Specify the cells where you want to add page breaks to using Worksheet.getRange().get() method.
  • Add horizontal and vertical page breaks to the cells using Worksheet.getHPageBreaks().add() and Worksheet.getVPageBreaks().add() methods.
  • Set the sheet view mode to ViewMode.Preview using Worksheet.setViewMode() method.
  • Save the result file using Workbook.saveToFile() method.
  • Java
import com.spire.xls.*;

public class AddPageBreaks {
    public static void main(String []args) {
        //Create a Workbook instance
        Workbook workbook = new Workbook();
        //Load an Excel file
        workbook.loadFromFile("Sample.xlsx");

        //Get the first worksheet
        Worksheet sheet = workbook.getWorksheets().get(0);

        //Specify the cells where you want to add page breaks to
        CellRange cell1 = sheet.getRange().get("A10");
        CellRange cell2 = sheet.getRange().get("F1");

        //Add a horizontal page break
        sheet.getHPageBreaks().add(cell1);

        //Add a vertical page break
        sheet.getVPageBreaks().add(cell2);

        //Set view mode to Preview in order to view the page breaks
        sheet.setViewMode(ViewMode.Preview);

        //Save the result file
        workbook.saveToFile("AddPageBreaks.xlsx", ExcelVersion.Version2013);
    }
}

Java: Add or Delete Page Breaks in Excel

Delete a Specific Page Break from Excel in Java

The following are the steps to delete a specific page break from an Excel worksheet:

  • Create an instance of Workbook class.
  • Load an Excel file using Workbook.loadFromFile() method.
  • Get the desired worksheet by its index using Workbook.getWorksheets().get() method.
  • Delete a specific horizontal or vertical page break from the worksheet by its index using Worksheet.getHPageBreaks().removeAt() or Worksheet.getVPageBreaks().removeAt() method.
  • Save the result file using Workbook.saveToFile() method.
  • Java
import com.spire.xls.ExcelVersion;
import com.spire.xls.Workbook;
import com.spire.xls.Worksheet;

public class DeleteASpecificPageBreak {
    public static void main(String []args) {
        //Create a Workbook instance
        Workbook workbook = new Workbook();
        //Load an Excel file
        workbook.loadFromFile("AddPageBreaks.xlsx");

        //Get the first worksheet
        Worksheet sheet = workbook.getWorksheets().get(0);

        //Delete the first horizontal page break
        sheet.getHPageBreaks().removeAt(0);
        //Delete the first vertical page break
        sheet.getVPageBreaks().removeAt(0);

        //Save the result file
        workbook.saveToFile("DeleteASpecificPageBreaks.xlsx", ExcelVersion.Version2013);
    }
}

Delete All Page Breaks from Excel in Java

The following are the steps to delete all the page breaks from an Excel worksheet:

  • Create an instance of Workbook class.
  • Load an Excel file using Workbook.loadFromFile() method.
  • Get the desired worksheet by its index using Workbook.getWorksheets().get() method.
  • Delete all the horizontal and vertical page breaks from the worksheet using Worksheet.getHPageBreaks().clear() and Worksheet.getVPageBreaks().clear() methods.
  • Save the result file using Workbook.saveToFile() method.
  • Java
import com.spire.xls.ExcelVersion;
import com.spire.xls.Workbook;
import com.spire.xls.Worksheet;

public class DeleteAllPageBreaks {
    public static void main(String []args) {
        //Create a Workbook instance
        Workbook workbook = new Workbook();
        //Load an Excel file
        workbook.loadFromFile("AddPageBreaks.xlsx");

        //Get the first worksheet
        Worksheet sheet = workbook.getWorksheets().get(0);

        //Delete all horizontal page breaks
        sheet.getHPageBreaks().clear();
        //Delete all vertical page breaks
        sheet.getVPageBreaks().clear();

        //Save the result file
        workbook.saveToFile("DeleteAllPageBreaks.xlsx", ExcelVersion.Version2013);
    }
}

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.

This article demonstrates how to add, count, retrieve and remove variables in a Word document in Java using Spire.Doc for Java library.

Add a Variable

The following example adds a document variable named "A1" with a value of 12 to a Word document.

import com.spire.doc.Document;
import com.spire.doc.FieldType;
import com.spire.doc.FileFormat;
import com.spire.doc.Section;
import com.spire.doc.documents.Paragraph;

public class AddVariables {
    public static void main(String[] args){
        //Create a Document instance
        Document document = new Document();
        //Add a section
        Section section = document.addSection();

        //Add a paragraph to the section
        Paragraph paragraph = section.addParagraph();

        //Add a DocVariable field to the paragraph
        paragraph.appendField("A1", FieldType.Field_Doc_Variable);

        //Add a document variable to the DocVariable field
        document.getVariables().add("A1", "12");

        //Update fields in the document
        document.isUpdateFields(true);
        
        //Save the result document
        document.saveToFile("AddVariables.docx", FileFormat.Docx_2013);
    }
}

Add, Count, Retrieve and Remove Variables in Word in Java

Count the number of Variables

import com.spire.doc.Document;

public class CountVariables {
    public static void main(String[] args){
        //Load the Word document
        Document document = new Document();
        document.loadFromFile("AddVariables.docx");

        //Get the number of variables in the document
        int number = document.getVariables().getCount();

        StringBuilder content = new StringBuilder();
        content.append("The number of variables is: " + number);

        System.out.println(content.toString());
    }
}

Add, Count, Retrieve and Remove Variables in Word in Java

Retrieve Name and Value of a Variable

import com.spire.doc.Document;

public class RetrieveVariables {
    public static void main(String[] args){
        //Load the Word document
        Document document = new Document();
        document.loadFromFile("AddVariables.docx");

        //Retrieve the name of a variable by index
        String s1 = document.getVariables().getNameByIndex(0);

        //Retrieve the value of a variable by index
        String s2 = document.getVariables().getValueByIndex(0);

        //Retrieve the value of a variable by name
        String s3 = document.getVariables().get("A1");

        System.out.println("The name of the variable retrieved by index 0 is: " + s1);
        System.out.println("The value of the variable retrieved by index 0 is: " + s2);
        System.out.println("The value of the variable retrieved by name \"A1\" is: " + s3);
    }
}

Add, Count, Retrieve and Remove Variables in Word in Java

Remove a specific Variable

import com.spire.doc.Document;
import com.spire.doc.FileFormat;

public class RemoveVariables {
    public static void main(String[] args){
        //Load the Word document
        Document document = new Document();
        document.loadFromFile("AddVariables.docx");

        //Remove a variable by name
        document.getVariables().remove("A1");
        
        //Update fields in the document
        document.isUpdateFields (true);
        
        //Save the result document
        document.saveToFile("RemoveVariables.docx", FileFormat.Docx_2013);
    }
}

Word document editing restrictions are password-protected limitations set on a Word document to restrict the type of editing that can be performed on the document. By setting restrictions on Word documents, users can exercise control over who can modify their documents and to what extent. This ensures that the important information remains unchanged while enabling smooth collaboration among multiple contributors and efficient information collection from a large number of people. On the other hand, it is also important to unsetting the editing restrictions to correct errors, update information, or accommodate changes. This article shows how to set or unset editing restrictions on Word documents using Spire.Doc for Java through Java programs.

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

Set Editing Restrictions on Word Documents

Spire.Doc for Java supports setting four types of editing restrictions with a password on Word documents: no changes (read only), tracked changes, comments, and filling in forms. These editing restrictions can be set by using the Document.protect() method and some Enums.

Here is a list of the Enums to set the editing restrictions and their descriptions.

Enum Restriction Description
ProtectionType.Allow_Only_Reading No changes (read only) Allow reading only.
ProtectionType.Allow_Only_Revisions Tracked changes Allow tracked changes only.
ProtectionType.Allow_Only_Comments Comments Allow commenting only.
ProtectionType.Allow_Only_Form_Fields Filling in forms Allow filling in forms only.
ProtectionType.No_Protection No restriction Allow any editing.

The detailed step for setting editing restrictions with a password on a Word document are as follows:

  • Create an object of Document class.
  • Load a Word document using Document.loadFromFile() method.
  • Set the editing restrictions with a password using Document.protect() method.
  • Save the document using Document.saveToFIle() method.
  • Java
import com.spire.doc.Document;
import com.spire.doc.FileFormat;
import com.spire.doc.ProtectionType;

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

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

        //Set the restriction type to read-only and add a password
        doc.protect(ProtectionType.Allow_Only_Reading, "password");

        //Set the restriction type to comment-only and add a password
        //doc.protect(ProtectionType.Allow_Only_Comments, "password");

        //Set the restriction type to form-filling-only and add a password
        //doc.protect(ProtectionType.Allow_Only_Form_Fields, "password");

        //Set the restriction type to revision-only and add a password
        //doc.protect(ProtectionType.Allow_Only_Revisions, "password");

        //Save the document
        doc.saveToFile("EditingRestrictions.docx", FileFormat.Auto);
    }
}

Java: Set or Unset Editing Restrictions on Word Documents

Add Exceptions While Setting Editing Restrictions on Word Documents

Users can add exceptions (unrestricted areas) when setting editing restrictions on Word documents by inserting permission starting and ending tags. The details steps are as follows:

  • Create an object of Document class.
  • Load a Word document using Document.loadFromFile() method.
  • Create an object of PermissionStart class and an object of PermissionEnd class.
  • Get the first section using Document.getSections().get() method.
  • Insert the permission starting and ending tags to the paragraphs to set unrestricted areas.
  • Set editing restrictions with a password on the other areas using Document.protect() method.
  • Save the document using Document.saveToFile() method.
  • Java
import com.spire.doc.*;

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

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

        //Create the permission starting and ending tags
        PermissionStart start = new PermissionStart(doc, "permission1");
        PermissionEnd end = new PermissionEnd(doc, "permission1");

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

        //Insert the permission starting tag and the permission ending tag to the document
        section.getParagraphs().get(0).getChildObjects().insert(0,start);
        section.getParagraphs().get(5).getChildObjects().add(end);

        //Set the editing restrictions with a password
        doc.protect(ProtectionType.Allow_Only_Reading, "password");

        //Save the document
        doc.saveToFile("RestrictionExceptions.docx", FileFormat.Auto);
    }
}

Java: Set or Unset Editing Restrictions on Word Documents

Remove Editing Restrictions from Word Documents

Editing restrictions can be removed by setting the editing restrictions to allow any editing. The detailed steps are as follows:

  • Create an object of Document class.
  • Load a Word document using Document.loadFromFile() method.
  • Set the editing restrictions to allow any editing and remove the password using Document.protect() method.
  • If there are areas of exception, find the permission start tags and permission end tags and remove them.
  • Save the document using Document.saveToFile() method.
  • Java
import com.spire.doc.*;
import com.spire.doc.documents.Paragraph;

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

        //Load a Word document
        doc.loadFromFile("RegionalEditingRestrictions.docx");

        //Remove the editing restrictions
        doc.protect(ProtectionType.No_Protection);

        //Find permission starting tags and permission ending tags and remove them
        for(int j=0;j<doc.getSections().getCount();j++){
            //Get a section
            Section section=doc.getSections().get(j);
            for(int k=0;k<section.getParagraphs().getCount();k++){
                //Get a paragraph in a section
                Paragraph paragraph=section.getParagraphs().get(k);
                for(int i=0;i<paragraph.getChildObjects().getCount();){
                    //Get a child object of a paragraph
                    DocumentObject obj=paragraph.getChildObjects().get(i);
                    //Determine if a child object is an instance of PermissionStart or PermissionEnd class
                    if(obj instanceof PermissionStart||obj instanceof PermissionEnd){
                        //Remove the child object if it is
                        paragraph.getChildObjects().remove(obj);
                    }else{
                        i++;
                    }
                }
            }
        }

        //Save the document
        doc.saveToFile("NoRestrictions.docx", FileFormat.Auto);
    }
}

Java: Set or Unset Editing Restrictions on 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.

Monday, 22 June 2020 08:13

Java draw dash and solid line to PDF

This article will show you how to draw dash and solid line in Java applications.

import com.spire.pdf.*;
import com.spire.pdf.graphics.*;
import java.awt.*;

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

        //Create a new PdfDocument instance and add a new page
        PdfDocument pdf = new PdfDocument();
        PdfPageBase page = pdf.getPages().add();

        //Set location and size
        float x = 150;
        float y = 100;
        float width = 300;


        //Create pens
        PdfPen pen = new PdfPen(new PdfRGBColor(Color.red), 3f);
        PdfPen pen1 = new PdfPen(new PdfRGBColor(Color.blue), 1f);

        //Set dash style and pattern
        pen.setDashStyle(PdfDashStyle.Dash);
        pen.setDashPattern(new float[]{1, 1, 1});

        //Draw lines to the PDF page
        page.getCanvas().drawLine(pen, x, y, x + width, y);
        page.getCanvas().drawLine(pen1, x, y+50, x + width, y+50);

        //Save the document
        pdf.saveToFile("output/drawLines_out.pdf");
    }
}

Effective screenshot after adding dash and solid lines to PDF:

Java draw dash and solid line to PDF