Java: Create Barcodes in a Word Document

2024-11-01 03:29:00 Written by Koohji

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>14.4.0</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.

This article demonstrates how to replace text in an exising PowerPoint document with new text using Spire.Presentation for Java.

import com.spire.presentation.*;

import java.util.HashMap;
import java.util.Map;

public class ReplaceText {

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

        //create a Presentation object
        Presentation presentation = new Presentation();

        //load the template file
        presentation.loadFromFile("C:\\Users\\Administrator\\Desktop\\input.pptx");

        //get the first slide
        ISlide slide= presentation.getSlides().get(0);

        //create a Map object
        Map map = new HashMap();

        //add several pairs of keys and values to the map
        map.put("#name#","John Smith");
        map.put("#age#","28");
        map.put("#address#","Oklahoma City, United States");
        map.put("#tel#","333 123456");
        map.put("#email#","johnsmith@outlook.com");

        //replace text in the slide
        replaceText(slide,map);

        //save to another file
        presentation.saveToFile("output/ReplaceText.pptx", FileFormat.PPTX_2013);
    }

    /**
     * Replace text within a slide
     * @param slide Specifies the slide where the replacement happens
     * @param map Where keys are existing strings in the document and values are the new strings to replace the old ones
     */
     public static void replaceText(ISlide slide, Map<String,String> map) {

        for (Object shape : slide.getShapes()
        ) {
            if (shape instanceof IAutoShape) {

                for (Object paragraph : ((IAutoShape) shape).getTextFrame().getParagraphs()
                ) {
                    ParagraphEx paragraphEx = (ParagraphEx)paragraph;
                    for (String key : map.keySet()
                    ) {
                        if (paragraphEx.getText().contains(key)) {

                            paragraphEx.setText(paragraphEx.getText().replace(key, map.get(key)));
                         }
                    }
                }
            }
        }
    }
}

Replace Text in PowerPoint in Java

Alternative text (Alt Text) can help people with vision or cognitive impairments understand shapes, pictures or other graphical content. This article demonstrates how to set and get the alternative text of a shape in a PowerPoint document using Spire.Presentation for Java.

Set alternative text

import com.spire.presentation.*;
import com.spire.presentation.drawing.FillFormatType;

import java.awt.*;
import java.awt.geom.Rectangle2D;

public class SetAltText {
    public static void main(String[] args) throws Exception {
        //instantiate a Presentation object
        Presentation ppt = new Presentation();

        //add a shape to the first slide
        IAutoShape shape = ppt.getSlides().get(0).getShapes().appendShape(ShapeType.TRIANGLE, new Rectangle2D.Double(115, 130, 100, 100));
        shape.getFill().setFillType(FillFormatType.SOLID);
        shape.getFill().getSolidColor().setColor(Color.orange);
        shape.getShapeStyle().getLineColor().setColor(Color.white);

        //set alt text (title and description) for the shape
        shape.setAlternativeTitle("Triangle");
        shape.setAlternativeText("This is a triangle.");

        //save the resultant document
        ppt.saveToFile("Output.pptx", FileFormat.PPTX_2013);
    }
}

Set and Get Alternative Text (Alt Text) of PowerPoint Shapes in Java

Get alternative text

import com.spire.presentation.*;

public class GetAltText {
    public static void main(String[] args) throws Exception {
        //load PowerPoint document
        Presentation ppt = new Presentation();
        ppt.loadFromFile("Output.pptx");

        //get the first shape in the first slide
        IShape shape = ppt.getSlides().get(0).getShapes().get(0);

        //get the alt text (title and description) of the shape
        String altTitle = shape.getAlternativeTitle();
        String altDescription = shape.getAlternativeText();

        System.out.println("Title: " + altTitle);
        System.out.println("Description: " + altDescription);
    }
}

Set and Get Alternative Text (Alt Text) of PowerPoint Shapes in Java

page 61