Ganeshja
Ganeshja

Reputation: 2765

How to set a value in PDF form using Java pdfbox api

I need to set a value for PDF form using JAVA pdacroform api

below the code for setting up a value for particular field in PDF file but it throws

Exception in thread "main" java.lang.NoClassDefFoundError: org/fontbox/afm/AFMParser

despite of adding fontbox-1.7.jar

can any one help me out pls

import java.io.IOException;

import org.pdfbox.pdmodel.interactive.form.PDAcroForm;
import org.pdfbox.pdmodel.interactive.form.PDField;

import org.pdfbox.pdmodel.PDDocument;
import org.pdfbox.pdmodel.PDDocumentCatalog;

import org.pdfbox.exceptions.COSVisitorException;

import org.pdfbox.examples.AbstractExample;

public class SetField extends AbstractExample {

    public void setField(PDDocument pdfDocument, String name, String value)
            throws IOException {
        PDDocumentCatalog docCatalog = pdfDocument.getDocumentCatalog();
        PDAcroForm acroForm = docCatalog.getAcroForm();
        PDField field = acroForm.getField(name);
        if (field != null) {
            field.setValue(value);
        } else {
            System.err.println("No field found with name:" + name);
        }

    }

    public static void main(String[] args) throws IOException,
            COSVisitorException {
        SetField setter = new SetField();
        setter.setField(args);
    }

    private void setField(String[] args) throws IOException,
            COSVisitorException {
        PDDocument pdf = null;
        try {
            if (args.length != 3) {
                usage();
            } else {
                SetField example = new SetField();

                pdf = PDDocument.load(args[0]);
                example.setField(pdf, args[1], args[2]);
                pdf.save(args[0]);
            }
        } finally {
            if (pdf != null) {
                pdf.close();
            }
        }
    }

    private static void usage() {
        System.err
                .println("usage: org.apache.pdfbox.examples.fdf.SetField <pdf-file> <field-name> <field-value>");
    }
}

Thanks

Upvotes: 1

Views: 10574

Answers (2)

mkl
mkl

Reputation: 95888

According to your comments to @user1951544's answer you seem to use a very old PdfBox version 0.7.3. This very likely is not cooperating well with the current FontBox jar. I would advice updating to the current state.

In that case you should also consider the other hard dependencies required by fontbox:

The main PDFBox component, pdfbox, has hard dependencies on the fontbox and jempbox components and the commons-logging library.

Upvotes: 1

zibi
zibi

Reputation: 3313

You are getting java.lang.NoClassDefFoundError because of missing jar with class definition.

You need to add FontBox jar to your classpath.

Upvotes: 5

Related Questions