Search code examples
pdfbuttonwidgetpdfbox

Insert button widget/annotation in PDF using PDFBox


I have been reading up and trying to use PDFBox (Java) to add widgets/annotations into PDF. This should have been a relatively simple task. I've tried numerous ways (one of them written below. Displays nothing) but I don't know what exactly I'm doing wrong here. Any help in this regard will be appreciated.

        //Creating PDF document object 
        PDDocument document = new PDDocument();    

        System.out.println("PDF created");
        
        PDPage page = new PDPage(PDRectangle.A4);
        document.addPage(page);

        PDAnnotationWidget buttonWidget = new PDAnnotationWidget();
        buttonWidget.setRectangle(new PDRectangle(100, 100, 100, 30)); // Set the button position and size
        buttonWidget.setPage(page);
        buttonWidget.setPrinted(true);

        // Set the button's action (e.g., JavaScript action)
        PDActionJavaScript javascript = new PDActionJavaScript("app.alert('Button Clicked!');");
        buttonWidget.setAction(javascript);

        // Create the appearance stream for the button widget
        PDAppearanceStream appearanceStream = createAppearanceStream(document, buttonWidget.getRectangle());
        PDAppearanceDictionary dict = new PDAppearanceDictionary();
        dict.setDownAppearance(appearanceStream);
        buttonWidget.setAppearance(dict);

        // Add the button widget to the page annotations
        List<PDAnnotation> annotations = page.getAnnotations();
        annotations.add(buttonWidget);
        page.setAnnotations(annotations);

document.save("C:\\Musaub\\Hp_Notebook\\Freelancing\\Jobs\\3d_Point_Cloud_Floorplan\\E57_Files\\Bundle_4\\Panoramas\\PDF 23-282_out.pdf");

        document.close();


Solution

  • Found the solution here thanks to Tilman's help: https://github.com/apache/pdfbox/blob/trunk/examples/src/main/java/org/apache/pdfbox/examples/interactive/form/CreatePushButton.java

    Gives a full example on how to do add a push button widget.