如何使用Java pdfbox api设置PDF格式的值

Gan*_*hja 1 java pdf pdfbox

我需要使用JAVA pdacroform api为PDF表单设置一个值

在下面的代码中为PDF文件中的特定字段设置值,但它会抛出

线程"main"中的异常java.lang.NoClassDefFoundError:org/fontbox/afm/AFMParser

尽管添加了fontbox-1.7.jar

任何人都可以帮助我

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>");
    }
}
Run Code Online (Sandbox Code Playgroud)

谢谢

zib*_*ibi 5

你得到了java.lang.NoClassDefFoundError,因为缺少带有类定义的jar.

您需要将FontBox jar添加到类路径中.