我正在寻找一种方法将PDF文件中按钮字段的正常外观设置为图像文件,但我找不到有关此过程的任何信息。
我能找到的最接近的是相反的,即如何将图标从按钮字段提取到独立的图像文件,在这里:How can i extract image from button icon in PDF using Apache PDFBox?
我更愿意使用PDFBox来完成这项任务。
非常感谢任何帮助。
答案 0 :(得分:2)
您可以使用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 test testCreateSimpleImageButton
)
由于您没有提及任何版本要求,我认为您的意思是当前的PDFBox 2.0.x。