用JAVA 创建自己的 A4 打印语言

来源:互联网 发布:哔哩哔哩录制软件 编辑:程序博客网 时间:2024/04/28 16:03
在这个低碳的时代,大家都在追求无纸化,但是有些打印还是不可避免,比如说产品出货单之类的,讲到打印那办法就多了,通过报表控件也可以完成打印,但我始终觉得不够灵活,如果有人玩过ZPL(zebra print language),就能了解打印格式其实可以很灵活地控制,可惜 ZPL只适用于Zebra的标签打印机,并不适合用平常的纸张打印。所以能不能做一种类ZPL的语言来打印,之前我也看过PCL,由于本人水平有限,真没看懂。

[java] view plaincopy
  1. package hpl;  
  2. import java.awt.Color;  
  3. import java.awt.Font;  
  4. import java.awt.Graphics;  
  5. import java.awt.Graphics2D;  
  6. import java.awt.Image;  
  7. import java.awt.RenderingHints;  
  8. import java.awt.Toolkit;  
  9. import java.awt.image.BufferedImage;  
  10. import java.awt.print.PageFormat;  
  11. import java.awt.print.Printable;  
  12. import java.awt.print.PrinterException;  
  13. import java.io.File;  
  14. import java.io.IOException;  
  15.   
  16. import javax.imageio.IIOException;  
  17. import javax.imageio.ImageIO;  
  18. import javax.print.Doc;  
  19. import javax.print.DocFlavor;  
  20. import javax.print.DocPrintJob;  
  21. import javax.print.PrintException;  
  22. import javax.print.PrintService;  
  23. import javax.print.PrintServiceLookup;  
  24. import javax.print.SimpleDoc;  
  25. import javax.print.DocFlavor.URL;  
  26. import javax.print.attribute.DocAttributeSet;  
  27. import javax.print.attribute.HashAttributeSet;  
  28. import javax.print.attribute.HashDocAttributeSet;  
  29. import javax.print.attribute.HashPrintRequestAttributeSet;  
  30. import javax.print.attribute.PrintRequestAttributeSet;  
  31. import javax.print.attribute.standard.MediaSizeName;  
  32. import javax.print.attribute.standard.PrinterName;  
  33. import javax.swing.JOptionPane;  
  34.   
  35. import Kanban.LineInfo;  
  36. /** 
  37.  * java定位打印,把打印内容打到指定的地方。 
  38.  * 
  39.  * @author Harvey_Huang 
  40.  * 
  41.  */  
  42. public class LocatePrint implements Printable {  
  43.     private int PAGES = 0;  
  44.     private String printStr;  
  45.     private String fontname;  
  46.     private int fontsize;  
  47.     private String imagepath;  
  48.     private int locx;  
  49.     private int locy;  
  50.     private String  Singpage;  
  51.     private String Orientation="N";  
  52.     private String Fontflag="N";  
  53.     private String Sizeflag="N";  
  54.     private String message="OK";  
  55.     /* 
  56.      * Graphic指明打印的图形环境;PageFormat指明打印页格式(页面大小以点为计量单位, 
  57.      * 1点为1英寸的1/72,1英寸为25.4毫米。A4纸大致为595×842点);page指明页号 
  58.      *  
  59.      */  
  60.       
  61.    // int pp= 1;  
  62.     public int print(Graphics gp, PageFormat pf, int page)  
  63.             throws PrinterException {  
  64.         //pp++;  
  65.         try {  
  66.               
  67.         try{      
  68.               
  69.         Graphics2D g2 = (Graphics2D) gp;  
  70.         g2.setPaint(Color.black); // 设置打印颜色为黑色  
  71.           
  72.         //System.err.println("PPPPPPPP  : " + page);  
  73.         if (page >= PAGES) // 当打印页号大于需要打印的总页数时,打印工作结束  
  74.             return Printable.NO_SUCH_PAGE;  
  75.         g2.translate(pf.getImageableX(), pf.getImageableY());// 转换坐标,确定打印边界  
  76.         //g2.drawString(printStr, locx, locy);// 具体打印每一行文本,同时走纸移位  
  77.       
  78.           
  79.           
  80.           
  81.         String[] itemarray;  
  82.         String[] detailarray;  
  83.         String typeflag = null;  
  84.         Font font;  
  85.           
  86.         itemarray=Singpage.split("\\^FS");  
  87.         //System.err.println("XZ:::::::" +itemarray.length);  
  88.          for (int i=0; i<itemarray.length;i++){  
  89.              typeflag="";  
  90.                 System.out.println("Split  " + i +" : "+itemarray[i]);  
  91.                 //System.out.println("-------------------------");  
  92.                 detailarray= itemarray[i].split("\\^");  
  93.               for (int j=0; j<detailarray.length;j++){  
  94.                   if(detailarray[j].length()>1){  
  95.                   if(detailarray[j].substring(02).toUpperCase().equals("XA")){  
  96.                      // System.out.println("初始化");   
  97.                       PAGES=0;  
  98.                       printStr="";  
  99.                       fontname="Arial";  
  100.                       fontsize=14;  
  101.                       imagepath="";  
  102.                       locx=0;  
  103.                      locy=0;  
  104.                   
  105.                   }if(detailarray[j].substring(02).toUpperCase().equals("FO")){  
  106.                     //  System.out.println("找到FO");   
  107.                       String[] location=detailarray[j].substring(2, detailarray[j].length()).split(",");  
  108.                       if(location.length>1){   
  109.                          locx=Integer.parseInt(location[0]);  
  110.                          locy=Integer.parseInt(location[1]);  
  111.                         //  System.out.println(location[1]);   
  112.                       }  
  113.                   }  
  114.                   if(detailarray[j].substring(02).toUpperCase().equals("FD")){  
  115.                      // System.out.println("找到FD");   
  116.                       printStr=detailarray[j].substring(2, detailarray[j].length());  
  117.                     //  System.out.println(printStr);   
  118.                   }  
  119.                     
  120.               
  121.                   if(detailarray[j].substring(02).toUpperCase().equals("PA")){  
  122.                      // System.out.println("找到PA");   
  123.                       imagepath=detailarray[j].substring(2, detailarray[j].length());  
  124.                     //  System.out.println(imagepath);  
  125.                   }  
  126.                   if(detailarray[j].substring(02).toUpperCase().equals("PQ")){  
  127.                     //  System.out.println("找到PQ");     
  128.                       PAGES=Integer.parseInt(detailarray[j].substring(2, detailarray[j].length()));  
  129.                         
  130.                         if (PAGES==0// 当打印页号大于需要打印的总页数时,打印工作结束  
  131.                             return Printable.NO_SUCH_PAGE;  
  132.                     //  System.out.println(PAGES);   
  133.                   }  
  134.                   if(detailarray[j].substring(02).toUpperCase().equals("AN")){  
  135.                      // System.out.println("找到AN");    
  136.                       fontname=detailarray[j].substring(2, detailarray[j].length());  
  137.                     //  System.out.println(fontname);  
  138.                       Fontflag="Y";  
  139.                   }  
  140.                   if(detailarray[j].substring(02).toUpperCase().equals("AS")){  
  141.                      // System.out.println("找到AS");    
  142.                       fontsize=Integer.parseInt(detailarray[j].substring(2, detailarray[j].length()));  
  143.                     //  System.out.println(fontsize);     
  144.                       Sizeflag="Y";  
  145.                   }  
  146.                   if(detailarray[j].substring(02).toUpperCase().equals("OR")){  
  147.                          // System.out.println("找到AS");    
  148.                       Orientation=detailarray[j].substring(2, detailarray[j].length());  
  149.                         //  System.out.println(Orientation);  
  150.                             
  151.                       }  
  152.                   if(detailarray[j].substring(02).toUpperCase().equals("ST")){  
  153.                     //  System.out.println("找到ST");  
  154.                      typeflag="ST";  
  155.                   
  156.                   }  
  157.                   if(detailarray[j].substring(02).toUpperCase().equals("RP")){  
  158.                      // System.out.println("找到RP");  
  159.                      typeflag="RP";  
  160.                        
  161.                      String[] rpstring=detailarray[j].substring(2, detailarray[j].length()).split(",");  
  162.                       if(rpstring.length>1){   
  163.                
  164.                       
  165.                           printStr="";  
  166.                      for(int h=0; h<Integer.parseInt(rpstring[1])+1;h++){  
  167.                          printStr=rpstring[0].toString()+printStr;  
  168.                      }  
  169.                       }  
  170.                   
  171.                   }  
  172.                     
  173.                   if(detailarray[j].substring(02).toUpperCase().equals("GF")){  
  174.                      // System.out.println("找到GF");    
  175.                      typeflag="GF";  
  176.                   }  
  177.                   }  
  178.                 //System.out.println(detailarray[j]);  
  179.               }  
  180.   
  181.                   
  182.                    if (Orientation.toUpperCase().equals("R")){  
  183.                         g2.rotate((3.14159/2), locx, locy);      
  184.                    }  
  185.                      
  186.                    if (Orientation.toUpperCase().equals("I")){  
  187.                         g2.rotate(3.14159, locx, locy);      
  188.                    }  
  189.                      
  190.                    if (Orientation.toUpperCase().equals("B")){  
  191.                         g2.rotate((3.14159*3/2), locx, locy);      
  192.                    }  
  193.                   
  194.               if(typeflag.equals("ST")){  
  195.             //   System.out.println(printStr+"    "+fontname+"    "+fontsize+"    ");    
  196.                 // N = Normal  
  197.                 // R = Rotated, 90 degrees clockwise;  
  198.                 // I = Inverted, 180 degrees  
  199.                  //B = Read from Bottom up, 270 degrees  
  200.                  if(Fontflag.equals("Y")||Sizeflag.equals("Y")){  
  201.                         font = new Font(fontname, Font.PLAIN, fontsize);// 创建字体  
  202.                         g2.setFont(font);      
  203.                  }  
  204.                   
  205.           
  206.                     // 打印当前页文本  
  207.                     g2.drawString(printStr, locx, locy);   
  208.                     Fontflag="N";  
  209.                     Sizeflag="N";  
  210.                       
  211.   
  212.               }  
  213.                 
  214.   
  215.              if(typeflag.equals("GF")){  
  216.                  // System.out.println("打印准备");  
  217.                     BufferedImage img = ImageIO.read(new File(imagepath));  
  218.                      
  219.                    // g2.rotate(3.14159, locx, locy);  
  220.                     g2.drawImage(img, locx, locy, null);  
  221.                     //  System.out.println("打印结束");  
  222.                     //g2.rotate(-3.14159, locx, locy);   
  223.               }  
  224.                
  225.               if(typeflag.equals("RP")){  
  226.                     // System.out.println(printStr+"    "+fontname+"    "+fontsize+"    ");    
  227.                        
  228.                   
  229.                          font = new Font("Arial", Font.PLAIN, fontsize);// 创建字体  
  230.                         g2.setFont(font);  
  231.                         // 打印当前页文本  
  232.                         g2.drawString(printStr, locx, locy);   
  233.                        
  234.                   }   
  235.                
  236.                if (Orientation.toUpperCase().equals("R")){  
  237.                     g2.rotate(-(3.14159/2), locx, locy);      
  238.                }  
  239.                  
  240.                if (Orientation.toUpperCase().equals("I")){  
  241.                     g2.rotate(-3.14159, locx, locy);      
  242.                }  
  243.                  
  244.                if (Orientation.toUpperCase().equals("B")){  
  245.                     g2.rotate(-(3.14159*3/2), locx, locy);      
  246.                }       
  247.                Orientation="N";  
  248.                
  249.   
  250.                  
  251.                  
  252.              // System.out.println("-------------------------");  
  253.         }  
  254.           
  255.           
  256.            
  257.           
  258.         } catch (IIOException e) {  
  259.             // TODO Auto-generated catch block  
  260.             message="E004";  
  261.             e.printStackTrace();  
  262.             return Printable.NO_SUCH_PAGE;  
  263.         }  
  264.           
  265.         } catch (IOException e) {  
  266.             // TODO Auto-generated catch block  
  267.             e.printStackTrace();  
  268.             return Printable.NO_SUCH_PAGE;  
  269.         }   
  270.   
  271.     //  System.err.println("pppppp:::::::" + pp);  
  272.        return Printable.PAGE_EXISTS; // 存在打印页时,继续打印工作  
  273.   
  274.     }  
  275.     // 打印内容到指定位置  
  276.     public String printContent(String hplpage,String Printq) {  
  277.    //   System.err.println("tttttt:" + pp);  
  278.         //String message="OK";  
  279.         Singpage=hplpage;  
  280.           
  281.        // printStr = "aaaaa";// 获取需要打印的目标文本  
  282.        // fontname = "Free 3 of 9";// 获取需要打印的目标文本  
  283.        // fontsize=24;  
  284.        // imagepath="c:\\2.jpg";  
  285.        // locx=100;  
  286.        // locy=300;  
  287.     
  288.         if (hplpage.length() > 0// 当打印内容不为空时  
  289.         {  
  290.               
  291.               try {  
  292.                    
  293.             DocPrintJob job = null;  
  294.             PAGES = 1// 获取打印总页数  
  295.             // 指定打印输出格式  
  296.             DocFlavor flavor = DocFlavor.SERVICE_FORMATTED.PRINTABLE;  
  297.             // 定位默认的打印服务  
  298.               
  299.             HashAttributeSet hs = new HashAttributeSet();    
  300.             String printerName=Printq;    
  301.               
  302.             hs.add(new PrinterName(printerName,null));  
  303.             PrintService[] printService =PrintServiceLookup.lookupPrintServices(null, hs);    
  304.            // PrintService printService = PrintServiceLookup.lookupDefaultPrintService();  
  305.             // 创建打印作业  
  306.             if(printService.length>0){  
  307.                  job = printService[0].createPrintJob();  
  308.           
  309.        
  310.             // 设置打印属性  
  311.             PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();  
  312.             // 设置纸张大小,也可以新建MediaSize类来自定义大小  
  313.             pras.add(MediaSizeName.ISO_A4);  
  314.   
  315.     
  316.             DocAttributeSet das = new HashDocAttributeSet();  
  317.             // 指定打印内容  
  318.             Doc doc = new SimpleDoc(this, flavor, das);  
  319.             // 不显示打印对话框,直接进行打印工作  
  320.     
  321.             
  322.                 job.print(doc, pras); // 进行每一页的具体打印操作  
  323.                 //System.err.print("分析标识点5");  
  324.             }else{  
  325.              message="E002";  
  326.            }  
  327.             } catch (PrintException pe) {  
  328.                 pe.printStackTrace();  
  329.                 message="E001";  
  330.             }  
  331.           
  332.         } else {  
  333.             // 如果打印内容为空时,提示用户打印将取消  
  334.             JOptionPane.showConfirmDialog(null,  
  335.                     "Sorry, Printer Job is Empty, Print Cancelled!",  
  336.                     "Empty", JOptionPane.DEFAULT_OPTION,  
  337.                     JOptionPane.WARNING_MESSAGE);  
  338.             message="E003";  
  339.         }  
  340.           
  341.         return message;  
  342.     }  
  343.       
  344.       
  345.   
  346.     public String analyze(String hpl,String Printq) {  
  347.          
  348.         String printstate="OK";  
  349.           
  350.           LocatePrint test = new LocatePrint();  
  351.         String[] pagearray=hpl.split("\\^XZ");  
  352.         //System.err.println("nnnnnnn======"+ pagearray.length);  
  353.   
  354.         for(int k=0; k<pagearray.length;k++){  
  355.               
  356.              printstate=test.printContent(pagearray[k].toString().trim(),Printq);  
  357.                
  358.         }  
  359.         return printstate;  
  360.     }  
  361.   
  362.       
  363.     public static void main(String[] args) {  
  364.          String testdata="^XA" +  
  365.             "^STthis is test^FO20,42^FDPICK LIST^ANArial^AS30^FS" +  
  366.             "^STthis is test^FO52,120^FDhelloworld^AN3 of 9 Barcode^AS20^FS" +  
  367.             "^STthis is test^FO60,482^FD中文测试中文测试^AN宋体^AS30^FS" +  
  368.             "^STthis is test^FO470,602^FD黑体测试^AN黑体^ORB^AS20^FS" +  
  369.             "^STthis is test^FO170,632^FD黑体测试1^FS" +  
  370.             "^STthis is test^FO170,652^FD黑体测试2^FS" +  
  371.             "^STthis is test^FO170,672^FD黑体测试3^FS" +  
  372.             "^STthis is test^FO170,692^FD黑体测试4^AS40^FS" +  
  373.             "^RP_,50^FO52,522^AS20^FS" +  
  374.             "^STthis is test^FO80,482^FD中文测试中文测试(旋转)^ORR^AN宋体^AS30^FS" +  
  375.             "^GFThis is test^PAc:\\2.jpg^FO294,372^ORI^FS" +  
  376.             "^PQ1" +  
  377.             "^XZ";  
  378.           LocatePrint test = new LocatePrint();  
  379.           System.out.print(test.analyze(testdata,"TESTPRINT"));  
  380.          
  381.     }  
  382. }  


如果你够仔细的话,你就会发现,程序会执行两遍后才会被打印出来,一开始我也以为是我的程序方面的问题,后来在网上查了一下,这块属于正常现像,原因就查阅:

http://hi.baidu.com/dcjob/item/e6c40d16d34b08ec9913d6fb

下面讲一下打印参数的含义:

^XA  是每次打印的开始。

^XZ 是结束

^AS 字体大小

^AN 字体名字,一定是操作系统中存在的字体

^FS 打印单项结束标识

^FD 打印数据

^FO 打印位置

^RP 重复打印某一字符或文字

^ST 字符串打印标识

^GF 图片打印标识

^PA 图片路径,注意路径的反斜杠需反义

^PQ 打印数量

^OR 打印方向  N正常,R 90度,I 180度 B 270度

请注意这行   System.out.print(test.analyze(testdata,"TESTPRINT"));

TESTPRINT是安装好的打印机在系统中的名称。名称一定要对应,默认或非默认打印机不会有问题。

参照例子的实例即可,如果想了解每个参数,请查阅下面的说明,由于公司是洋人开的,就假装一回洋鬼子,如果你学过ZPL会发现和ZPL手册很像。



HPL  Command Guide

__________________________________________

   

^XA

^STthis is test^FO20,42^FDPICK LIST^ANArial^AS30^FS

^STthis is test^FO52,120^FDhelloworld^AN3 of 9 Barcode^AS20^FS

^STthis is test^FO60,482^FD中文测试中文测试^AN宋体^AS30^FS

^STthis is test^FO470,602^FD黑体测试^AN黑体^ORB^AS20^FS

^STthis is test^FO170,632^FD黑体测试1^FS

^STthis is test^FO170,652^FD黑体测试2^FS

^STthis is test^FO170,672^FD黑体测试3^FS

^STthis is test^FO170,692^FD黑体测试4^AS40^FS

^RP_,50^FO52,522^AS20^FS

^STthis is test^FO80,482^FD中文测试(旋转)^ORR^AN宋^AS30^FS

^GFThis is test^PAc:\\2.jpg^FO294,372^ORI^FS

^PQ1

^XZ





    ^XA
        Start Format

Description:The ^XA command is used at the beginning of HPL code,It is the opening      bracket and indicates the start of a new label format.


                 Format:^XA

Comments:Report formats should start with the ^XA command and end with the ^XZ command to be in valid HPL format


    ^XZ
        End Format

Description:The ^XZ command is the ending (closing) bracket.It indicates the end of a report format.When this command is received. a report will be printed.


                 Format:^XZ

Comments:Report formats should start with the ^XA command and end with the ^XZ command to be in valid HPL format.


     ^AN
        Font name

Description:The ^AN is used with system fonts


Format:^ANf


Parameters:

     f= font name

          Accepted Values:System font name


Example:

         ^XA

         ^STthis is test^FO20,42^FDPICK LIST^ANArial^AS30^FS

         ^PQ1

         ^XZ



     ^AS
        Font Size

Description:Font Size  


Format:^ASf


Parameters:

     f= font size

          Accepted Values:System font size


Example:

         ^XA

         ^STthis is test^FO20,42^FDPICK LIST^ANArial^AS30^FS

         ^PQ1

         ^XZ


     ^FD
        Field Data

Description:The ^FD command defines the data string for the field.The filed data can be any printable character.


Format:^FDa


Parameters:

     a= data to be printed

          Accepted Values:Any ASCII string


     ^FO
        Field Origin

Description:The ^FO command  sets a field origin,

Format:^FOx,y


Parameters:

     x= x-axis location

          Default Value:0

     y= y-axis location

          Default Value:0


Comments:If the value entered for x or y parameter is too high,it could position the field origin completely off the report.


     ^FS
        Field Separator

Description:The ^FS command  denotes the end of the field definiton.


Format:^FS



     ^OR
        Field orientation

Description:The ^FO command  sets a field orientation


Format:^ORo

       

Parameters:

     Accepted values:

                  N=normal;

                  R=rotated 90 degrees(clockwise)

                  I=inverted 180 degrees

                  B=read from bottom up,270 degrees


     ^PQ
        Print quantity

Description:The ^PQ command  gives control over serveral printing operations.It controls the number of reports to print.

Format:^FOq


Parameters:

     q= total quantity of reports to print

          Default Value:0


Comments:If Q=0 ,It wouldn’t print the report.




     ^PA
        graphic path

Description:The ^PA command  sets graphic path,It controls the path of graphic to print.

Format:^PAp


Parameters:

     p= graphic path.the “\” need transfer to Antisense character “\\”


Example:

                    ^XA

                                    ^GFThis is test^PAc:\\2.jpg^FO294,372^FS
                                    ^PQ1

                    ^XZ


     ^RP
        repeat print character

Description:The ^RP command  gives control continuous print the same character

Format:^RPc,q


Parameters:

     c= Need to be printed characters

     q= Quantity of character


     Example:

                    ^XA

                                    ^RP_,50^FO52,522^AS20^FS
                                    ^PQ1

                    ^XZ






     ^ST
        Print string start

Description:The ^ST command is used at the beginning of string printing, It is the opening bracket and indicates the start of string printing.

Format:^STd


Parameters:

     d= Description,it will not be printed on the report,Just better understanding of the code

          Default Value:NULL




     ^GF
        Print graphic start

Description:The ^GF command is used at the beginning of graphic printing, It is the opening bracket and indicates the start of graphic printing.

Format:^GFd


Parameters:

     d= Description.it will not be printed on the report,Just better understanding of the code

          Default Value:NULL


作者xhhuang1979

0 0