【问题标题】:How to import an icon to a button field in a PDF using PDFBox?如何使用 PDFBox 将图标导入 PDF 中的按钮字段?
【发布时间】:2017-02-18 21:48:27
【问题描述】:

我正在寻找一种将 PDF 文件中按钮字段的正常外观设置为图像文件的方法,但没有找到有关此过程的任何信息。

我能找到的最接近的是相反的,即如何从按钮字段中提取图标到独立的图像文件,这里:How can i extract image from button icon in PDF using Apache PDFBox?

我更喜欢使用 PDFBox 来完成这项任务。

非常感谢任何帮助。

【问题讨论】:

    标签: java pdf pdfbox


    【解决方案1】:

    您可以像这样使用 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。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-20
      • 2015-04-18
      • 2014-10-20
      • 2013-01-21
      • 2021-10-28
      相关资源
      最近更新 更多