Java:打印带有页眉和页脚的自定义(可打印)页面

标签 java printing header customization footer

我知道Java中的一些组件(JTable、JTextArea)有自己的方式来传递页面的页眉和页脚。
有没有简单的方法来打印基于我自己实现的 Printable 的页面,或者我应该自己定位它们(​​例如,在 Printable 接口(interface)的重写 print(...) 方法中)?
这个 Printable 类作为输入接收纯文本包,仅此而已。 当然最后我可以把所有东西都放在 JTextArea 中,但如果有其他方法我不想这样做。
问候。

最佳答案

您需要将它们放置在重写的 print() 方法中。

public class TestReport implements Printable
{
    //Here is where we set up the class variables.
    private int numberOfPages = 0;              //numberOfPages -- How many pages we will be printing.
    private int headerLines = 0;                //headerLines -- How many lines are in the header.
    private int footerLines = 0;                //footerLines -- How many lines are in the footer.
    private int bodyLines = 0;                  //bodyLines -- How many lines we've added to the body of the report.
    private boolean useDefaultFooter = false;   //useDefaultFooter -- If we are to use the default footer instead of a custom one.
    private int fontSize = 10;                  //fontSize -- The size of the font to use, in points. The default is 10pt.
    private Vector header = new Vector();       //header -- The vector containing the header text.
                                                //Each item in the vector is a line on the header.
    private Vector body = new Vector();         //body -- The vector containing the body text.
    private Vector footer = new Vector();       //footer -- The vector containing the footer.

    //The constructor does not need to do anything.

    /**
     * Create a new instance or TestReport
     */
    public TestReport() 
    {

    }

    /**
     * Prints the final report after the information has been added.
     */
    public void printReport()
    {

        //Get the number of lines in the header, body, and footer. If we're using the default footer, it's only one line long.

        headerLines = header.size();
        bodyLines = body.size();
        if (useDefaultFooter == true) {
            footerLines = 1;
        } else {
            footerLines = footer.size();
        }
        PrinterJob printerJob = PrinterJob.getPrinterJob();
        PageFormat landscape = printerJob.defaultPage();
        landscape.setOrientation(PageFormat.LANDSCAPE);
        printerJob.setPrintable(TestReport.this, landscape);

        printerJob.printDialog();

        try {
            printerJob.print();
        } catch (Exception PrintException) {}
    }

    public void addHeaderLine (String headerLine)
    {
        header.addElement(headerLine);
    }

    public void addBodyLine (String bodyLine)
    {
        body.addElement(bodyLine);
    }

    public void addFooterLine (String footerLine)
    {
        footer.addElement(footerLine);
    }

    public void setFontSize(int fontSize)
    {
        this.fontSize = fontSize;
    }

    public void useDefaultFooter()
    {
        useDefaultFooter = true;
    } 


    public int print(Graphics g, PageFormat pageFormat, int pageIndex) throws PrinterException 
    {
        Graphics2D g2 = (Graphics2D) g;
        g2.setColor(Color.black);
        Font myFont = new Font("Courier", Font.PLAIN, fontSize);
        g2.setFont(myFont);

        int fontHeight = g2.getFontMetrics().getHeight();
        int fontDescent = g2.getFontMetrics().getDescent();

        double pageHeight = pageFormat.getHeight();
        double pageWidth = pageFormat.getWidth();

        int lineHeight = fontHeight + fontDescent;

        int linesPerPage = (int)((pageHeight - 72 - 72) / lineHeight);

        int bodyLinesPerPage = linesPerPage - headerLines - footerLines;

        int numberOfPages = (int)Math.ceil((double)bodyLines / bodyLinesPerPage);

        if (pageIndex >= numberOfPages)
        {
            return Printable.NO_SUCH_PAGE;
        }
        //Start at one inch down, one inch accross
        int currentY = 72 + lineHeight;
        int currentX = 72;

        //Draw the header
        for (int i = 0; i < header.size(); i++) 
        {
            g2.drawString(header.get(i), currentX, currentY);
            currentY = currentY + lineHeight;
        }
        //Draw the body
        for (int i = bodyLinesPerPage * pageIndex; i < (bodyLinesPerPage * (pageIndex + 1)) ; i++ )
        {
            if (i < body.size()){
                g2.drawString(body.get(i), currentX, currentY);
            }
            currentY = currentY + lineHeight;
        }
        if (useDefaultFooter == true) 
        {
            GregorianCalendar calendar = new GregorianCalendar();
            int todayYear = calendar.get(GregorianCalendar.YEAR);
            int todayMonth = calendar.get(GregorianCalendar.MONTH) + 1;
            int todayDay = calendar.get(GregorianCalendar.DAY_OF_MONTH); 

            String theMonth = "0" + todayMonth;
            String theDay   = "0" + todayDay;

            g2.drawString("SYSTEM DATE: " + todayYear + "-" + theMonth.substring
                          (theMonth.length() - 2) + "-" + 
                          theDay.substring(theDay.length() - 2) 
                          + " | PAGE " + (pageIndex + 1) 
                          + " OF " + numberOfPages, currentX, currentY);
        } 
        else 
        {
            for (int i = 0; i < footer.size(); i++)
            {
                g2.drawString(footer.get(i), currentX, currentY);
                currentY = currentY + lineHeight;
            }
        }
        return Printable.PAGE_EXISTS;       
    }
}   

关于Java:打印带有页眉和页脚的自定义(可打印)页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19159237/

相关文章:

java - 为什么我的 LinkedList 中的 add() 方法不起作用?

Java, MongoDB : How to update every object while iterating a huge collection?

C++ 扩展 ASCII 码

c++ - 如何从 main.cpp 文件中的单独 cpp 文件调用函数?

java - 简单更改后 REST 服务不起作用

java - 在Java中如何通过递归计算出某个字母在字符串中出现了多少个?

java - System.out.print ('\r' ) 不起作用

c++ - 模板打印函数 C++

c++ - 自动化 C++ 头文件/源代码分离的工具

xcode - #将函数导入多个源文件