'How to insert a link programmatically into PDPushButton to existing pdf using pdfbox / acro-form
The problem:
I have a pdf that I've created using Adobe acrobat pro. Inside the pdf I have several form buttons ("fields") which I want to dynamically insert them a web url link to enter when one's click a button.
what I've tried so far:
PDDocument doc = new PDDocument.load(pdf);
PDAcroForm acroForm = doc.getDocumentCatalog().getAcroForm();
PDPushButton b1 = acroForm.getField("Button1");
PDActionURI uri = new PDActionURI();
uri.setURI("https://stackoverflow.com");
PDFormFieldAdditionalActions actions = new PDFormFieldAdditionalActions();
actions.setF(uri);
b1.setActions(actions);
and -
PDDocument doc = new PDDocument.load(pdf);
PDAcroForm acroForm = doc.getDocumentCatalog().getAcroForm();
PDPushButton b1 = acroForm.getField("Button1");
PDActionURI uri = new PDActionURI();
uri.setURI("https://stackoverflow.com");
b1.getWidget().setAction(uri);
I haven't find any documentation on how to do it - so I've tried the above code based on reading their open source code and what I've understood from it.
I've also tried to use an action called PDActionGoTo but it has a function 'setDestination' which gets 'PDDestination' object, but I didn't understand how to initial it with a url.
I've found also someone with a similar problem - only that he created the button in the code instead of getting it from the pdf file. I didn't manage to make the adjustment but I will supply the code (he wrote that it worked for him eventually):
PDPushButton pb = new PDPushButton(acroForm);
pb.setPartialName("sbtn");
COSDictionary cosPush = pb.getCOSObject();
COSDictionary cosA = new COSDictionary();
cosPush.setInt(COSName.F, 4);
cosPush.setItem(COSName.A, cosA);
cosPush.setItem(COSName.P, page);
cosA.setInt(COSName.FLAGS, 256);
cosA.setName(COSName.S, "SubmitForm");
COSDictionary cosF = new COSDictionary();
cosA.setItem(COSName.F, cosF);
cosF.setString(COSName.F, "https://stackoverflow.com");
cosF.setName("FS", "URL");
// add the field to the acroform
acroForm.getFields().add(pb);
To see the original question go here
Also, does anyone knows what are those constants COSName.F/COSName.A/ect. meaning? is it part of the pdf acro-form specification? I tried to look it up but didn't find any helpful information about it, beside that it looks like everyone that asked about pdfbox before somehow already knows it.
about the environment:
java 8
pdfbox version 2.0.22
adobe acrobat pro version 2022.001.20112
thanks for the help : )
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
