Thursday, 16 March 2023 05:54

Java: Create a Fillable Form in Word

Word allows you to create forms that other people can use to enter information. Fillable forms are used for a variety of purposes. Human resources use forms to collect employee and consultant information. Marketing departments use forms to survey customer satisfaction with their products and services. Organizations use forms to register members, students, or clients. Some of the tools you will use when creating a form include:

  • Content Controls: The areas where users input information in a form.
  • Tables: Tables are used in forms to align text and form fields, and to create borders and boxes.
  • Protection: Allows users to populate fields but not to make changes to the rest of the document.

Content controls in Word are containers for content that let users build structured documents. A structured document controls where content appears within the document. There are basically ten types of content controls available in Word 2013. This article focuses on how to create a fillable form in Word consisting of the following seven common content controls using Spire.Doc for Java.

Content Control Description
Plain Text A text field limited to plain text, so no formatting can be included.
Rich Text A text field that can contain formatted text or other items, such as tables, pictures, or other content controls.
Picture Accepts a single picture.
Drop-Down List A drop-down list displays a predefined list of items for the user to choose from.
Combo Box A combo box enables users to select a predefined value in a list or type their own value in the text box of the control.
Check Box A check box provides a graphical widget that allows the user to make a binary choice: yes (checked) or no (not checked).
Date Picker Contains a calendar control from which the user can select a date.

Install Spire.Doc for Java

First of all, you're required to add the Spire.Doc.jar file as a dependency in your Java program. The JAR file can be downloaded from this link. If you use Maven, you can easily import the JAR file in your application by adding the following code to your project's pom.xml file.

<repositories>
    <repository>
        <id>com.e-iceblue</id>
        <name>e-iceblue</name>
        <url>https://repo.e-iceblue.com/nexus/content/groups/public/</url>
    </repository>
</repositories>
<dependencies>
    <dependency>
        <groupId>e-iceblue</groupId>
        <artifactId>spire.doc</artifactId>
        <version>12.11.0</version>
    </dependency>
</dependencies>
    

Create a Fillable Form in Word in Java

The StructureDocumentTagInline class provided by Spire.Doc for Java is used to create structured document tags for inline-level structures (DrawingML object, fields, etc.) in a paragraph. The SDTProperties property and the SDTContent property under this class shall be used to specify the properties and content of the current structured document tag. The following are the detailed steps to create a fillable form with content controls in Word.

  • Create a Document object.
  • Add a section using Document.addSection() method.
  • Add a table using Section.addTable() method.
  • Add a paragraph to a specific table cell using TableCell.addParagraph() method.
  • Create an instance of StructureDocumentTagInline class, and add it to the paragraph as a child object using Paragraph.getChildObjects().add() method.
  • Specify the properties and content of the structured document tag using the methods under the SDTProperties property and the SDTContent property of the StructureDocumentTagInline object. The type of the structured document tag is set through SDTProperties.setSDTType() method.
  • Prevent users from editing content outside form fields using Document.protect() method.
  • Save the document using Document.saveToFile() method.
  • Java
import com.spire.doc.*;
import com.spire.doc.documents.*;
import com.spire.doc.fields.DocPicture;
import com.spire.doc.fields.TextRange;

import java.util.Date;

public class CreateFillableForm {

    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(7, 2);

        //Add text to the cells of the first column
        Paragraph paragraph = table.getRows().get(0).getCells().get(0).addParagraph();
        paragraph.appendText("Plain Text Content Control");
        paragraph = table.getRows().get(1).getCells().get(0).addParagraph();
        paragraph.appendText("Rich Text Content Control");
        paragraph = table.getRows().get(2).getCells().get(0).addParagraph();
        paragraph.appendText("Picture Content Control");
        paragraph = table.getRows().get(3).getCells().get(0).addParagraph();
        paragraph.appendText("Drop-Down List Content Control");
        paragraph = table.getRows().get(4).getCells().get(0).addParagraph();
        paragraph.appendText("Check Box Content Control");
        paragraph = table.getRows().get(5).getCells().get(0).addParagraph();
        paragraph.appendText("Combo box Content Control");
        paragraph = table.getRows().get(6).getCells().get(0).addParagraph();
        paragraph.appendText("Date Picker Content Control");

        //Add a plain text content control to the cell (0,1)
        paragraph = table.getRows().get(0).getCells().get(1).addParagraph();
        StructureDocumentTagInline sdt = new StructureDocumentTagInline(doc);
        paragraph.getChildObjects().add(sdt);
        sdt.getSDTProperties().setSDTType(SdtType.Text);
        sdt.getSDTProperties().setAlias("Plain Text");
        sdt.getSDTProperties().setTag("Plain Text");
        sdt.getSDTProperties().isShowingPlaceHolder(true);
        SdtText text = new SdtText(true);
        text.isMultiline(false);
        sdt.getSDTProperties().setControlProperties(text);
        TextRange tr = new TextRange(doc);
        tr.setText("Click or tap here to enter text.");
        sdt.getSDTContent().getChildObjects().add(tr);

        //Add a rich text content control to the cell (1,1)
        paragraph = table.getRows().get(1).getCells().get(1).addParagraph();
        sdt = new StructureDocumentTagInline(doc);
        paragraph.getChildObjects().add(sdt);
        sdt.getSDTProperties().setSDTType(SdtType.Rich_Text);
        sdt.getSDTProperties().setAlias("Rich Text");
        sdt.getSDTProperties().setTag("Rich Text");
        sdt.getSDTProperties().isShowingPlaceHolder(true);
        text = new SdtText(true);
        text.isMultiline(false);
        sdt.getSDTProperties().setControlProperties(text);
        tr = new TextRange(doc);
        tr.setText("Click or tap here to enter text.");
        sdt.getSDTContent().getChildObjects().add(tr);

        //Add a picture content control to the cell (2,1)
        paragraph = table.getRows().get(2).getCells().get(1).addParagraph();
        sdt = new StructureDocumentTagInline(doc);
        paragraph.getChildObjects().add(sdt);
        sdt.getSDTProperties().setSDTType(SdtType.Picture);
        sdt.getSDTProperties().setAlias("Picture");
        sdt.getSDTProperties().setTag("Picture");
        SdtPicture sdtPicture = new SdtPicture();
        sdt.getSDTProperties().setControlProperties(sdtPicture);
        DocPicture pic = new DocPicture(doc);
        pic.loadImage("C:\\Users\\Administrator\\Desktop\\ChooseImage.png");
        sdt.getSDTContent().getChildObjects().add(pic);

        //Add a dropdown list content control to the cell(3,1)
        paragraph = table.getRows().get(3).getCells().get(1).addParagraph();
        sdt = new StructureDocumentTagInline(doc);
        sdt.getSDTProperties().setSDTType(SdtType.Drop_Down_List);
        sdt.getSDTProperties().setAlias("Dropdown List");
        sdt.getSDTProperties().setTag("Dropdown List");
        paragraph.getChildObjects().add(sdt);
        SdtDropDownList sddl = new SdtDropDownList();
        sddl.getListItems().add(new SdtListItem("Choose an item.", "1"));
        sddl.getListItems().add(new SdtListItem("Item 2", "2"));
        sddl.getListItems().add(new SdtListItem("Item 3", "3"));
        sddl.getListItems().add(new SdtListItem("Item 4", "4"));
        sdt.getSDTProperties().setControlProperties(sddl);
        tr = new TextRange(doc);
        tr.setText(sddl.getListItems().get(0).getDisplayText());
        sdt.getSDTContent().getChildObjects().add(tr);

        //Add two check box content controls to the cell (4,1)
        paragraph = table.getRows().get(4).getCells().get(1).addParagraph();
        sdt = new StructureDocumentTagInline(doc);
        paragraph.getChildObjects().add(sdt);
        sdt.getSDTProperties().setSDTType(SdtType.Check_Box);
        SdtCheckBox scb = new SdtCheckBox();
        sdt.getSDTProperties().setControlProperties(scb);
        tr = new TextRange(doc);
        sdt.getChildObjects().add(tr);
        scb.setChecked(false);
        paragraph.appendText(" Option 1");

        paragraph = table.getRows().get(4).getCells().get(1).addParagraph();
        sdt = new StructureDocumentTagInline(doc);
        paragraph.getChildObjects().add(sdt);
        sdt.getSDTProperties().setSDTType(SdtType.Check_Box);
        scb = new SdtCheckBox();
        sdt.getSDTProperties().setControlProperties(scb);
        tr = new TextRange(doc);
        sdt.getChildObjects().add(tr);
        scb.setChecked(false);
        paragraph.appendText(" Option 2");

        //Add a combo box content control to the cell (5,1)
        paragraph = table.getRows().get(5).getCells().get(1).addParagraph();
        sdt = new StructureDocumentTagInline(doc);
        paragraph.getChildObjects().add(sdt);
        sdt.getSDTProperties().setSDTType(SdtType.Combo_Box);
        sdt.getSDTProperties().setAlias("Combo Box");
        sdt.getSDTProperties().setTag("Combo Box");
        SdtComboBox cb = new SdtComboBox();
        cb.getListItems().add(new SdtListItem("Choose an item."));
        cb.getListItems().add(new SdtListItem("Item 2"));
        cb.getListItems().add(new SdtListItem("Item 3"));
        sdt.getSDTProperties().setControlProperties(cb);
        tr = new TextRange(doc);
        tr.setText(cb.getListItems().get(0).getDisplayText());
        sdt.getSDTContent().getChildObjects().add(tr);

        //Add a date picker content control to the cell (6,1)
        paragraph = table.getRows().get(6).getCells().get(1).addParagraph();
        sdt = new StructureDocumentTagInline(doc);
        paragraph.getChildObjects().add(sdt);
        sdt.getSDTProperties().setSDTType(SdtType.Date_Picker);
        sdt.getSDTProperties().setAlias("Date Picker");
        sdt.getSDTProperties().setTag("Date Picker");
        SdtDate date = new SdtDate();
        date.setCalendarType(CalendarType.Default);
        date.setDateFormat("yyyy.MM.dd");
        date.setFullDate(new Date());
        sdt.getSDTProperties().setControlProperties(date);
        tr = new TextRange(doc);
        tr.setText("Click or tap to enter a date.");
        sdt.getSDTContent().getChildObjects().add(tr);

        //Allow users to edit the form fields only
        doc.protect(ProtectionType.Allow_Only_Form_Fields, "permission-psd");

        //Save to file
        doc.saveToFile("output/WordForm.docx", FileFormat.Docx_2013);
    }
}

Java: Create a Fillable Form 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.

Published in Form Field
Thursday, 01 December 2022 07:14

Java: Add Document Properties to Word Documents

The properties of a document are a set of information about the document and its content, such as title, subject, author's name, manager, company, category, keywords (also known as tags), and comments. This information does not appear in the content of the document, but it can help you better search, sort, and filter files. In this article, you will learn how to add document properties to Word documents in Java using Spire.Doc for 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.11.0</version>
    </dependency>
</dependencies>
    

Add Built-in Document Properties to a Word Document in Java

A built-in document property (also known as a standard document property) consists of a name and a value. You cannot set or change the name of a built-in document property as it’s predefined by Microsoft Word, but you can set or change its value. The following steps demonstrate how to set values for built-in document properties in a Word document in Java using Spire.Doc for Java:

  • Initialize an instance of Document class.
  • Load a Word document using Document.loadFromFile() method.
  • Access the built-in document properties of the document using Document.getBuiltinDocumentProperties() method.
  • Set the values of specific document properties such as title, subject and author using setTitle(), setSubject() and setAuthor() methods provided by BuiltinDocumentProperties class.
  • Save the result document using Document.saveToFile() method.
  • Java
import com.spire.doc.BuiltinDocumentProperties;
import com.spire.doc.Document;
import com.spire.doc.FileFormat;

public class AddBuiltinDocumentProperties {
    public static void main(String []args) throws Exception {
        //Create a Document instance
        Document document = new Document();
        //Load a Word document
        document.loadFromFile("Sample.docx");

        //Access the built-in document properties of the document
        BuiltinDocumentProperties standardProperties = document.getBuiltinDocumentProperties();
        //Set the values of specific built-in document properties 
        standardProperties.setTitle("Add Document Properties");
        standardProperties.setSubject("Java Example");
        standardProperties.setAuthor("James");
        standardProperties.setCompany("Eiceblue");
        standardProperties.setManager("Michael");
        standardProperties.setCategory("Document Manipulation");
        standardProperties.setKeywords("Java, Word, Document Properties");
        standardProperties.setComments("This article shows how to add document properties");

        //Save the result document
        document.saveToFile("AddStandardDocumentProperties.docx", FileFormat.Docx_2013);
    }
}

Java: Add Document Properties to Word Documents

Add Custom Document Properties to a Word Document in Java

A custom document property can be defined by a document author or user. Each custom document property should contain a name, a value and a data type. The data type can be one of these four types: Text, Date, Number and Yes or No. The following steps demonstrate how to add custom document properties with different data types to a Word document in Java using Spire.Doc for Java:

  • Initialize an instance of Document class.
  • Load a Word document using Document.loadFromFile() method.
  • Access the custom document properties of the document using Document.getCustomDocumentProperties() method.
  • Add custom document properties with different data types to the document using CustomDocumentProperties.add(String, Object) method.
  • Save the result document using Document.saveToFile() method.
  • Java
import com.spire.doc.CustomDocumentProperties;
import com.spire.doc.Document;
import com.spire.doc.FileFormat;

import java.util.Date;

public class AddCustomDocumentProperties {
    public static void main(String []args) throws Exception {
        //Create a Document instance
        Document document = new Document();
        //Load a Word document
        document.loadFromFile("Sample.docx");

        //Access the custom document properties of the document
        CustomDocumentProperties customProperties = document.getCustomDocumentProperties();
        //Add custom document properties with different data types to the document
        customProperties.add("Document ID", 1);
        customProperties.add("Authorized", true);
        customProperties.add("Authorized By", "John Smith");
        customProperties.add("Authorized Date", new Date());

        //Save the result document
        document.saveToFile("AddCustomDocumentProperties.docx", FileFormat.Docx_2013);
    }
}

Java: Add Document Properties to 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.

Published in Document Operation
Monday, 04 July 2022 09:15

Java: Merge Word Documents

Sometimes we need to merge several related Word documents to make a more complete one. To merge documents with MS Word, you need to manually copy and paste contents or import contents from other documents, which can be tedious. Luckily, Spire.Doc for Java provides 2 easy ways to merge Word documents by programming. This article will show the detailed steps to merge Word documents.

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

Merge Documents by Inserting the Entire File

The method Document.insertTextFromFile() provided by Spire.Doc allows merging Word documents by inserting other documents entirely into a document with the inserted contents starting from a new page.

The detailed steps of merging documents by inserting the entire file are as follows:

  • Create an object of Document class and load a Word document from disk.
  • Insert another Word document entirely to the loaded document using Document.insertTextFromFile() method.
  • Save the result document using Document.saveToFile() method.
  • Java
import com.spire.doc.*;

public class merge {
    public static void main(String[] args) {
        //Create an object of Document and load a Word document from disk
        Document document = new Document("C:/Samples/Sample1.docx");

        //Insert another Word document entirely to the document
        document.insertTextFromFile("C:/Samples/Sample2.docx", FileFormat.Docx_2013);

        //Save the result document
        document.saveToFile("MergingResult.docx", FileFormat.Docx_2013);
    }
}

Java: Merge Word Documents

Merge Documents by Cloning Contents

If you want to merge documents without starting a new page, you can clone the contents of other documents to add to the end of a document.

The detailed steps of merging documents by cloning contents are as follows:

  • Create two objects of Document and load the two Word documents from disk.
  • Loop through the second document to get all the sections using Document.getSections() method, then loop through all the sections to get their child objects using Section.getBod().getChildObjects() method, then get the last section of the first document using Document.getLastSection() method, and then add the child objects to the last section of the first document using Body.getChildObjects().add() method.
  • Save the result document using Document.saveToFile() method.
  • Java
import com.spire.doc.*;

public class mergeDocuments {
    public static void main(String[] args){
        //Create two Document objects and load two Word documents from disk
        Document document1 = new Document("C:/Samples/Sample1.docx");
        Document document2 = new Document("C:/Samples/Sample2.docx");

        //Loop through the second document to get all the sections
        for (Object sectionObj : (Iterable) document2.getSections()) {
            Section sec=(Section)sectionObj;
            //Loop through the sections of the second document to get their child objects
            for (Object docObj :(Iterable ) sec.getBody().getChildObjects()) {
                DocumentObject obj=(DocumentObject)docObj;

                //Get the last section of the first document
                Section lastSection = document1.getLastSection();

                //Add the child objects to the last section of the first document
                Body body = lastSection.getBody();
                body.getChildObjects().add(obj.deepClone());
            }
        }

        //Save the result document
        document1.saveToFile("MergingResult.docx", FileFormat.Docx_2013);
    }
}

Java: Merge 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.

Published in Document Operation
Wednesday, 17 April 2024 05:53

Java: Print Word Documents

Printing Word documents is a fundamental aspect of document management, allowing you to transform digital files into tangible, physical copies. Whether you need to produce hard copies for reference, distribution, or archival purposes, the ability to print Word documents is a valuable skill that remains relevant in various professional and personal settings.

In this article, you will learn how to print Word documents in Java using the Spire.Doc for Java library and java.awt.print package.

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

Print Word with the Default Printer in Java

Printing Word documents with the default printer is a convenient and straightforward method. This approach is often suitable for regular printing tasks when specific printer settings are not necessary or when users prefer to utilize the default configurations set in their printer.

The following are the steps to print Word documents with the default printer using Spire.Doc for Java and java.awt.print.

  • Create a PrinterJob object, and call the methods under it to set up a print job.
  • Create a Document object, and load a Word document using Document.LoadFromFile() method.
  • Render each page of the document in the specified format using PrinterJob.setPrintable() method.
  • Call PrinterJob.print() method to print the Word document.
  • Java
import com.spire.doc.Document;

import java.awt.print.PageFormat;
import java.awt.print.Paper;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;

public class PrintWithDefaultPrinter {

    public static void main(String[] args) {

        // Create a Document object
        Document document = new Document();
        
        // Load a Word file
        document.loadFromFile("C:\\Users\\Administrator\\Desktop\\Input.docx");

        // Create a PrinterJob object
        PrinterJob printerJob = PrinterJob.getPrinterJob();

        // Create a PageFormat object and set it to the default size and orientation
        PageFormat pageFormat = printerJob.defaultPage();

        // Return a copy of the Paper object associated with this PageFormat
        Paper paper = pageFormat.getPaper();

        // Set the imageable area of this Paper
        paper.setImageableArea(0, 0, pageFormat.getWidth(), pageFormat.getHeight());

        // Set the number of copies to be printed
        printerJob.setCopies(1);

        // Set the Paper object for this PageFormat
        pageFormat.setPaper(paper);

        // Call painter to render the pages in the specified format
        printerJob.setPrintable(document, pageFormat);

        // Print document
        try {
            printerJob.print();
        } catch (PrinterException e) {
            e.printStackTrace();
        }
    }
}

Print Word with a Specified Printer in Java

Printing a Word document with a specified printer in Java allows you to choose a specific printer device to handle the printing task. This approach can be useful in scenarios where you have multiple printers available and want to direct the print output to a specific one.

The following are the steps to print Word documents with a specified printer using Spire.Doc for Java and java.awt.print.

  • Create a PrinterJob object, and call the methods under it to set up a print job.
  • Find the print service by the printer name using the custom method findPrintService().
  • Apply the print service using PrinterJob.setPrintService() method.
  • Create a Document object, and load a Word document using Document.LoadFromFile() method.
  • Render each page of the document in the specified format using PrinterJob.setPrintable() method.
  • Call PrinterJob.print() method to print the Word document.
  • Java
import com.spire.doc.Document;

import javax.print.PrintService;
import java.awt.print.PageFormat;
import java.awt.print.Paper;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;

public class PrintWithSpecifiedPrinter {

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

        // Create a PrinterJob object which is initially associated with the default printer
        PrinterJob printerJob = PrinterJob.getPrinterJob();

        // Specify printer name
        PrintService myPrintService = findPrintService("\\\\192.168.1.104\\HP LaserJet P1007");
        printerJob.setPrintService(myPrintService);

        // Create a PageFormat instance and set it to a default size and orientation
        PageFormat pageFormat = printerJob.defaultPage();

        // Return a copy of the Paper object associated with this PageFormat.
        Paper paper = pageFormat.getPaper();

        // Set the imageable area of this Paper.
        paper.setImageableArea(0, 0, pageFormat.getWidth(), pageFormat.getHeight());

        // Set the Paper object for this PageFormat.
        pageFormat.setPaper(paper);

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

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

        // Call painter to render the pages in the specified format
        printerJob.setPrintable(document, pageFormat);

        // Print document
        try {
            printerJob.print();
        } catch (PrinterException e) {
            e.printStackTrace();
        }
    }

    // Find print service
    private static PrintService findPrintService(String printerName) {

        PrintService[] printServices = PrinterJob.lookupPrintServices();
        for (PrintService printService : printServices) {
            if (printService.getName().equals(printerName)) {
                return printService;
            }
        }
        return null;
    }
}

Print Word with a Print Dialog Box in Java

Printing a Word document with a print dialog box enables users to select a printer and customize print settings before initiating the process. By presenting a print dialog box, you provide users with flexibility and control over the printing operation.

To print Word document with a print dialog box in Java, follow these step:

  • Create a PrinterJob object, and call methods under it to set up a print job.
  • Create a Document object, and load a Word document using Document.LoadFromFile() method.
  • Render each page of the document in the specified format using PrinterJob.setPrintable() method.
  • Call PrinterJob.printDialog() method to display print dialog.
  • Call PrinterJob.print() method to print the Word document.
  • Java
import com.spire.doc.Document;

import java.awt.print.PageFormat;
import java.awt.print.Paper;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;

public class PrintWithDialogBox {

    public static void main(String[] args) {

        // Create a PrinterJob object which is initially associated with the default printer
        PrinterJob printerJob = PrinterJob.getPrinterJob();

        // Create a PageFormat object and set it to a default size and orientation
        PageFormat pageFormat = printerJob.defaultPage();

        // Return a copy of the Paper object associated with this PageFormat
        Paper paper = pageFormat.getPaper();

        // Set the imageable area of this Paper
        paper.setImageableArea(0, 0, pageFormat.getWidth(), pageFormat.getHeight());

        // Set the Paper object for this PageFormat
        pageFormat.setPaper(paper);

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

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

        // Call painter to render the pages in the specified format
        printerJob.setPrintable(document, pageFormat);

        // Display the print dialog
        if (printerJob.printDialog()) {
            try {
		
// Print document
                printerJob.print();
            } catch (PrinterException e) {
                e.printStackTrace();
            }
        }
    }
}

Print a Range of Pages in Word in Java

Printing a range of pages in Microsoft Word is a useful feature that allows you to select specific pages from a document and print only those pages, rather than printing the entire document. This can be particularly handy when you're working with lengthy documents or when you only need to print a specific section.

The steps to set print range while printing Word documents in Java are as follows.

  • Create a PrinterJob object, and call the methods under it to set up a print job.
  • Create a Document object, and load a Word document using Document.LoadFromFile() method.
  • Render each page of the document in the specified format using PrinterJob.setPrintable() method.
  • Create a PrintRequestAttributeSet object, and add the print range to the attribute set.
  • Call PrinterJob.print() method to print the range of pages.
  • Java
import com.spire.doc.Document;

import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.PrintRequestAttributeSet;
import javax.print.attribute.standard.PageRanges;
import java.awt.print.PageFormat;
import java.awt.print.Paper;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;

public class PrintPageRange {

    public static void main(String[] args) {

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

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

        // Create a PrinterJob object
        PrinterJob printerJob = PrinterJob.getPrinterJob();

        // Create a PageFormat object and set it to the default size and orientation
        PageFormat pageFormat = printerJob.defaultPage();

        // Return a copy of the Paper object associated with this PageFormat
        Paper paper = pageFormat.getPaper();

        // Set the imageable area of this Paper
        paper.setImageableArea(0, 0, pageFormat.getWidth(), pageFormat.getHeight());

        // Set the number of copies
        printerJob.setCopies(1);

        // Set the Paper object for this PageFormat
        pageFormat.setPaper(paper);

        // Call painter to render the pages in the specified format
        printerJob.setPrintable(document, pageFormat);
        
        // Create a PrintRequestAttributeSet object
        PrintRequestAttributeSet attributeSet = new HashPrintRequestAttributeSet();

        // Set print range
        attributeSet.add(new PageRanges(1,5));
        
        // Print document
        try {
            printerJob.print(attributeSet);
        } catch (PrinterException e) {
            e.printStackTrace();
        }
    }
}

Print Word in Duplex Mode in Java

Duplex printing, also known as two-sided printing, allows you to print on both sides of a sheet of paper automatically, which can be beneficial for lengthy reports, presentations, or handouts.

The steps to print Word documents in duplex mode in Java are as follows.

  • Create a PrinterJob object, and call the methods under it to set up a print job.
  • Create a Document object, and load a Word document using Document.LoadFromFile() method.
  • Render each page of the document in the specified format using PrinterJob.setPrintable() method.
  • Create a PrintRequestAttributeSet object, and add the two-sided printing mode to the attribute set.
  • Call PrinterJob.print() method to print the Word document.
  • Java
import com.spire.doc.Document;

import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.PrintRequestAttributeSet;
import javax.print.attribute.standard.Sides;
import java.awt.print.PageFormat;
import java.awt.print.Paper;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;

public class PrintInDuplexMode {

    public static void main(String[] args) {

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

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

        // Create a PrinterJob object which is initially associated with the default printer
        PrinterJob printerJob = PrinterJob.getPrinterJob();

        // Create a PageFormat object and set it to a default size and orientation
        PageFormat pageFormat = printerJob.defaultPage();

        // Return a copy of the Paper object associated with this PageFormat
        Paper paper = pageFormat.getPaper();

        // Set the imageable area of this Paper
        paper.setImageableArea(0, 0, pageFormat.getWidth(), pageFormat.getHeight());

        // Set the Paper object for this PageFormat
        pageFormat.setPaper(paper);

        // Call painter to render the pages in the specified format
        printerJob.setPrintable(document, pageFormat);

        // Create a PrintRequestAttributed object
        PrintRequestAttributeSet attributeSet = new HashPrintRequestAttributeSet();

        // Enable duplex printing mode
        attributeSet.add(Sides.TWO_SIDED_SHORT_EDGE);

        // Print document
        try {
            printerJob.print(attributeSet);
        } catch (PrinterException e) {
            e.printStackTrace();
        }
    }
}

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.

Published in Print
Wednesday, 22 June 2022 08:26

Java: Create a Word Document

The Word file format was invented by Microsoft and has gradually become irreplaceable. Most printed and digital publications, reports, brochures and resumes that we've seen were created with Word. In this article, you will learn how to programmatically create a Word document in Java using Spire.Doc for Java.

The Document class provided by Spire.Doc for Java represents a document model, which is used to create a Word document from scratch or load an existing Word file for further modification. A Word document must contain at least one section (represented by Section class) and each section is a container for basic Word elements like paragraphs, tables, headers, footers and so on. Below is a list of the key classes and methods covered in this tutorial.

Member Description
Document class Represents a Word document model.
Section class Represents a section in a Word document.
Paragraph class Represents a paragraph in a section.
ParagraphStyle class Defines the font formatting information that can be applied to a paragraph.
Section.addParagraph() method Adds a paragraph to a section.
Paragraph.appendText() method Appends text to a paragraph at the end.
Paragraph.applyStyle() method Applies a style to a paragraph.
Document.saveToFile() method Saves the document to a Word file with an extension of .doc or .docx. This method also supports saving the document to PDF, XPS, HTML, PLC, etc.

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

Create a Simple Word Document in Java

The following are the steps to create a simple Word document containing several paragraphs by using Spire.Doc for Java.

  • Create a Document object.
  • Add a section using Document.addSection() method.
  • Set the page margins using Section.getPageSetup().setMargins() method.
  • Add several paragraphs to the section using Section.addParagraph() method.
  • Add text to the paragraphs using Paragraph.appendText() method.
  • Create ParagraphStyle objects, and apply them to separate paragraphs using Paragraph.applyStyle() method.
  • Save the document to a Word file using Document.saveToFile() method.
  • Java
import com.spire.doc.Document;
import com.spire.doc.FileFormat;
import com.spire.doc.Section;
import com.spire.doc.documents.HorizontalAlignment;
import com.spire.doc.documents.Paragraph;
import com.spire.doc.documents.ParagraphStyle;

import java.awt.*;

public class CreateWordDocument {

    public static void main(String[] args) {

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

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

        //Set the page margins
        section.getPageSetup().getMargins().setAll(40f);

        //Add a paragraph as title
        Paragraph titleParagraph = section.addParagraph();
        titleParagraph.appendText("Introduction of Spire.Doc for Java");

        //Add two paragraphs as body
        Paragraph bodyParagraph_1 = section.addParagraph();
        bodyParagraph_1.appendText("Spire.Doc for Java is a professional Word API that empowers Java applications to " +
                "create, convert, manipulate and print Word documents without dependency on Microsoft Word.");

        Paragraph bodyParagraph_2 = section.addParagraph();
        bodyParagraph_2.appendText("By using this multifunctional library, developers are able to process copious tasks " +
                "effortlessly, such as inserting image, hyperlink, digital signature, bookmark and watermark, setting " +
                "header and footer, creating table, setting background image, and adding footnote and endnote.");

        //Create and apply a style for title paragraph
        ParagraphStyle style1 = new ParagraphStyle(doc);
        style1.setName("titleStyle");
        style1.getCharacterFormat().setBold(true);;
        style1.getCharacterFormat().setTextColor(Color.BLUE);
        style1.getCharacterFormat().setFontName("Times New Roman");
        style1.getCharacterFormat().setFontSize(12f);
        doc.getStyles().add(style1);
        titleParagraph.applyStyle("titleStyle");

        //Create and apply a style for body paragraphs
        ParagraphStyle style2 = new ParagraphStyle(doc);
        style2.setName("paraStyle");
        style2.getCharacterFormat().setFontName("Times New Roman");
        style2.getCharacterFormat().setFontSize(12);
        doc.getStyles().add(style2);
        bodyParagraph_1.applyStyle("paraStyle");
        bodyParagraph_2.applyStyle("paraStyle");

        //Set the horizontal alignment of paragraphs
        titleParagraph.getFormat().setHorizontalAlignment(HorizontalAlignment.Center);
        bodyParagraph_1.getFormat().setHorizontalAlignment(HorizontalAlignment.Justify);
        bodyParagraph_2.getFormat().setHorizontalAlignment(HorizontalAlignment.Justify);

        //Set the first line indent
        bodyParagraph_1.getFormat().setFirstLineIndent(30) ;
        bodyParagraph_2.getFormat().setFirstLineIndent(30);

        //Set the after spacing
        titleParagraph.getFormat().setAfterSpacing(10);
        bodyParagraph_1.getFormat().setAfterSpacing(10);

        //Save to file
        doc.saveToFile("WordDocument.docx", FileFormat.Docx_2013);
        doc.close();
    }
}

Java: Create 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.

Published in Document Operation
Page 3 of 3