How to import an icon to a button field in a PDF u

2019-06-06 22:59发布

I'm looking for a way to set the normal appearance of a button field in a PDF file to an image file, but am not finding any information about this process.

The closest I could find was the opposite, ie how to extract an icon from a button field to a stand-alone image file, here: How can i extract image from button icon in PDF using Apache PDFBox?

I would prefer to use PDFBox for this task.

Any help is greatly appreciated.

标签: java pdf pdfbox
1条回答
爷的心禁止访问
2楼-- · 2019-06-06 23:21

You can create a button with an image appearance using PDFBox like this:

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)

As you did not mention any version requirements, I assumed you meant a current PDFBox 2.0.x.

查看更多
登录 后发表回答