有才華的人,別忘記給滋潤(rùn)你的那塊土壤施肥

            BlogJava :: 首頁(yè) :: 新隨筆 :: 聯(lián)系 :: 聚合  :: 管理 ::
            28 隨筆 :: 5 文章 :: 147 評(píng)論 :: 0 Trackbacks
           前段時(shí)間在學(xué)習(xí)關(guān)于java打印的,瞎忙乎了好久。就是一張關(guān)于股票的數(shù)據(jù)分析表打印出來(lái)的結(jié)果A4不能完全顯示,會(huì)截取一部分打印不出來(lái),如下圖做了簡(jiǎn)單的例子點(diǎn)擊正常打印后的圖有的字不能完全顯示:

                本打算拿得所要打印的panel的畫(huà)筆,然后將他轉(zhuǎn)換成Graphics2D,再調(diào)用他的translate(double tx, double ty)scale(double sx, double sy)直接進(jìn)行坐標(biāo)轉(zhuǎn)移縮放,然后對(duì)其打印,但是printJob.getGraphics()不能轉(zhuǎn)換成g2,會(huì)拋出sun.print.ProxyPrintGraphics cannot be cast to java.awt.Graphics2D這個(gè)異常。在這個(gè)異常上花了很長(zhǎng)時(shí)間,總想一定有什么辦法在上面行的通。但是最后還是放棄。

             最后還是把當(dāng)前的panel畫(huà)成圖片存在內(nèi)存中,然后對(duì)這張圖片進(jìn)行縮放處理,下圖是點(diǎn)擊按比例縮小打印后的圖,不過(guò)這樣處理后的圖有個(gè)問(wèn)題就是有的字會(huì)模糊,縮放比例越小越不清楚,對(duì)照上下兩張圖看button上的字就能對(duì)比出來(lái),不過(guò)對(duì)于縮放出來(lái)的圖,這種問(wèn)題也是正常情況。

           下面是源碼:

          package kissJava.print;
          /**
           * 
          @author jxliangby
           * 
          @since  2007.10.14
           * 
          */

          import java.awt.BorderLayout;
          import java.awt.Color;
          import java.awt.Font;
          import java.awt.Frame;
          import java.awt.Graphics;
          import java.awt.Graphics2D;
          import java.awt.Image;
          import java.awt.PageAttributes;
          import java.awt.PrintJob;
          import java.awt.RenderingHints;
          import java.awt.Toolkit;
          import java.awt.event.ActionEvent;
          import java.awt.event.ActionListener;
          import java.awt.geom.AffineTransform;
          import java.awt.image.AffineTransformOp;
          import java.awt.image.BufferedImage;
          import java.awt.print.PageFormat;
          import java.awt.print.Paper;
          import java.awt.print.Printable;
          import java.awt.print.PrinterException;
          import java.awt.print.PrinterJob;
          import java.io.IOException;
          import javax.print.PrintService;
          import javax.swing.JButton;
          import javax.swing.JComponent;
          import javax.swing.JFrame;
          import javax.swing.JPanel;

          public class BigPrintExample extends JFrame implements ActionListener{
              
          private JPanel panel = new JPanel();
              
          private JPanel btnPanel = new JPanel();
              
          private JButton normBtn = new JButton("正常打印(打印不完)");
              
          private JButton zoomBtn = new JButton("按比例縮小打印");
              
          private JComponent component = new PaintComponent();
              
              
          public BigPrintExample(){
                 
          this.setTitle("Print Test");
                 
          this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                 
          this.setBounds((int)((SystemProperties.SCREEN_WIDTH - 800/ 2), (int)((SystemProperties.SCREEN_HEIGHT - 600/ 2), 800600);
                 initLayout();
              }

              
          //組件布局
              private void initLayout(){
                  
          this.getContentPane().setLayout(new BorderLayout());
                  btnPanel.add(normBtn);
                  btnPanel.add(zoomBtn);
                  panel.setLayout(
          new BorderLayout());
                  panel.add(component, BorderLayout.CENTER);
                  panel.add(btnPanel, BorderLayout.SOUTH);
                  
          this.getContentPane().add(panel);
                  normBtn.addActionListener(
          this);
                  zoomBtn.addActionListener(
          this);
              }

              
              
          public void actionPerformed(ActionEvent e) {  
                  
          if(e.getSource() == normBtn)    
                      normalPrint();
                  
          else    
                      zoomInPrint();
                  
              }

              
          //截取打印,A4不能完全顯示
              private void normalPrint(){
                  
          final PageAttributes pa = new PageAttributes();
                  pa.setOrigin(java.awt.PageAttributes.OriginType.PRINTABLE);
                  pa.setColor(java.awt.PageAttributes.ColorType.COLOR);
                  pa.setMedia(java.awt.PageAttributes.MediaType.A4);
                  
          final Toolkit tk = panel.getToolkit();
                  
          final Graphics pg = panel.getGraphics();
                  
          final Graphics gr = pg.create();
                  
          final PrintJob pjob = tk.getPrintJob(
                      
          new Frame() {
                           
          public Graphics getGraphics(){
                                
          return gr;
                           }

                      }
          "printing pop-up frame"null, pa);

                  
          if(pjob != null{
                      
          final Graphics2D ppg = (Graphics2D)pjob.getGraphics();
                      
          if(ppg != null){
                          panel.printAll(ppg);
          //打印
                           ppg.dispose();
                      }

                      pjob.end();
                  }
           
              }

              
              
          private void zoomInPrint(){
                  BufferedImage imag 
          = create(this.getWidth(), this.getHeight());
                  BufferedImage   image 
          =null;
                  
          try{
                       image 
          = zoomImage(imag, 0.70);  //變成0.8的圖片
                       
          //ImageIO.write(image, "jpg", new File("d:\tt.jpg"));
                  }

                  
          catch(Exception ed){
                       System.out.println(ed.toString());
                   }
           
                  PrinterJob pj 
          = PrinterJob.getPrinterJob();    
                  PrintService[] services 
          = PrinterJob.lookupPrintServices();
                  PageFormat pageFormat 
          = pj.defaultPage();//得到默認(rèn)頁(yè)格式
                  
          //pageFormat.setOrientation(PageFormat.LANDSCAPE);//橫向打印
                  Paper paper = pageFormat.getPaper();
                  
          int nExtWidth = (int)paper.getImageableX()*4/5;
                  
          int nExtHeight = (int)paper.getImageableY()*2/3;
                 
          //設(shè)置頁(yè)面顯示大小,如調(diào)邊距等。。。。
                 paper.setImageableArea(paper.getImageableX()-nExtWidth, paper.getImageableY()-nExtHeight,
                     paper.getImageableWidth()
          +nExtWidth*2, paper.getImageableHeight()+nExtHeight*2);
                 pageFormat.setPaper(paper);
                 pj.setPrintable(
          new PrintableDemo(image), pageFormat);
                 
          if (services.length > 0{
                      
          try {
                          pj.setPrintService(services[
          0]);
                          
          if(pj.printDialog()) {
                              pj.print();
                          }

                      }
           catch (PrinterException pe) 
                          System.err.println(pe);
                      }

                  }
           
              }

              
          /**
               * 將這個(gè)frame畫(huà)成BufferedImage;
               * 
          */

              
          private  BufferedImage create( int width, int height) {
                  BufferedImage image 
          = null;
                  
          try {    
                      image 
          = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
                      getContentPane().paint(image.getGraphics()); 
                  }
           catch (Exception e) {
                      System.out.println(
          "ffff = " + e);
                  }

                  
          return image;
              }

              
          /**
               * 將BufferedImage按比例變換
               * scale為變換比例
               * 
          */

              
          private BufferedImage zoomImage(BufferedImage image, double scale)   throws   IOException  {  
           
                  RenderingHints renderingHints 
          =  new  RenderingHints(  
                      RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);  
                  AffineTransformOp scaleOp 
          = new AffineTransformOp(  
                          AffineTransform.getScaleInstance(scale, scale), renderingHints);  
                  BufferedImage targetImage 
          = new BufferedImage(  
                      (
          int)(image.getWidth() * scale),    
                      (
          int)(image.getHeight() * scale), image.getType());  
                  scaleOp.filter(image, targetImage);  
                  
          return   targetImage;  
              }

              
              
          public static void main(String[] args) {
                  
          new BigPrintExample().setVisible(true);
              }


              
          class PaintComponent extends JComponent{
                  
          private String mString = "Java Source and Support";
                  
          private String javaStr = "I Love Java";
                  
          private String author = "By jxliangby";
                  
          private Font mFont = new Font("Serif", Font.PLAIN, 64);
                  
          private  int strX = 50, strY = 150

                  
          protected void paintComponent(Graphics g) {
                      g.setFont(mFont);
                      g.setColor(Color.red);
                      g.drawString(mString, strX, strY);
                      g.drawString(javaStr, strX , strY 
          + 150);
                      g.drawString(author, strX 
          + 400 , strY + 300);
                  }
              
              }

              
          /**
               * 實(shí)現(xiàn)Printtable,將圖片畫(huà)出。
               * 
          */

              
          class PrintableDemo implements Printable {
                      Image image ;
          //= new ImageIcon("1.gif").getImage();
                       public PrintableDemo(Image image){
                          
          this.image = image;
                       }

                      
          public int print(Graphics g, PageFormat pf, int pageIndex) throws PrinterException {
                          
          if (pageIndex == 0{
                              Graphics2D g2d
          = (Graphics2D)g;
                              g2d.translate(pf.getImageableX(), pf.getImageableY()); 
                              g2d.setColor(Color.red);            
                              g2d.drawImage(image, 
          00null);
                              g2d.setColor(Color.black);
                              
          return Printable.PAGE_EXISTS;                    
                          }
           else {
                              
          return Printable.NO_SUCH_PAGE;
                          }

                      }

                      
                  }

          }

          posted on 2008-03-05 11:23 kissjava 閱讀(1752) 評(píng)論(1)  編輯  收藏 所屬分類: swing

          評(píng)論

          # re: 處理A4不能打印大圖片 2009-02-04 17:28 laiang
          很棒,謝謝
            回復(fù)  更多評(píng)論
            

          主站蜘蛛池模板: 茌平县| 江陵县| 托克逊县| 泽库县| 墨竹工卡县| 广南县| 桃园县| 开鲁县| 宿州市| 大荔县| 岑溪市| 佛坪县| 花莲县| 绥阳县| 周口市| 弋阳县| 卢龙县| 静宁县| 吉安市| 贡嘎县| 托克托县| 临漳县| 郓城县| 崇礼县| 公安县| 陆河县| 东港市| 平顶山市| 福海县| 龙游县| 新田县| 玉龙| 疏附县| 娄烦县| 福海县| 涪陵区| 陇南市| 小金县| 永泰县| 五原县| 石棉县|