2017-10-19 30 views
0

J'ai une liste avec des fruits, j'essaie de mettre un fruit de la liste avec ses données dans un JPanel en utilisant une boucle for. Je veux remplir l'écran avec JPanels de 4 par 2 (total 8) dans une page. Voir le résultat sur l'image ci-dessous.Comment faire un PDF de plusieurs pages avec iText Java

Dans l'exemple de code je n'ai pas utilisé la liste de fruits, mais j'ai utilisé une boucle for qui représente comme j'ai une liste de 11 fruits >> pour (int i = 0; i < 11; i ++). Donc ce que je m'attends à obtenir maintenant est un fichier PDF avec 2 pages. Le premier contient 8 panneaux et le second 3 panneaux. Ce que je me demande, c'est comment je peux faire l'application pour obtenir plusieurs PDF paginé où une page contient seulement 8 panneaux maximum. Toute aide serait appréciée.

// Le code du JFrame //

import com.itextpdf.text.Document; 
import com.itextpdf.text.PageSize; 
import com.itextpdf.text.pdf.PdfContentByte; 
import com.itextpdf.text.pdf.PdfTemplate; 
import com.itextpdf.text.pdf.PdfWriter; 
import java.awt.*; 
import java.io.FileOutputStream; 
import java.util.Date; 
import javax.swing.*; 

public class SmallList extends JFrame { 

GridLayout gridLayout = new GridLayout(0,4); 

public SmallList(String name) { 
    super(name); 
    setResizable(false); 
} 

public void addComponentsToPane(final Container pane) { 
    final JPanel components = new JPanel(); 
    components.setLayout(gridLayout); 

    for(int i = 0; i < 11; i++) { 
     JPanel jPanel = new javax.swing.JPanel(); 
     JSeparator seperator = new javax.swing.JSeparator(); 
     JSeparator separator1 = new javax.swing.JSeparator(); 
     JLabel nameLabel = new javax.swing.JLabel(); 
     JLabel unitLabel = new javax.swing.JLabel(); 
     JLabel priceLabel = new javax.swing.JLabel(); 
     JLabel centLabel = new javax.swing.JLabel(); 
     JLabel comma = new javax.swing.JLabel(); 
     jPanel.setBackground(new java.awt.Color(255, 255, 255)); 
     jPanel.setAlignmentX(0.0F); 
     jPanel.setAlignmentY(0.0F); 
     jPanel.setMaximumSize(null); 
     jPanel.setPreferredSize(new java.awt.Dimension(203, 289)); 

     seperator.setBackground(new java.awt.Color(0, 0, 0)); 

     separator1.setBackground(new java.awt.Color(0, 0, 0)); 

     nameLabel.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N 
     nameLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); 

     unitLabel.setFont(new java.awt.Font("Tahoma", 0, 40)); // NOI18N 
     unitLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); 

     priceLabel.setFont(new java.awt.Font("Tahoma", 0, 90)); // NOI18N 
     priceLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); 
     priceLabel.setText(" "); 

     centLabel.setFont(new java.awt.Font("Tahoma", 0, 55)); // NOI18N 
     centLabel.setText(" "); 

     comma.setFont(new java.awt.Font("Tahoma", 0, 36)); // NOI18N 
     comma.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); 
     comma.setText(","); 

     javax.swing.GroupLayout jPanelLayout = new javax.swing.GroupLayout(jPanel); 
     jPanel.setLayout(jPanelLayout); 
     jPanelLayout.setHorizontalGroup(
      jPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) 
      .addComponent(seperator) 
      .addComponent(separator1) 
      .addGroup(jPanelLayout.createSequentialGroup() 
       .addContainerGap() 
       .addGroup(jPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) 
        .addComponent(unitLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) 
        .addComponent(nameLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) 
        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanelLayout.createSequentialGroup() 
         .addComponent(priceLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 101, javax.swing.GroupLayout.PREFERRED_SIZE) 
         .addGroup(jPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) 
          .addGroup(jPanelLayout.createSequentialGroup() 
           .addComponent(comma) 
           .addGap(0, 0, Short.MAX_VALUE)) 
          .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanelLayout.createSequentialGroup() 
           .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) 
           .addComponent(centLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 77, javax.swing.GroupLayout.PREFERRED_SIZE))))) 
       .addContainerGap()) 
     ); 
     jPanelLayout.setVerticalGroup(
      jPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) 
      .addGroup(jPanelLayout.createSequentialGroup() 
       .addGap(6, 6, 6) 
       .addComponent(unitLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE) 
       .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) 
       .addComponent(seperator, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) 
       .addGroup(jPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) 
        .addGroup(jPanelLayout.createSequentialGroup() 
         .addGap(32, 32, 32) 
         .addGroup(jPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) 
          .addComponent(priceLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE) 
          .addComponent(comma))) 
        .addGroup(jPanelLayout.createSequentialGroup() 
         .addGap(29, 29, 29) 
         .addComponent(centLabel))) 
       .addGap(32, 32, 32) 
       .addComponent(separator1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) 
       .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) 
       .addComponent(nameLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE) 
       .addContainerGap()) 
     ); 
     jPanel.setBorder(BorderFactory.createLineBorder(Color.BLACK)); 

     components.add(jPanel); 
    } 

    pane.add(components); 
    print(); 
} 

private void print() { 
    Date date = new Date(); 
    try { 
     JFrame f = new JFrame("Productlijst klein"); 
     f.add(this.getComponent(0)); 
     f.setUndecorated(true); 
     f.pack(); 
     f.setVisible(true); 

     Document document = new Document(PageSize.A4.rotate()); 
     String fileName = "prijslijst" + date.getTime() + ".pdf"; 
     PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(fileName)); 
     document.open(); 

     PdfContentByte cb = writer.getDirectContent(); 
     PdfTemplate template = cb.createTemplate(PageSize.A4.getHeight(), PageSize.A4.getWidth()); 
     Graphics2D g2d = template.createGraphics(f.getWidth(), f.getHeight()); 
     f.paintAll(g2d); 
     g2d.dispose(); 
     cb.addTemplate(template, 0, 0); 

     document.close();   

    } catch (Exception e) { 
     System.out.println(e); 
    } 
} 

/** 
* Create the GUI and show it. For thread safety, 
* this method is invoked from the 
* event dispatch thread. 
*/ 
private static void createAndShowGUI() { 
    //Create and set up the window. 
    SmallList frame = new SmallList("Fruit - kleine afmeting"); 
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    //Set up the content pane. 
    frame.addComponentsToPane(frame.getContentPane()); 
    //Display the window. 
    frame.pack(); 
    frame.setVisible(true); 
} 

public static void main(String[] args) { 
    /* Use an appropriate Look and Feel */ 
    try { 
     //UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel"); 
     UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel"); 
    } catch (UnsupportedLookAndFeelException ex) { 
     ex.printStackTrace(); 
    } catch (IllegalAccessException ex) { 
     ex.printStackTrace(); 
    } catch (InstantiationException ex) { 
     ex.printStackTrace(); 
    } catch (ClassNotFoundException ex) { 
     ex.printStackTrace(); 
    } 
    /* Turn off metal's use of bold fonts */ 
    UIManager.put("swing.boldMetal", Boolean.FALSE); 

    //Schedule a job for the event dispatch thread: 
    //creating and showing this application's GUI. 
    javax.swing.SwingUtilities.invokeLater(new Runnable() { 
     public void run() { 
      createAndShowGUI(); 
     } 
    }); 
} 

}

Le résultat sera comme celui-ci, lorsque l'application est terminée. Une page contiendra 8 JPanels de fruits. Result

+0

S'il vous plaît donner un exemple minimal qui montre où vous essayez exactement de créer un PDF de plusieurs pages. La plupart de ce code n'a rien à voir avec votre question sur la génération de PDF. – Muto

+0

Vous utilisez des méthodes de bas niveau pour ajouter du contenu (comme dans l'utilisation de 'ContentByte'), vous devrez vous occuper des sauts de page vous-même. Si cela vous aide, les opérations que vous êtes en train de faire peuvent être vues comme une peinture sur un canevas de taille infinie, que vous ajoutez à un canevas de la taille d'une page (via 'cb.addTemplate()'). Vous avez dessiné 11 étiquettes, vous ne pouvez pas voir le fond 3 depuis qu'ils sont dessinés de la page. –

+0

Merci pour les réponses, Muto regarde la méthode print(). Le problème est que je ne sais pas comment créer un PDF multi-paginé. C'est ce que je demande en réalité. – Hans

Répondre

2

Solution

  • Au lieu d'utiliser les graphiques PDF, il suffit de faire votre table dans le PDF en utilisant iText. séparer le modèle (les données sous-jacentes) et votre représentation graphique (une interface utilisateur ou un document PDF) est toujours une bonne idée, car cela vous permet de faire preuve de flexibilité dans le futur.

  • code des exemples de table (ce qui est probablement comment vous devez construire votre PDF) se trouve sur la page web iText
    https://developers.itextpdf.com/content/itext-7-examples/itext-7-tables

  • insérer Explicitement un saut de page a déjà été demandé (et répondu) ici
    how can I make a page break using itext