您可以使用PDFBox的像這樣的圖像外觀創建按鈕:
try ( InputStream resource = getClass().getResourceAsStream("2x2colored.png");
PDDocument document = new PDDocument() )
{
BufferedImage bufferedImage = ImageIO.read(resource);
PDImageXObject pdImageXObject = LosslessFactory.createFromImage(document, bufferedImage);
float width = 10 * pdImageXObject.getWidth();
float height = 10 * pdImageXObject.getHeight();
PDAppearanceStream pdAppearanceStream = new PDAppearanceStream(document);
pdAppearanceStream.setResources(new PDResources());
try (PDPageContentStream pdPageContentStream = new PDPageContentStream(document, pdAppearanceStream))
{
pdPageContentStream.drawImage(pdImageXObject, 0, 0, width, height);
}
pdAppearanceStream.setBBox(new PDRectangle(width, height));
PDPage page = new PDPage(PDRectangle.A4);
document.addPage(page);
PDAcroForm acroForm = new PDAcroForm(document);
document.getDocumentCatalog().setAcroForm(acroForm);
PDPushButton pdPushButton = new PDPushButton(acroForm);
pdPushButton.setPartialName("ImageButton");
List<PDAnnotationWidget> widgets = pdPushButton.getWidgets();
for (PDAnnotationWidget pdAnnotationWidget : widgets)
{
pdAnnotationWidget.setRectangle(new PDRectangle(50, 750, width, height));
pdAnnotationWidget.setPage(page);
page.getAnnotations().add(pdAnnotationWidget);
PDAppearanceDictionary pdAppearanceDictionary = pdAnnotationWidget.getAppearance();
if (pdAppearanceDictionary == null)
{
pdAppearanceDictionary = new PDAppearanceDictionary();
pdAnnotationWidget.setAppearance(pdAppearanceDictionary);
}
pdAppearanceDictionary.setNormalAppearance(pdAppearanceStream);
}
acroForm.getFields().add(pdPushButton);
document.save(new File(RESULT_FOLDER, "imageButton.pdf"));
}
(CreateImageButton.java測試testCreateSimpleImageButton
)
當你沒有提到任何版本的要求,我認爲你的意思是一目前的PDFBox 2.0.x.
來源
2016-10-23 18:13:35
mkl