/*Graphic指明打印的圖形環(huán)境;PageFormat指明打印頁(yè)格式(頁(yè)面大小以點(diǎn)為計(jì)量單位,1點(diǎn)為1英寸的1/72,1英寸為25.4毫米。A4紙大致為595×842點(diǎn));page指明頁(yè)號(hào)*/ public int print(Graphics g, PageFormat pf, int page) throws PrinterException { Graphics2D g2 = (Graphics2D)g; g2.setPaint(Color.black); //設(shè)置打印顏色為黑色 if (page >= PAGES) //當(dāng)打印頁(yè)號(hào)大于需要打印的總頁(yè)數(shù)時(shí),打印工作結(jié)束 return Printable.NO_SUCH_PAGE; g2.translate(pf.getImageableX(), pf.getImageableY());//轉(zhuǎn)換坐標(biāo),確定打印邊界 drawCurrentPageText(g2, pf, page); //打印當(dāng)前頁(yè)文本 return Printable.PAGE_EXISTS; //存在打印頁(yè)時(shí),繼續(xù)打印工作 } /*打印指定頁(yè)號(hào)的具體文本內(nèi)容*/ private void drawCurrentPageText(Graphics2D g2, PageFormat pf, int page) { String s = getDrawText(printStr)[page]; //獲取當(dāng)前頁(yè)的待打印文本內(nèi)容 //獲取默認(rèn)字體及相應(yīng)的尺寸 FontRenderContext context = g2.getFontRenderContext(); Font f = area.getFont(); String drawText; float ascent = 16; //給定字符點(diǎn)陣 int k, i = f.getSize(), lines = 0; while(s.length() > 0 && lines < 54) //每頁(yè)限定在54行以內(nèi) { k = s.indexOf(‘\n‘); //獲取每一個(gè)回車(chē)符的位置 if (k != -1) //存在回車(chē)符 { lines += 1; //計(jì)算行數(shù) drawText = s.substring(0, k); //獲取每一行文本 g2.drawString(drawText, 0, ascent); //具體打印每一行文本,同時(shí)走紙移位 if (s.substring(k + 1).length() > 0) { s = s.substring(k + 1); //截取尚未打印的文本 ascent += i; } } else //不存在回車(chē)符 { lines += 1; //計(jì)算行數(shù) drawText = s; //獲取每一行文本 g2.drawString(drawText, 0, ascent); //具體打印每一行文本,同時(shí)走紙移位 s = ""; //文本已結(jié)束 } } } /*將打印目標(biāo)文本按頁(yè)存放為字符串?dāng)?shù)組*/ public String[] getDrawText(String s) { String[] drawText = new String[PAGES]; //根據(jù)頁(yè)數(shù)初始化數(shù)組 for (int i = 0; i < PAGES; i++) drawText[i] = ""; //數(shù)組元素初始化為空字符串 int k, suffix = 0, lines = 0; while (s.length() > 0) { if (lines < 54) //不夠一頁(yè)時(shí) { k = s.indexOf(‘\n‘); if (k != -1) //存在回車(chē)符 { lines += 1; //行數(shù)累加 //計(jì)算該頁(yè)的具體文本內(nèi)容,存放到相應(yīng)下標(biāo)的數(shù)組元素 drawText[suffix] = drawText[suffix] + s.substring(0, k + 1); if (s.substring(k + 1).length() > 0) s = s.substring(k + 1); } else { lines += 1; //行數(shù)累加 //將文本內(nèi)容存放到相應(yīng)的數(shù)組元素 drawText[suffix] = drawText[suffix] + s; s = ""; } } else //已滿一頁(yè)時(shí) { lines = 0; //行數(shù)統(tǒng)計(jì)清零 suffix++; //數(shù)組下標(biāo)加1 } } return drawText; } |
public int getPagesCount(String curStr) { int page = 0; int position, count = 0; String str = curStr; while(str.length() > 0) //文本尚未計(jì)算完畢 { position = str.indexOf(‘\n‘); //計(jì)算回車(chē)符的位置 count += 1; //統(tǒng)計(jì)行數(shù) if (position != -1) str = str.substring(position + 1); //截取尚未計(jì)算的文本 else str = ""; //文本已計(jì)算完畢 } if (count > 0) page = count / 54 + 1; //以總行數(shù)除以54獲取總頁(yè)數(shù) return page; //返回需打印的總頁(yè)數(shù) } |
private void printTextAction() { printStr = area.getText().trim(); //獲取需要打印的目標(biāo)文本 if (printStr != null && printStr.length() > 0) //當(dāng)打印內(nèi)容不為空時(shí) { PAGES = getPagesCount(printStr); //獲取打印總頁(yè)數(shù) PrinterJob myPrtJob = PrinterJob.getPrinterJob(); //獲取默認(rèn)打印作業(yè) PageFormat pageFormat = myPrtJob.defaultPage(); //獲取默認(rèn)打印頁(yè)面格式 myPrtJob.setPrintable(this, pageFormat); //設(shè)置打印工作 if (myPrtJob.printDialog()) //顯示打印對(duì)話框 { try { myPrtJob.print(); //進(jìn)行每一頁(yè)的具體打印操作 } catch(PrinterException pe) { pe.printStackTrace(); } } } else { //如果打印內(nèi)容為空時(shí),提示用戶打印將取消 JOptionPane.showConfirmDialog(null, "Sorry, Printer Job is Empty, Print Cancelled!", "Empty", JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE); } } |
private void printText2Action() { printFlag = 0; //打印標(biāo)志清零 printStr = area.getText().trim();//獲取需要打印的目標(biāo)文本 if (printStr != null && printStr.length() > 0) //當(dāng)打印內(nèi)容不為空時(shí) { PAGES = getPagesCount(printStr); //獲取打印總頁(yè)數(shù) //指定打印輸出格式 DocFlavor flavor = DocFlavor.SERVICE_FORMATTED.PRINTABLE; //定位默認(rèn)的打印服務(wù) PrintService printService = PrintServiceLookup.lookupDefaultPrintService(); //創(chuàng)建打印作業(yè) DocPrintJob job = printService.createPrintJob(); //設(shè)置打印屬性 PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet(); DocAttributeSet das = new HashDocAttributeSet(); //指定打印內(nèi)容 Doc doc = new SimpleDoc(this, flavor, das); //不顯示打印對(duì)話框,直接進(jìn)行打印工作 try { job.print(doc, pras); //進(jìn)行每一頁(yè)的具體打印操作 } catch(PrintException pe) { pe.printStackTrace(); } } else { //如果打印內(nèi)容為空時(shí),提示用戶打印將取消 JOptionPane.showConfirmDialog(null, "Sorry, Printer Job is Empty, Print Cancelled!", "Empty", JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE); } } |
/*將待打印內(nèi)容按比例繪制到屏幕*/ public void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2 = (Graphics2D)g; PageFormat pf = PrinterJob.getPrinterJob().defaultPage(); //獲取頁(yè)面格式 double xoff; //在屏幕上頁(yè)面初始位置的水平偏移 double yoff; //在屏幕上頁(yè)面初始位置的垂直偏移 double scale; //在屏幕上適合頁(yè)面的比例 double px = pf.getWidth(); //頁(yè)面寬度 double py = pf.getHeight(); //頁(yè)面高度 double sx = getWidth() - 1; double sy = getHeight() - 1; if (px/py < sx/sy) { scale = sy / py; //計(jì)算比例 xoff = 0.5 * (sx - scale * px); //水平偏移量 yoff = 0; } else { scale = sx / px; //計(jì)算比例 xoff = 0; yoff = 0.5 * (sy - scale * py); //垂直偏移量 } g2.translate((float)xoff, (float)yoff); //轉(zhuǎn)換坐標(biāo) g2.scale((float)scale, (float)scale); Rectangle2D page = new Rectangle2D.Double(0, 0, px, py); //繪制頁(yè)面矩形 g2.setPaint(Color.white); //設(shè)置頁(yè)面背景為白色 g2.fill(page); g2.setPaint(Color.black);//設(shè)置頁(yè)面文字為黑色 g2.draw(page); try { preview.print(g2, pf, currentPage); //顯示指定的預(yù)覽頁(yè)面 } catch(PrinterException pe) { g2.draw(new Line2D.Double(0, 0, px, py)); g2.draw(new Line2D.Double(0, px, 0, py)); } } /*預(yù)覽指定的頁(yè)面*/ public void viewPage(int pos) { int newPage = currentPage + pos; //指定頁(yè)面在實(shí)際的范圍內(nèi) if (0 <= newPage && newPage < preview.getPagesCount(printStr)) { currentPage = newPage; //將指定頁(yè)面賦值為當(dāng)前頁(yè) repaint(); } } |
/*打印指定的窗體及其包含的組件*/ private void printFrameAction() { Toolkit kit = Toolkit.getDefaultToolkit(); //獲取工具箱 Properties props = new Properties(); props.put("awt.print.printer", "durango"); //設(shè)置打印屬性 props.put("awt.print.numCopies", "2"); if (kit != null) { //獲取工具箱自帶的打印對(duì)象 PrintJob printJob = kit.getPrintJob(this, "Print Frame", props); if (printJob != null) { Graphics pg = printJob.getGraphics(); //獲取打印對(duì)象的圖形環(huán)境 if (pg != null) { try { this.printAll(pg); //打印該窗體及其所有的組件 } finally { pg.dispose(); //注銷圖形環(huán)境 } } printJob.end(); //結(jié)束打印作業(yè) } } } |
/*打印指定的文件*/ private void printFileAction() { //構(gòu)造一個(gè)文件選擇器,默認(rèn)為當(dāng)前目錄 JFileChooser fileChooser = new JFileChooser(SystemProperties.USER_DIR); int state = fileChooser.showOpenDialog(this); //彈出文件選擇對(duì)話框 if (state == fileChooser.APPROVE_OPTION) //如果用戶選定了文件 { File file = fileChooser.getSelectedFile(); //獲取選擇的文件 //構(gòu)建打印請(qǐng)求屬性集 PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet(); //設(shè)置打印格式,因?yàn)槲创_定文件類型,這里選擇AUTOSENSE DocFlavor flavor = DocFlavor.INPUT_STREAM.AUTOSENSE; //查找所有的可用打印服務(wù) PrintService printService[] = PrintServiceLookup.lookupPrintServices(flavor, pras); //定位默認(rèn)的打印服務(wù) PrintService defaultService = PrintServiceLookup.lookupDefaultPrintService(); //顯示打印對(duì)話框 PrintService service = ServiceUI.printDialog(null, 200, 200, printService, defaultService, flavor, pras); if (service != null) { try { DocPrintJob job = service.createPrintJob(); //創(chuàng)建打印作業(yè) FileInputStream fis = new FileInputStream(file); //構(gòu)造待打印的文件流 DocAttributeSet das = new HashDocAttributeSet(); Doc doc = new SimpleDoc(fis, flavor, das); //建立打印文件格式 job.print(doc, pras); //進(jìn)行文件的打印 } catch(Exception e) { e.printStackTrace(); } } } } |
聯(lián)系客服