[swing] PrintJob으로 component PDF로 내보내기

jmkim·2023년 7월 5일
0

swing

목록 보기
9/9
package swing;

import javax.swing.*;
import java.awt.*;
import java.awt.print.*;

public class PrintFrame extends JFrame {

    public PrintFrame() {
        setSize(550, 500);
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        setLocationRelativeTo(null);
        setTitle("PDF");

        JButton btn = new JButton("현재 화면 프린트 하기");
        btn.setFont(new Font("맑은 고딕", 1, 15));
        btn.setFocusPainted(false);
        btn.addActionListener(e -> {
            PrinterJob print = PrinterJob.getPrinterJob();
            print.setJobName("PDF Title"); // PDF 제목
            print.setPrintable(new Printable() {
                @Override
                public int print(Graphics graphics, PageFormat pageFormat, int pageIndex) throws PrinterException {
                    if(pageIndex > 0) {
                        return Printable.NO_SUCH_PAGE;
                    }

                    Graphics2D g2 = (Graphics2D) graphics;
                    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
                    g2.translate(pageFormat.getImageableX(), pageFormat.getImageableY());

                    PrintFrame.this.print(g2);

                    return Printable.PAGE_EXISTS;
                }
            });

            if(print.printDialog()) {
                try {
                    print.print();
                } catch (PrinterException ex) {
                    throw new RuntimeException(ex);
                }
            }

        });

        JLabel label = new JLabel("<html>햄버거 ❤</html>");
        label.setFont(new Font("맑은 고딕", 1, 25));
        label.setHorizontalAlignment(JLabel.CENTER);

        JPanel panel = new JPanel(new BorderLayout(10, 10));
        panel.add(label, BorderLayout.NORTH);
        panel.add(new JLabel(new ImageIcon(new ImageIcon("C:\\햄버거.jpg").getImage().getScaledInstance(500, 350, Image.SCALE_SMOOTH))));
        panel.add(btn, BorderLayout.SOUTH);

        add(panel);

        setVisible(true);
    }
    
}

버튼 클릭 시 다이로그 나타남

출력 후 결과

0개의 댓글