2016-10-10 51 views
1

我正在尋找一種方法來將PDF文件中按鈕字段的正常外觀設置爲圖像文件,但沒有找到有關此過程的任何信息。如何使用PDFBox將圖標導入PDF中的按鈕字段?

我能找到的最接近的是相反的,即如何提取從一個按鈕字段的圖標,一個獨立的圖像文件,在這裏:How can i extract image from button icon in PDF using Apache PDFBox?

我寧願使用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.

相關問題