我正在编写一个程序,它使我的文本区域已经生成了数据,并且需要将其打印出来。我得到它计算打印整个textarea需要多少页,但不是打印第1页然后打印第2页,它打印第1页然后再打印第1页。我似乎无法让它来拯救我的生命。我一直在浏览所有论坛并在oracle上提供帮助,但必须有一些我缺少的东西。如果你可以这么善良,花点时间看看我的代码,我将非常感激。谢谢。 -Garrett
private void hardPrintActionPerformed(java.awt.event.ActionEvent evt)
{
int width = printOut.getWidth() ;
int height = printOut.getHeight();
System.out.println("width is "+ width);
System.out.println("Height is "+height);
String font = fontSize.getText();
int FontS = Integer.parseInt(font);
Font fonT = new Font("Monospaced", Font.PLAIN, 12);
printOut.setFont(new Font("Tahoma", Font.PLAIN, FontS));
PrinterJob pj = PrinterJob.getPrinterJob();
PageFormat pf = pj.defaultPage();
Book bk = new Book();
Paper paper = new Paper();
double margin = 18;
pj.setPageable(bk);
paper.setSize(612,792);
paper.setImageableArea(margin, margin
, paper.getWidth() -margin * 2
, paper.getHeight() - margin * 2);
int lines = printOut.getLineCount();
System.out.println("lines = "+lines);
pf.setPaper(paper);
int tall = (int) pf.getImageableHeight();
System.out.println("tall ="+tall);
System.out.println("orientation "+pf.getOrientation());
int pagenum =bk.getNumberOfPages();
System.out.println("pagenum = "+pagenum);
System.out.println("areah = "+height);
int numpages =1;
if (height >756) {
for (int i = 756; i < height;) {
numpages = numpages+1;
i= i +756;
}
}
System.out.println("numpages ="+numpages);
bk.append(new MyPrintable(), pf,numpages);
// pj.setPrintable(new MyPrintable(), pf);
if (pj.printDialog()) {
try {
printOut.setBounds(0, 0, printOut.getWidth(), printOut.getHeight());
pj.print();
} catch (PrinterException pp) {
System.out.println(pp);
}
}
}
/**
* @param args the command line arguments
*/
class MyPrintable implements Printable {
public int print(Graphics g, PageFormat pf, int pageIndex) {
//int pagenum =bk.getNumberOfPages();
int height = printOut.getHeight();
int numpages =1;
if (height >756) {
for (int i = 756; i < height;) {
numpages = numpages+1;
i= i +756;
}
}
if (pageIndex >3)
return NO_SUCH_PAGE;
else{
Graphics2D g2 = (Graphics2D) g;
g2.setFont(new Font("Monospaced", Font.PLAIN, 10));
printOut.setBounds(0, 0, printOut.getWidth(), printOut.getHeight());
// paper.getImageableWidth();
g2.translate(pf.getImageableX(), pf.getImageableY());
System.out.println("print " +pf.getImageableY());
Rectangle componentBounds = printOut.getBounds();
g2.translate(-componentBounds.x, -componentBounds.y);
g2.scale(1, 1);
boolean wasBuffered = printOut.isDoubleBuffered();
printOut.printAll(g2); //printOut is my text area.
printOut.setDoubleBuffered(wasBuffered);
return PAGE_EXISTS;
}
}
}
答案 0 :(得分:3)
您需要使用g2.translate(-componentBounds.x, -componentBounds.y);
使用pageIndex*pageHeight
答案 1 :(得分:0)
你真的需要使用printJob吗?为什么不使用JasperReports制作你的pdf(作为一个加号,你得到一个制作pdf,xls和许多其他格式的库),你不能设计在IReports和然后将它与jasper一起使用,或者从代码设计报告,非常有效的工具:D