繁体   English   中英

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

[英]how to add javascript code to pdf using java which changes listbox content based on selected item of another listbox

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

我google了很多但找不到完整的例子。 请在下面看到我的代码,它创建了一个列表框,一个文本字段和一个签名字段。

    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 Entreprise individuelle','LU01'],['LU06Sociétéanonyme','LU06'],['LU14Sociétécivile' ,'LU14']],“+”'德国':[[ - - ',' - '],['DE201 Aktiengesellschaft','DE201'],['DE602 EV','DE602'],['DE205 Investmentaktiengesellschaft','DE205']],“+”'希腊':[[' - ',' - '],['GR906ΕταιρίαΠεριορισμένηςΕυθύνης/Etería','GR906'],['GR912Κοινοπραξία','GR912 '',['GR999Λοιπά','GR999']]};“;

// javascript for listbox 1

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 [event.value]);“ +“this.getField('signatureField')。display = display.hidden;” +“r.value =' - ';” +“}”;

// listbox 1的相关java代码

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

// javascript for listbox 2

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}”;

// listbox 2的相关java代码

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM