簡體   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