使用Java上的Printable打印多页 [英] Print more than one page with Printable on Java
问题描述
我需要在应用程序上打印多页,但是例如,当我尝试打印时,我只能打印一页,或者同一页打印5次.
I need to print more than one page on my application, but when I try to print it I get only one page printed, or the same page printed 5 times, for example.
我将代码放在下面:
MyPrintableTable mpt = new MyPrintableTable();
PrinterJob job = PrinterJob.getPrinterJob();
//PageFormat pf = job.defaultPage();
job.setPrintable(mpt);
job.printDialog();
try
{
job.print();
}
catch (PrinterException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
"MyPrintableTable"类:
"MyPrintableTable" class:
class MyPrintableTable implements Printable
{
public int print(Graphics g, PageFormat pf, int pageIndex)
{
if (pageIndex != 0)
return NO_SUCH_PAGE;
Graphics2D g2 = (Graphics2D) g;
g2.setFont(new Font("Serif", Font.PLAIN, 16));
g2.setPaint(Color.black);
int x = 100;
int y = 100;
for(int i = 0; i < sTable.size(); i++)
{
g2.drawString(sTable.get(i).toString(), x, y);
y += 20;
}
return PAGE_EXISTS;
}
}
如果我更改"pageIndex!= 0"条件,则我将打印更多的页面,但所有页面均使用相同的文本.
If I change the "pageIndex !=0" condition, I have more pages printed, but all with the same text.
我要打印我的所有文本,该文本的长度为三页,但是我只能打印第一页,或者打印三倍于第一页.
I want to print all my text, that has a three page lenght, but I only can print the first one, o print three times the first one.
有人可以帮助我吗?
推荐答案
这里是一个测试程序,该程序演示了我之前在注释中建议的原理.它基于打印多页文档中的思想,以及问题中的代码.在实际程序中,我可能会计算 linesPerPage
而不是将其编译为数字.
Here is a test program that demonstrates the principles I previously suggested in comments. It is based on ideas from Printing a Multiple Page Document, as well as on the code in the question. In a real program I would probably calculate linesPerPage
rather than compiling in a number.
public class Test {
public static void main(String[] args) {
MyPrintableTable mpt = new MyPrintableTable();
PrinterJob job = PrinterJob.getPrinterJob();
// PageFormat pf = job.defaultPage();
job.setPrintable(mpt);
job.printDialog();
try {
job.print();
} catch (PrinterException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
class MyPrintableTable implements Printable {
private int linesPerPage = 20;
private List<String> sTable = new ArrayList<String>();
{
for (int i = 0; i < 100; i++) {
sTable.add("Line" + i);
}
}
public int print(Graphics g, PageFormat pf, int pageIndex) {
if (pageIndex * linesPerPage >= sTable.size())
return NO_SUCH_PAGE;
Graphics2D g2 = (Graphics2D) g;
g2.setFont(new Font("Serif", Font.PLAIN, 16));
g2.setPaint(Color.black);
int x = 100;
int y = 100;
for (int i = linesPerPage * pageIndex; i < sTable.size()
&& i < linesPerPage * (pageIndex + 1); i++) {
g2.drawString(sTable.get(i).toString(), x, y);
y += 20;
}
return PAGE_EXISTS;
}
}
这篇关于使用Java上的Printable打印多页的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!