|
楼主 |
发表于 2006-2-21 22:24:52
|
显示全部楼层
看来,我要叫你大师了,真是很感谢你。只是最近较忙,等抽出功夫才能试你的代码,先将我的代码给你:
import javax.swing.*;
import java.awt.*;
//import javax.swing.text.*;
import java.awt.print.*;
//import javax.print.attribute.*;
public class MyPrint {
private String prnStr="";
private String []arrStr;
//private PrinterJob job;
private PageFormat pf;
private Font font;
private int line=0,y=0;
private int rowNum;
int totalPageNum=0;
//#####################
public MyPrint(String str,PageFormat pf0,Font fnt){
prnStr=str;
arrStr=prnStr.split("\n");
rowNum=arrStr.length;
font=fnt;
PrinterJob job=PrinterJob.getPrinterJob();
if(pf0==null)pf=job.defaultPage();
else pf=pf0;
int size=font.getSize()+2;//that is very important
int height=(int)pf.getImageableHeight();
//line=arrStr.length;
totalPageNum=size*rowNum/height;
if(totalPageNum==0)totalPageNum=1;
else if(totalPageNum%height!=0)totalPageNum++;
int linePerPage=height/size;//,curSize=0;
JOptionPane.showMessageDialog(null,String.valueOf(linePerPage));
Book bk = new Book();
bk.append(new Painter(arrStr,font,linePerPage,totalPageNum),
pf,totalPageNum);
job.setPageable(bk);
//job.setPrintable(new Painter(arrStr,font,linePerPage),pf);
if(job.printDialog())
try { job.print(); }
catch (Exception e) {
JOptionPane.showMessageDialog(null,e.toString());}
}//end MyPrint
}//end class MyPrint
//###############
class Painter implements Printable{
String []arrStr;
Font fnt;
int size,i=0;
int rowNum;
int linePerPage,totalPageNum;
String start="0";
public Painter(String arr[],Font f,int linePerPage,
int totalPage){
arrStr=arr;fnt=f;
size=fnt.getSize();
this.linePerPage=linePerPage;
rowNum=arrStr.length;
totalPageNum=totalPage;
}
//##################
public int print(Graphics g, PageFormat pf, int pageIndex)
throws PrinterException {
if(pageIndex>=totalPageNum)
return Printable.NO_SUCH_PAGE;
int y0=(int)pf.getImageableY();
int x0=(int)pf.getImageableX();
int y=0;
int height=(int)pf.getImageableHeight();
g.translate(x0,y0);
g.setFont(fnt);
int i=pageIndex*linePerPage;
while(i<(pageIndex+1)*linePerPage){
if(i>=rowNum)break;
g.drawString(arrStr,x0,y+y0);
y=y+size;
i++;
}//end while
return Printable.PAGE_EXISTS;
}//end print
//###################
}//end class Painter |
|