Thursday, 04 January 2024 01:20

Java: Add or Remove Captions in Word Documents

Captions play multiple important roles in a document. They not only provide explanations for images or tables but also help in organizing the document structure, referencing specific content, and ensuring consistency and standardization. They serve as guides, summaries, and emphasis within the document, enhancing readability and assisting readers in better understanding and utilizing the information presented in the document. This article will demonstrate how to use Spire.Doc for Java to add or remove captions in Word documents within a Java project.

Install Spire.Doc for Java

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

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

Add Image Captions to a Word document in Java

By using the DocPicture.addCaption(String name, CaptionNumberingFormat format, CaptionPosition captionPosition) method, you can easily add descriptive captions to images within a Word document. The following are the detailed steps:

  • Create an object of the Document class.
  • Use the Document.addSection() method to add a section.
  • Add a paragraph using Section.addParagraph() method.
  • Use the Paragraph.appendPicture(String filePath) method to add a DocPicture image object to the paragraph.
  • Add a caption using the DocPicture.addCaption(String name, CaptionNumberingFormat format, CaptionPosition captionPosition) method, numbering the captions in CaptionNumberingFormat.Number format.
  • Update all fields using the Document.isUpdateFields(true) method.
  • Save the resulting document using the Document.saveToFile() method.
  • Java
import com.spire.doc.*;
import com.spire.doc.documents.*;
import com.spire.doc.fields.*;
public class addPictureCaption {
    public static void main(String[] args) {

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

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

        // Add a new paragraph and insert an image into it
        Paragraph pictureParagraphCaption = section.addParagraph();
        pictureParagraphCaption.getFormat().setAfterSpacing(10);
        DocPicture pic1 = pictureParagraphCaption.appendPicture("Data\\1.png");
        pic1.setHeight(100);
        pic1.setWidth(100);

        // Add a caption to the image
        CaptionNumberingFormat format = CaptionNumberingFormat.Number;
        pic1.addCaption("Image", format, CaptionPosition.Below_Item);

        // Add another paragraph and insert another image into it
        pictureParagraphCaption = section.addParagraph();
        DocPicture pic2 = pictureParagraphCaption.appendPicture("Data\\2.png");
        pic2.setHeight(100);
        pic2.setWidth(100);

        // Add a caption to the second image
        pic2.addCaption("Image", format, CaptionPosition.Below_Item);

        // Update all fields in the document
        document.isUpdateFields(true);

        // Save the document as a docx file
        String result = "AddImageCaption.docx";
        document.saveToFile(result, FileFormat.Docx_2016);

        // Close and dispose the document object to release resources
        document.close();
        document.dispose();
    }
}

Java: Add or Remove Captions in Word documents

Add Table Captions to a Word document in Java

Similar to adding captions to images, to add a caption to a table, you need to call the Table.addCaption(String name, CaptionNumberingFormat format, CaptionPosition captionPosition) method. The detailed steps are as follows:

  • Create an object of the Document class.
  • Use the Document.addSection() method to add a section.
  • Create a Table object and add it to the specified section in the document.
  • Use the Table.resetCells(int rowsNum, int columnsNum) method to set the number of rows and columns in the table.
  • Add a caption using the Table.addCaption(String name, CaptionNumberingFormat format, CaptionPosition captionPosition) method, numbering the captions in CaptionNumberingFormat.Number format.
  • Update all fields using the Document.isUpdateFields(true) method.
  • Save the resulting document using the Document.saveToFile() method.
  • Java
import com.spire.doc.*;
public class addTableCaption {
    public static void main(String[] args) {

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

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

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

        // Add a caption to the table
        tableCaption.addCaption("Table", CaptionNumberingFormat.Number, CaptionPosition.Below_Item);

        // Add another table to the section
        tableCaption = section.addTable(true);
        tableCaption.resetCells(2, 3);

        // Add a caption to the second table
        tableCaption.addCaption("Table", CaptionNumberingFormat.Number, CaptionPosition.Below_Item);

        // Update all fields in the document
        document.isUpdateFields(true);

        // Save the document as a docx file
        String result = "AddTableCaption.docx";
        document.saveToFile(result, FileFormat.Docx_2016);

        // Close and dispose the document object to release resources
        document.close();
        document.dispose();
    }
}

Java: Add or Remove Captions in Word documents

Remove Captions from a Word document in Java

In addition to adding captions, Spire.Doc for Java also supports deleting captions from a Word document. The steps involved are as follows:

  • Create an object of the Document class.
  • Use the Document.loadFromFile() method to load a Word document.
  • Create a custom method named DetectCaptionParagraph(Paragraph paragraph), to determine if the paragraph contains a caption.
  • Iterate through all the Paragraph objects in the document using a loop and use the custom method, DetectCaptionParagraph(Paragraph paragraph), to identify the paragraphs that contain captions and delete them.
  • Save the resulting document using the Document.saveToFile() method.
  • Java
import com.spire.doc.*;
import com.spire.doc.documents.*;
import com.spire.doc.fields.*;

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

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

        // Load the sample.docx file
        document.loadFromFile("Data/sample.docx");

        Section section;

        // Iterate through all sections
        for (int i = 0; i < document.getSections().getCount(); i++) {
            section = document.getSections().get(i);

        // Iterate through paragraphs in reverse order
            for (int j = section.getBody().getParagraphs().getCount() - 1; j >= 0; j--) {
                // Check if the paragraph is a caption paragraph
                if (DetectCaptionParagraph(section.getBody().getParagraphs().get(j))) {
                    // If it is a caption paragraph, remove it
                    section.getBody().getParagraphs().removeAt(j);
                }
            }
        }

        // Save the document after removing captions
        String result = "RemoveCaptions.docx";
        document.saveToFile(result, FileFormat.Docx_2016);

        // Close and dispose the document object to release resources
        document.close();
        document.dispose();
    }

    // Method to detect if a paragraph is a caption paragraph
    static Boolean DetectCaptionParagraph(Paragraph paragraph) {
        Boolean tag = false;
        Field field;

        // Iterate through child objects of the paragraph
        for (int i = 0; i < paragraph.getChildObjects().getCount(); i++) {
            if (paragraph.getChildObjects().get(i).getDocumentObjectType().equals(DocumentObjectType.Field)) {
                // Check if the child object is of type Field
                field = (Field) paragraph.getChildObjects().get(i);
                if (field.getType().equals(FieldType.Field_Sequence)) {
                    // Check if the Field type is FieldSequence, indicating a caption field
                    return true;
                }
            }
        }

        return tag;
    }
}

Java: Add or Remove Captions in Word documents

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

Published in Others

Spire.Doc for Java supports embedding an external file (Word, Excel, PowerPoint, PDF, picture, video, etc.) in Word documents as an OLE object. This article gives you an example of how to insert a PDF file into a Word document.

import com.spire.doc.Document;
import com.spire.doc.FileFormat;
import com.spire.doc.Section;
import com.spire.doc.documents.OleObjectType;
import com.spire.doc.documents.Paragraph;
import com.spire.doc.fields.DocOleObject;
import com.spire.doc.fields.DocPicture;

public class InsertOLE {

    public static void main(String[] args) {

        //Create a Document object and load a Word document
        Document doc = new Document();
        doc.loadFromFile("C:\\Users\\Administrator\\Desktop\\source.docx");

        //Get the last section
        Section section = doc.getLastSection();

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

        //Load an image which will be inserted to Word document representing the embedded file
        DocPicture pdfIcon = new DocPicture(doc);
        pdfIcon.loadImage("C:\\Users\\Administrator\\Desktop\\pdf-icon.jpg");

        //Insert a PDF file to the Word document as an OLE object
        par.appendOleObject("C:\\Users\\Administrator\\Desktop\\report.pdf", pdfIcon, OleObjectType.Adobe_Acrobat_Document);

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

Insert an External File into Word Documents in Java

Published in Others
Tuesday, 05 November 2019 09:15

Detect and remove Word Macros in Java

Spire.Doc load the word document with macros, it also supports to detect if a Word document contains VBA macros and remove all the VBA macros from a word document. This article demonstrates how to detect and remove VBA macros from Word document in Java applications.

Firstly, please view the sample document with macros:

Detect and remove Word Macros in Java

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


public class RemoveMacro {
    public static void main(String[] args) throws Exception {

        //Load the Sample Word document.
        Document doc = new Document();
        doc.loadFromFile("VBAMacros.docm");

        //If the document contains Macros, remove them from the document.
        if (doc.isContainMacro() )
        {
            doc.clearMacros();
        }

        //save to file
        doc.saveToFile("output/RemoveMacro.docm", FileFormat.Docm);

    }
}

Effective screenshot after clear the VBA macros from word document:

Detect and remove Word Macros in Java

Published in Others
Friday, 01 November 2024 03:29

Java: Create Barcodes in a Word Document

Creating barcodes in a Word document is a powerful way to enhance efficiency and organization. Barcodes streamline data management by enabling quick scanning and tracking, making them invaluable for businesses, events, and personal projects.

This article outlines two methods for generating barcodes in a Word document using Java: one method uses barcode fonts with Spire.Doc for Java, while the other utilizes Spire.Barcode for Java in conjunction with 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.10.3</version>
    </dependency>
</dependencies>
    

Create Barcodes in Word Documents Using Barcode Fonts

A barcode font is a special typeface designed to represent data in a format that can be scanned by barcode readers. Unlike standard fonts that display alphanumeric characters, barcode fonts convert text into a series of lines and spaces that make up a barcode.

To use a barcode font, you typically install the font on your system and then apply it to the text you want to convert into a barcode.

The steps to create barcodes in a Word document using barcode fonts are as follows:

  • Download and install the desired barcode font on your computer.
  • Create a Document object.
  • Load a Word file using Document.loadFromFile() method.
  • Get a specific section and add a paragraph using Section.addParagraph() method.
  • Add text to the paragraph using Paragraph.appendText() method.
  • Apply the barcode font to the text using TextRange.getCharacterFormat().setFontName() method.
  • Set the font size and color for the text.
  • Save the document to a different Word file.
  • Java
import com.spire.doc.Document;
import com.spire.doc.FileFormat;
import com.spire.doc.Section;
import com.spire.doc.documents.Paragraph;
import com.spire.doc.fields.TextRange;

import java.awt.*;

public class CreateBarcodeInWordUsingBarcodeFont {

    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");

        // Get a specific section
        Section section = document.getSections().get(0);

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

        // Append text to the paragraph
        TextRange txtRang = paragraph.appendText("Hello,World");

        // Apply barcode font to the text
        txtRang.getCharacterFormat().setFontName("Code 128");

        // Set the font size and text color
        txtRang.getCharacterFormat().setFontSize(80f);
        txtRang.getCharacterFormat().setTextColor(Color.black);

        // Save the document to a different Word file
        document.saveToFile("CreateBarcode.docx", FileFormat.Docx);

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

Java: Create Barcodes in a Word Document

Create Barcodes in Word Documents Using Barcode API

Spire.Barcode for Java is an API that enables you to easily generate barcode images with customizable options, including barcode type, data, size, and color. To use it, you need to download the library and add it as a dependency in your project.

Once the barcode image is created, you can insert it into a Word document using the Paragraph.appendPicture() method provided by Spire.Doc for Java.

The steps to create barcode in a Word document using a Barcode API are as follows:

  • Import Spire.Barcode for Java as a dependency in your project.
  • Create a BarcodeSettings object.
  • Specify the barcode type, data, width and other attributes using the methods under the BarcodeSettings object.
  • Generate a barcode image based on the settings using BarCodeGenerator.generateImage() method.
  • Create a Document object.
  • Load a Word file using Document.loadFromFile() method.
  • Get a specific section and add a paragraph using Section.addParagraph() method.
  • Add the barcode image to the paragraph using Paragraph.appendPicture() method.
  • Save the document to a different Word file.
  • Java
import com.spire.barcode.BarCodeGenerator;
import com.spire.barcode.BarCodeType;
import com.spire.barcode.BarcodeSettings;
import com.spire.barcode.QRCodeECL;
import com.spire.doc.Document;
import com.spire.doc.FileFormat;
import com.spire.doc.Section;
import com.spire.doc.documents.Paragraph;

import java.awt.image.BufferedImage;

public class CreateBarcodesInWordUsingAPI {

    public static void main(String[] args) {

        // Create a BarcodeSettings object
        BarcodeSettings settings = new BarcodeSettings();

        // Set barcode type
        settings.setType(BarCodeType.QR_Code);

        // Set barcode data
        settings.setData2D("Hello, World");

        // Set the other attributes of the barcode
        settings.setX(2f);
        settings.setQRCodeECL(QRCodeECL.H);
        settings.setShowText(false);
        settings.setLeftMargin(0f);
        settings.setRightMargin(0f);

        // Create a BarCodeGenerator object
        BarCodeGenerator generator = new BarCodeGenerator(settings);

        // Generate a barcode image
        BufferedImage image = generator.generateImage();

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

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

        // Get a specific section
        Section section = document.getSections().get(0);

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

        // Add the barcode image to the paragraph
        paragraph.appendPicture(image);

        // Save the document to a different Word file
        document.saveToFile("CreateBarcode.docx", FileFormat.Docx);

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

Java: Create Barcodes in 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 Others