java - 如何使用 iText Java 制作多页 PDF

标签 java pdf jframe itext pdf-generation

我有一个水果列表,我试图通过使用 for 循环将列表中的水果及其数据放入 JPanel 中。我想用 4 x 2(总共 8 个)的 JPanel 将屏幕填充到一页中。请参阅下图的结果。

在代码示例中,我没有使用水果列表,而是使用了一个 for 循环,它表示我有一个包含 11 个水果的列表 >> for(int i = 0; i < 11; i++)。 所以我现在期望得到的是一个 2 页的 PDF 文件。第一个包含 8 个面板,第二个包含 3 个面板。我想知道的是如何使应用程序获得多页 PDF,其中一页仅包含最多 8 个面板。任何帮助将不胜感激。

//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();
        }
    });
}

当应用程序完成时,结果将是这样的。一页将包含 8 个水果 JPanel。 Result

最佳答案

解决方案

关于java - 如何使用 iText Java 制作多页 PDF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46831506/

相关文章:

java - 如何合并多个pdf

python - 为什么我在生成 pdf 时在 reportlab 中收到 "memory error"

java - 使用可变数量的 JLabel 创建 JFrame

java - Hibernate 不会更新或删除,但会插入

java - 将 BlackBerry 应用程序与 Flurry 集成

java - 无法导入 com.itextpdf.text.pdf.PdfReader

Java GUI 布局建议

java - NetBeansUpdate 后无法编辑 JFrame 窗体

java - 递归?字符串中的组合

java - Spring MVC : ResponseBodyAdvice doesn't get called for null response from controller