javascript - 如何使用java将javascript代码添加到pdf,该代码根据另一个列表框的所选项目更改列表框内容

标签 javascript java pdf

我想通过java创建一个pdf文件,其中包含两个列表框。选择列表框 1 的项目应该修改列表框 2 的项目。我了解到这需要 JavaScript。我怎样才能用java编写这个代码呢?到目前为止我正在使用 pdfbox。

我用谷歌搜索了很多,但找不到完整的例子。请参阅下面我的代码,它创建了一个列表框、一个文本字段和一个签名字段。

    import org.apache.pdfbox.cos.COSName;
    import org.apache.pdfbox.pdmodel.*;
    import org.apache.pdfbox.pdmodel.common.PDRectangle;
    import org.apache.pdfbox.pdmodel.encryption.InvalidPasswordException;
    import org.apache.pdfbox.pdmodel.font.PDFont;
    import org.apache.pdfbox.pdmodel.font.PDType1Font;
    import org.apache.pdfbox.pdmodel.interactive.action.PDAction;
    import org.apache.pdfbox.pdmodel.interactive.action.PDActionJavaScript;
    import org.apache.pdfbox.pdmodel.interactive.action.PDAnnotationAdditionalActions;
    import org.apache.pdfbox.pdmodel.interactive.action.PDFormFieldAdditionalActions;
    import org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotationWidget;
    import org.apache.pdfbox.pdmodel.interactive.annotation.PDAppearanceDictionary;
    import org.apache.pdfbox.pdmodel.interactive.annotation.PDAppearanceStream;
    import org.apache.pdfbox.pdmodel.interactive.form.*;

    import java.awt.*;
    import java.io.File;
    import java.io.IOException;
    import java.util.Arrays;
    import java.util.List;


    public class PDFCreate {
public static void main(String[] args) {
    System.out.println("Creating pdf docoument including signature field");

    try {
    // Create a new document with an empty page.
        PDDocument document = new PDDocument();
        PDPage page = new PDPage(PDRectangle.A4);
        document.addPage(page);

        // Adobe Acrobat uses Helvetica as a default font and
        // stores that under the name '/Helv' in the resources dictionary
        PDFont font = PDType1Font.HELVETICA;
        PDResources resources = new PDResources();
        resources.put(COSName.getPDFName("Helv"), font);


        PDDocumentCatalog pdCatalog = document.getDocumentCatalog();

        PDAcroForm pdAcroForm = new PDAcroForm(document);
        pdCatalog.setAcroForm(pdAcroForm);

        pdAcroForm.setDefaultResources(resources);

        String defaultAppearanceString = "/Helv 0 Tf 0 g";
        pdAcroForm.setDefaultAppearance(defaultAppearanceString);


        PDTextField textBox = new PDTextField(pdAcroForm);
        textBox.setPartialName("newTextField");

        defaultAppearanceString = "/Helv 12 Tf 0 g";
        textBox.setDefaultAppearance(defaultAppearanceString);
        pdAcroForm.getFields().add(textBox);

        PDAnnotationWidget widget = textBox.getWidgets().get(0);
        PDRectangle rect = new PDRectangle(50, 750, 200, 50);
        widget.setRectangle(rect);
        widget.setPage(page);

        // make sure the annotation is visible on screen and paper
        widget.setPrinted(true);

        // Add the annotation to the page
        page.getAnnotations().add(widget);
        textBox.setValue("value in newly created text field");

        PDListBox pdListBox = new PDListBox(pdAcroForm);
        pdListBox.setPartialName("newListBox");
        List<String> displayList = Arrays.asList("option 1", "option 2", "option 3");
        List<String> exportList = Arrays.asList("option 1 key", "option 2 key", "option 3");
        pdListBox.setOptions(exportList, displayList );
        defaultAppearanceString = "/Helv 12 Tf 0 g";
        pdListBox.setDefaultAppearance(defaultAppearanceString);





        pdAcroForm.getFields().add(pdListBox);

        PDAnnotationWidget widget2 = pdListBox.getWidgets().get(0);
        PDRectangle rect2 = new PDRectangle(50, 680, 200, 50);
        widget2.setRectangle(rect2);
        widget2.setPage(page);

        // make sure the annotation is visible on screen and paper
        widget2.setPrinted(true);

        PDFormFieldAdditionalActions pdFormFieldAdditionalActions = new PDFormFieldAdditionalActions();
        PDActionJavaScript jsChangedAction = new PDActionJavaScript();
        jsChangedAction.setAction("app.alert(\"On 'change' action\")");

        pdFormFieldAdditionalActions.setC((PDAction) jsChangedAction);

        pdListBox.setActions(pdFormFieldAdditionalActions);


        // Add the annotation to the page
        page.getAnnotations().add(widget2);

        pdListBox.setValue("option 2 key");


        PDRectangle rect3 = new PDRectangle(50, 150, 200, 50);

        PDAppearanceDictionary appearanceDictionary = new PDAppearanceDictionary();
        PDAppearanceStream appearanceStream = new PDAppearanceStream(document);
        appearanceStream.setBBox(rect3.createRetranslatedRectangle());
        appearanceStream.setResources(resources);
        appearanceDictionary.setNormalAppearance(appearanceStream);
        PDPageContentStream contentStream = new PDPageContentStream(document, appearanceStream);
        contentStream.setStrokingColor(Color.BLACK);
        contentStream.setNonStrokingColor(Color.LIGHT_GRAY);
        contentStream.setLineWidth(2);
        contentStream.addRect(0, 0, rect3.getWidth(), rect3.getHeight());
        contentStream.fill();
        contentStream.moveTo(1 * rect3.getHeight() / 4, 1 * rect3.getHeight() / 4);
        contentStream.lineTo(2 * rect3.getHeight() / 4, 3 * rect3.getHeight() / 4);
        contentStream.moveTo(1 * rect3.getHeight() / 4, 3 * rect3.getHeight() / 4);
        contentStream.lineTo(2 * rect3.getHeight() / 4, 1 * rect3.getHeight() / 4);
        contentStream.moveTo(3 * rect3.getHeight() / 4, 1 * rect3.getHeight() / 4);
        contentStream.lineTo(rect3.getWidth() - rect3.getHeight() / 4, 1 * rect3.getHeight() / 4);
        contentStream.stroke();
        contentStream.setNonStrokingColor(Color.DARK_GRAY);
        contentStream.beginText();
        contentStream.setFont(font, rect3.getHeight() / 5);
        contentStream.newLineAtOffset(3 * rect3.getHeight() / 4, -font.getBoundingBox().getLowerLeftY() * rect3.getHeight() / 5000);
        contentStream.showText("Customer");
        contentStream.endText();
        contentStream.close();

        PDSignatureField signatureField = new PDSignatureField(pdAcroForm);
        signatureField.setPartialName("SignatureField");

        PDAnnotationWidget widget3 = signatureField.getWidgets().get(0);
        widget3.setAppearance(appearanceDictionary);
        widget3.setRectangle(rect3);
        widget3.setPage(page);

        page.getAnnotations().add(widget3);
        pdAcroForm.getFields().add(signatureField);


        PDFormFieldAdditionalActions pdFormAdditionalActions = new PDFormFieldAdditionalActions();
        String javaScript = "app.alert( {cMsg: 'this is an example', nIcon: 3,"
                + " nType: 0,cTitle: 'PDFBox Javascript example' } );";
        PDActionJavaScript PDAjavascript = new PDActionJavaScript(javaScript);


        pdFormAdditionalActions.setC(PDAjavascript);
        /*        PDActionJavaScript(PDAjavascript); */
        pdListBox.setActions(pdFormAdditionalActions);


                pdListBox.getActions().getCOSObject().addAll(pdFormAdditionalActions.getCOSObject());


        //document.getDocumentCatalog().setOpenAction(PDAjavascript);

        document.save("create from empty.pdf");

        for (PDField pdField : pdAcroForm.getFields()) {
            System.out.println(pdField.getFullyQualifiedName() + " " + pdField.getFieldType() + " " + pdField.getValueAsString());
        }
        document.close();

    } catch (IOException e) {
        e.printStackTrace();
    }

    }
    }

我的代码中更改的操作从未显示任何效果。更重要的是,我需要帮助来添加一个操作,该操作将根据第一个列表框的所选项目更改第二个列表框的条目。提前致谢!

最佳答案

//以下解决了问题:

//定义列表框内容。

String javaScript = "+ "this.getField('signatureField').display=display.hidden;"+ "var formReady = false;"+ "var anacredit = { '-': [['-', ' -']], "+ "'卢森堡': [[ '-', '-'], ['LU01 个体企业', 'LU01'],[ 'LU06 Société anonyme', 'LU06'] ,['LU14 Société Civile','LU14']] , "+ "'德国': [[ '-', '-'], ['DE201 Aktiengesellschaft', 'DE201'], ['DE602 EV', 'DE602'], ['DE205 Investmentaktiengesellschaft', 'DE205']], "+ "'希腊': [[ '-', '-'], ['GR906 Εταιρία Περιορισμένnς Ευθύνnς/Etería', 'GR906'], ['GR912 Κοινο πραία' , 'GR912'], ['GR999 Λοιπά', 'GR999']] };";

//列表框 1 的 JavaScript

String jsListBox0 = "var f = this.getField('domicilation');"+“var r = this.getField('legalForm');” + "console.println('dom' + f.value + 'lF' + r.value);"+ "if (event.willCommit)"+ "{ console.println('dom EC' + event.change + 'EV' + event.value + 'ECE' + event.changeEx); "+ "r.setItems( anacredit [事件.值] );"+ "this.getField('signatureField').display=display.hidden;"+“r.value='-';” +“}”;

//列表框1的相关java代码

jsKeylinesAction.setAction(jsListBox0); fieldActions.setK(jsKeylinesAction); domicilation.setActions(fieldActions);

//列表框 2 的 JavaScript

String jsListBox2 = "var lb = this.getField('legalForm'); var d = this.getField('domicilation');"+“var sf = this.getField('signatureField');” + "if (!event.willCommit) "+ "{ console.println('lF' + lb.value + 'EC' + event.change + 'EV' + event.value + 'ECE' + event.changeEx); ” + "if ((event.changeEx =='-') || (event.changeEx == null)) sf.display = display.hidden;"+ "else sf.display = display.visible}";

//列表框2的相关java代码

jsKeyStrokeAction.setAction(jsListBox2); fieldActions2.setK(jsKeyStrokeAction); legalForm.setActions(fieldActions2);

关于javascript - 如何使用java将javascript代码添加到pdf,该代码根据另一个列表框的所选项目更改列表框内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56331004/

相关文章:

java - 是否热衷于使用mp3spi获得mp3文件的持续时间?

java - 最多可容纳 N 个项目的 LIFO 数据结构

angularjs - 使用 Angular 下载 PDF

javascript - 使用 jquery 动态添加选项并更新 html 源

java - 如何使用z轴?

javascript - 如何在 MongoDB 中的数组元素的开头和结尾的字段中查找两个子字符串?

google-chrome - 从服务器收到重复的 header

c# - PDF阅读高亮文本(高亮注释)使用C#

javascript - 如何在js文件中动态获取字段id?

javascript - 将多个球体放在一个距离相同的动画中