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

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

package hpl;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.RenderingHints;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.awt.print.PageFormat;
import java.awt.print.Printable;
import java.awt.print.PrinterException;
import java.io.File;
import java.io.IOException;

import javax.imageio.IIOException;
import javax.imageio.ImageIO;
import javax.print.Doc;
import javax.print.DocFlavor;
import javax.print.DocPrintJob;
import javax.print.PrintException;
import javax.print.PrintService;
import javax.print.PrintServiceLookup;
import javax.print.SimpleDoc;
import javax.print.DocFlavor.URL;
import javax.print.attribute.DocAttributeSet;
import javax.print.attribute.HashAttributeSet;
import javax.print.attribute.HashDocAttributeSet;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.PrintRequestAttributeSet;
import javax.print.attribute.standard.MediaSizeName;
import javax.print.attribute.standard.PrinterName;
import javax.swing.JOptionPane;

import Kanban.LineInfo;
/**
 * java定位打印,把打印内容打到指定的地方。
 *
 * @author Harvey_Huang
 *
 */
public class LocatePrint implements Printable {
    private int PAGES = 0;
    private String printStr;
    private String fontname;
    private int fontsize;
    private String imagepath;
    private int locx;
    private int locy;
    private String  Singpage;
    private String Orientation="N";
    private String Fontflag="N";
    private String Sizeflag="N";
    private String message="OK";
    /*
     * Graphic指明打印的图形环境;PageFormat指明打印页格式(页面大小以点为计量单位,
     * 1点为1英寸的1/72,1英寸为25.4毫米。A4纸大致为595×842点);page指明页号
     * 
     */
    
   // int pp= 1;
    public int print(Graphics gp, PageFormat pf, int page)
            throws PrinterException {
    	//pp++;
        try {
        	
        try{	
        	
    	Graphics2D g2 = (Graphics2D) gp;
        g2.setPaint(Color.black); // 设置打印颜色为黑色
        
        //System.err.println("PPPPPPPP  : " + page);
        if (page >= PAGES) // 当打印页号大于需要打印的总页数时,打印工作结束
            return Printable.NO_SUCH_PAGE;
        g2.translate(pf.getImageableX(), pf.getImageableY());// 转换坐标,确定打印边界
        //g2.drawString(printStr, locx, locy);// 具体打印每一行文本,同时走纸移位
    
		
		
		
 		String[] itemarray;
 		String[] detailarray;
 		String typeflag = null;
 		Font font;
		
		itemarray=Singpage.split("\\^FS");
		//System.err.println("XZ:::::::" +itemarray.length);
		 for (int i=0; i<itemarray.length;i++){
			 typeflag="";
				System.out.println("Split  " + i +" : "+itemarray[i]);
				//System.out.println("-------------------------");
				detailarray= itemarray[i].split("\\^");
			  for (int j=0; j<detailarray.length;j++){
				  if(detailarray[j].length()>1){
				  if(detailarray[j].substring(0, 2).toUpperCase().equals("XA")){
					 // System.out.println("初始化"); 
					  PAGES=0;
					  printStr="";
					  fontname="Arial";
					  fontsize=14;
					  imagepath="";
					  locx=0;
					 locy=0;
				
				  }if(detailarray[j].substring(0, 2).toUpperCase().equals("FO")){
					//  System.out.println("找到FO"); 
					  String[] location=detailarray[j].substring(2, detailarray[j].length()).split(",");
					  if(location.length>1){ 
					     locx=Integer.parseInt(location[0]);
						 locy=Integer.parseInt(location[1]);
						//  System.out.println(location[1]); 
					  }
				  }
				  if(detailarray[j].substring(0, 2).toUpperCase().equals("FD")){
					 // System.out.println("找到FD"); 
					  printStr=detailarray[j].substring(2, detailarray[j].length());
					//  System.out.println(printStr); 
				  }
				  
			
				  if(detailarray[j].substring(0, 2).toUpperCase().equals("PA")){
					 // System.out.println("找到PA"); 
					  imagepath=detailarray[j].substring(2, detailarray[j].length());
					//  System.out.println(imagepath);
				  }
				  if(detailarray[j].substring(0, 2).toUpperCase().equals("PQ")){
					//  System.out.println("找到PQ");   
					  PAGES=Integer.parseInt(detailarray[j].substring(2, detailarray[j].length()));
					  
					    if (PAGES==0) // 当打印页号大于需要打印的总页数时,打印工作结束
				            return Printable.NO_SUCH_PAGE;
					//  System.out.println(PAGES); 
				  }
				  if(detailarray[j].substring(0, 2).toUpperCase().equals("AN")){
					 // System.out.println("找到AN");  
					  fontname=detailarray[j].substring(2, detailarray[j].length());
					//  System.out.println(fontname);
					  Fontflag="Y";
				  }
				  if(detailarray[j].substring(0, 2).toUpperCase().equals("AS")){
					 // System.out.println("找到AS");  
					  fontsize=Integer.parseInt(detailarray[j].substring(2, detailarray[j].length()));
					//  System.out.println(fontsize);   
					  Sizeflag="Y";
				  }
				  if(detailarray[j].substring(0, 2).toUpperCase().equals("OR")){
						 // System.out.println("找到AS");  
					  Orientation=detailarray[j].substring(2, detailarray[j].length());
						//  System.out.println(Orientation);
						  
					  }
				  if(detailarray[j].substring(0, 2).toUpperCase().equals("ST")){
					//  System.out.println("找到ST");
					 typeflag="ST";
				
				  }
				  if(detailarray[j].substring(0, 2).toUpperCase().equals("RP")){
					 // System.out.println("找到RP");
					 typeflag="RP";
					 
					 String[] rpstring=detailarray[j].substring(2, detailarray[j].length()).split(",");
					  if(rpstring.length>1){ 
			 
					
						  printStr="";
					 for(int h=0; h<Integer.parseInt(rpstring[1])+1;h++){
						 printStr=rpstring[0].toString()+printStr;
					 }
					  }
				
				  }
				  
				  if(detailarray[j].substring(0, 2).toUpperCase().equals("GF")){
					 // System.out.println("找到GF");  
					 typeflag="GF";
				  }
				  }
				//System.out.println(detailarray[j]);
			  }

		        
				   if (Orientation.toUpperCase().equals("R")){
						g2.rotate((3.14159/2), locx, locy);    
				   }
				   
				   if (Orientation.toUpperCase().equals("I")){
						g2.rotate(3.14159, locx, locy);    
				   }
				   
				   if (Orientation.toUpperCase().equals("B")){
						g2.rotate((3.14159*3/2), locx, locy);    
				   }
		        
			  if(typeflag.equals("ST")){
			//	 System.out.println(printStr+"    "+fontname+"    "+fontsize+"    ");  
				// N = Normal
				// R = Rotated, 90 degrees clockwise;
				// I = Inverted, 180 degrees
				 //B = Read from Bottom up, 270 degrees
				 if(Fontflag.equals("Y")||Sizeflag.equals("Y")){
					    font = new Font(fontname, Font.PLAIN, fontsize);// 创建字体
				        g2.setFont(font);	 
				 }
			    
		
			        // 打印当前页文本
			        g2.drawString(printStr, locx, locy); 
			        Fontflag="N";
			        Sizeflag="N";
			        

			  }
			  

			 if(typeflag.equals("GF")){
				 // System.out.println("打印准备");
				    BufferedImage img = ImageIO.read(new File(imagepath));
				   
				   // g2.rotate(3.14159, locx, locy);
					g2.drawImage(img, locx, locy, null);
					//  System.out.println("打印结束");
					//g2.rotate(-3.14159, locx, locy); 
			  }
			 
			  if(typeflag.equals("RP")){
					// System.out.println(printStr+"    "+fontname+"    "+fontsize+"    ");  
					 
				
				         font = new Font("Arial", Font.PLAIN, fontsize);// 创建字体
				        g2.setFont(font);
				        // 打印当前页文本
				        g2.drawString(printStr, locx, locy); 
					 
				  } 
			 
		 	   if (Orientation.toUpperCase().equals("R")){
					g2.rotate(-(3.14159/2), locx, locy);    
			   }
			   
			   if (Orientation.toUpperCase().equals("I")){
					g2.rotate(-3.14159, locx, locy);    
			   }
			   
			   if (Orientation.toUpperCase().equals("B")){
					g2.rotate(-(3.14159*3/2), locx, locy);    
			   }     
			   Orientation="N";
			 

			   
			   
			 // System.out.println("-------------------------");
		}
		
		
		 
		
    	} catch (IIOException e) {
			// TODO Auto-generated catch block
    		message="E004";
			e.printStackTrace();
		    return Printable.NO_SUCH_PAGE;
		}
		
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		    return Printable.NO_SUCH_PAGE;
		} 

	//	System.err.println("pppppp:::::::" + pp);
       return Printable.PAGE_EXISTS; // 存在打印页时,继续打印工作

    }
    // 打印内容到指定位置
    public String printContent(String hplpage,String Printq) {
   // 	System.err.println("tttttt:" + pp);
    	//String message="OK";
    	Singpage=hplpage;
    	
       // printStr = "aaaaa";// 获取需要打印的目标文本
       // fontname = "Free 3 of 9";// 获取需要打印的目标文本
       // fontsize=24;
       // imagepath="c:\\2.jpg";
       // locx=100;
       // locy=300;
  
        if (hplpage.length() > 0) // 当打印内容不为空时
        {
        	
        	  try {
        		 
        	DocPrintJob job = null;
            PAGES = 1; // 获取打印总页数
            // 指定打印输出格式
            DocFlavor flavor = DocFlavor.SERVICE_FORMATTED.PRINTABLE;
            // 定位默认的打印服务
            
            HashAttributeSet hs = new HashAttributeSet();  
            String printerName=Printq;  
            
            hs.add(new PrinterName(printerName,null));
            PrintService[] printService =PrintServiceLookup.lookupPrintServices(null, hs);  
           // PrintService printService = PrintServiceLookup.lookupDefaultPrintService();
            // 创建打印作业
            if(printService.length>0){
                 job = printService[0].createPrintJob();
        
     
            // 设置打印属性
            PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();
            // 设置纸张大小,也可以新建MediaSize类来自定义大小
            pras.add(MediaSizeName.ISO_A4);

  
            DocAttributeSet das = new HashDocAttributeSet();
            // 指定打印内容
            Doc doc = new SimpleDoc(this, flavor, das);
            // 不显示打印对话框,直接进行打印工作
  
          
                job.print(doc, pras); // 进行每一页的具体打印操作
            	//System.err.print("分析标识点5");
            }else{
           	 message="E002";
           }
            } catch (PrintException pe) {
                pe.printStackTrace();
                message="E001";
            }
        
        } else {
            // 如果打印内容为空时,提示用户打印将取消
            JOptionPane.showConfirmDialog(null,
                    "Sorry, Printer Job is Empty, Print Cancelled!",
                    "Empty", JOptionPane.DEFAULT_OPTION,
                    JOptionPane.WARNING_MESSAGE);
            message="E003";
        }
        
        return message;
    }
    
    

    public String analyze(String hpl,String Printq) {
       
    	String printstate="OK";
    	
    	  LocatePrint test = new LocatePrint();
 		String[] pagearray=hpl.split("\\^XZ");
 		//System.err.println("nnnnnnn======"+ pagearray.length);

 		for(int k=0; k<pagearray.length;k++){
 			
 			 printstate=test.printContent(pagearray[k].toString().trim(),Printq);
 			 
 		}
 		return printstate;
    }

    
    public static void main(String[] args) {
    	 String testdata="^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";
    	  LocatePrint test = new LocatePrint();
    	  System.out.print(test.analyze(testdata,"TESTPRINT"));
       
    }
}


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

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

欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值