2016-10-10 1 views
1

Je cherche un moyen de définir l'apparence normale d'un champ de bouton dans un fichier PDF dans un fichier image, mais je ne trouve aucune information sur ce processus.Comment importer une icône dans un champ de bouton dans un PDF en utilisant PDFBox?

Le plus approchante était le contraire, à savoir comment extraire une icône d'un champ de bouton à un fichier image autonome, ici: How can i extract image from button icon in PDF using Apache PDFBox?

Je préférerais utiliser PDFBox pour cette tâche.

Toute aide est grandement appréciée.

Répondre

1

Vous pouvez créer un bouton avec une apparence d'image en utilisant PDFBox comme ceci:

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 essai testCreateSimpleImageButton)

Comme vous ne l'avez pas mentionné toutes les exigences de version, je vous supposais voulais dire une PDFBox 2.0.x actuel