您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

PDFBox按钮执行JavaScript以关闭文档

PDFBox按钮执行JavaScript以关闭文档

改进的答案,如OP自己的评论中所述,并且还包括后续问题的答案。

PDDocument doc = new PDDocument();
PDPage page = new PDPage();
doc.addPage(page);

COSDictionary acroFormDict = new COSDictionary();
PDAcroForm acroForm = new PDAcroForm(doc, acroFormDict);
doc.getDocumentCatalog().setAcroForm(acroForm);
acroForm.setFields(new ArrayList<>());

PDPushButton button = new PDPushButton(acroForm);
button.setPartialName("Btn1");

PDActionJavaScript actionJavaScript = new PDActionJavaScript("this.closeDoc();");
PDAnnotationAdditionalActions additionalActions = new PDAnnotationAdditionalActions();
additionalActions.setU(actionJavaScript);

// widget
PDAnnotationWidget widget = button.getWidgets().get(0);
widget.setActions(additionalActions);
widget.setRectangle(new PDRectangle(100, 700, 100, 50));

PDColor colourBlack = new PDColor(new float[] { 0, 0, 0 }, PDDeviceRGB.INSTANCE);
PDAppearancecharacteristicsDictionary fieldAppearance
        = new PDAppearancecharacteristicsDictionary(new COSDictionary());
fieldAppearance.setBorderColour(colourBlack);
widget.setAppearancecharacteristics(fieldAppearance);

// Create appearance
PDAppearanceDictionary appearanceDictionary = new PDAppearanceDictionary();
PDAppearanceStream appearanceStream = new PDAppearanceStream(doc);
appearanceStream.setResources(new PDResources());
try (PDPageContentStream cs = new PDPageContentStream(doc, appearanceStream))
{
    PDRectangle b@R_136_2419@ = new PDRectangle(widget.getRectangle().getWidth(), widget.getRectangle().getHeight());
    appearanceStream.setB@R_136_2419@(b@R_136_2419@);
    cs.setNonStrokingColor(0, 0, 0); // black
    cs.addRect(b@R_136_2419@.getLowerLeftX() + 0.5f, b@R_136_2419@.getLowerLeftY() + 0.5f, b@R_136_2419@.getWidth() - 1, b@R_136_2419@.getHeight() - 1);
    cs.stroke();

    // put some useful text
    cs.setFont(PDType1Font.HELVETICA, 20);
    cs.beginText();
    cs.newLineAtOffset(20, 20);
    cs.showText("Close");
    cs.endText();
}
appearanceDictionary.setNormalAppearance(appearanceStream);
widget.setAppearance(appearanceDictionary);

page.getAnnotations().add(widget);

acroForm.getFields().add(button);

doc.save("..../Button.pdf");
doc.close();
javascript 2022/1/1 18:26:39 有342人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶