java生成图片并打印

时间:2023-02-09 21:17:46

最近做一个点菜宝项目,需要打印java后台嗲用打印机并且打印票据,思路是这样 先填充数据,然后生成图片,调用打印机直接打印图片!废话不多说直接上代码!

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.util.Date;
import java.util.List;

import com.sarnath.orderdishes.vo.OrderDishes;
import com.sarnath.orderdishes.vo.OrderForm;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

 

public class CreateImage{
 public static BufferedImage image;
 
 public static String createImage(String fileLocation) {
 try {
 FileOutputStream fos = new FileOutputStream(fileLocation);
 BufferedOutputStream bos = new BufferedOutputStream(fos);
 JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(bos);
 encoder.encode(image);
 bos.close();
 
 } catch (Exception e) {
 e.printStackTrace();
 }
 return fileLocation;
 }
 
 
 
 public static String  graphicsGeneration(List<OrderDishes> orderDishesList,OrderForm orderForm) {
 createDir("C://orderForm//image");
 int imageWidth = 400;//图片的宽度
 int imageHeight = 400+orderDishesList.size()*200;//图片的高度
 image = new BufferedImage(imageWidth, imageHeight, BufferedImage.TYPE_INT_RGB);
 Graphics graphics = image.getGraphics();
 graphics.setColor(Color.WHITE);
 graphics.fillRect(0, 0, imageWidth, imageHeight);
 graphics.setColor(Color.BLACK);
 Font fontTitle=new Font("楷体",Font.BOLD,35);
 graphics.setFont(fontTitle);
 graphics.drawString("点菜宝", 40, 25);
 Font font=new Font("宋体",Font.PLAIN,25);
 graphics.setFont(font);
 graphics.drawString("订单编号: " + orderForm.getFormCode(), 50, 75);
 graphics.drawString("对应楼层: " + orderForm.getDisk().getFloor().getFloorNum(), 50, 100);
 graphics.drawString("对应餐桌: " + orderForm.getDisk().getDiskCode(), 50, 125);
 graphics.drawString("订单时间: " + orderForm.getFormDate(), 50, 150);
 Integer  y=175;
 for(OrderDishes od:orderDishesList){
  y=y+25;
  graphics.drawString("菜名 : " +od.getDishes().getDishesName() , 50, y);
  y=y+25;
  graphics.drawString("价格 : " + od.getDishes().getPrice(), 50, y);
  y=y+25;
  graphics.drawString("份数: " + od.getNum(), 50, y);
  y=y+25;
  graphics.drawString("备注: " + od.getMemo(), 50, y);
  y=y+25;
 }
 //ImageIcon imageIcon = new ImageIcon(imgurl);
 //graphics.drawImage(imageIcon.getImage(), 230, 0, null);
 //改成这样:
 BufferedImage bimg = null;
 try {
    bimg = javax.imageio.ImageIO.read(new java.io.File("C://orderForm//image"+DateUtil.DateToStringHHSSMM(new Date())+orderForm.getFormCode()+".jpg"));
 } catch (Exception e) {
 }
 if(bimg!=null)
 graphics.drawImage(bimg, 230, 0, null);
 graphics.dispose();
 String  imageUrl=createImage("C://orderForm//image//"+DateUtil.DateToStringHHSSMM(new Date())+orderForm.getFormCode()+".jpg");
 return imageUrl;
 }

 
 public static boolean createDir(String destDirName) {
     File dir = new File(destDirName);
     if(dir.exists()) {
      System.out.println("创建目录" + destDirName + "失败,目标目录已存在!");
      return false;
     }
     if(!destDirName.endsWith(File.separator))
      destDirName = destDirName + File.separator;
     // 创建单个目录
     if(dir.mkdirs()) {
      System.out.println("创建目录" + destDirName + "成功!");
      return true;
     } else {
      System.out.println("创建目录" + destDirName + "成功!");
      return false;
     }
 }

}

生成图片 然后嗲用java自带的打印服务进行打印!

package com.sarnath.orderdishes.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.net.InetSocketAddress;
import java.net.Socket;

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.ServiceUI;
import javax.print.SimpleDoc;
import javax.print.attribute.DocAttributeSet;
import javax.print.attribute.HashDocAttributeSet;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.PrintRequestAttributeSet;
import javax.print.attribute.standard.MediaSizeName;
import javax.swing.JOptionPane;

public class PrintUtil {
     public static void printJava() { 
//         JFileChooser fileChooser = new JFileChooser(); //创建打印作业 
//         int state = fileChooser.showOpenDialog(null); 
//         if(state == fileChooser.APPROVE_OPTION){ 
//             File file = fileChooser.getSelectedFile();
             File file = new File("E:/孙小娇简历.docx"); //获取选择的文件 
             //构建打印请求属性集 
             HashPrintRequestAttributeSet pras = new HashPrintRequestAttributeSet(); 
             //设置打印格式,因为未确定类型,所以选择autosense 
             DocFlavor flavor = DocFlavor.INPUT_STREAM.AUTOSENSE; 
             //查找所有的可用的打印服务 
             PrintService printService[] = PrintServiceLookup.lookupPrintServices(flavor, pras);
            
             //定位默认的打印服务 
             PrintService defaultService = PrintServiceLookup.lookupDefaultPrintService(); 
             //显示打印对话框 
             PrintService service = ServiceUI.printDialog(null, 200, 200, printService,  
                     defaultService, flavor, pras); 
             if(service != null){ 
                 try { 
                     DocPrintJob job = service.createPrintJob(); //创建打印作业 
                     FileInputStream fis = new FileInputStream(file); //构造待打印的文件流 
                     DocAttributeSet das = new HashDocAttributeSet(); 
                     Doc doc = new SimpleDoc(fis, flavor, das); 
                     job.print(doc, pras); 
                     fis.close();
                 } catch (Exception e) { 
                     e.printStackTrace(); 
                 } 
             
     } 
 }
    
     public static boolean printNoDriver(String ip, int port, String str,int skip)
       throws Exception{
           Socket client=new java.net.Socket();
         
           PrintWriter socketWriter;
           client.connect(new InetSocketAddress(ip,port),1000); // 创建一个 socket
           socketWriter = new PrintWriter(client.getOutputStream());// 创建输入输出数据流
           /* 纵向放大一倍 */
           socketWriter.write(0x1c);
           socketWriter.write(0x21);
           socketWriter.write(8);
           socketWriter.write(0x1b);
           socketWriter.write(0x21);
           socketWriter.write(8);
           socketWriter.println(str);
           for(int i=0;i<skip;i++){
               socketWriter.println("");// 打印完毕自动走纸
           }
           return true;
        }
    
     public static void printImage() {     
      FileInputStream textStream = null;  
       try {
     textStream = new FileInputStream("E:\\123.htm");
    } catch (FileNotFoundException e1) {
     // TODO Auto-generated catch block
     e1.printStackTrace();
    } 
      //String printStr = "打印测试内容";// 获取需要打印的目标文本  
           if (textStream != null) // 当打印内容不为空时 
            {            // 指定打印输出格式       
            DocFlavor flavor = DocFlavor.INPUT_STREAM.POSTSCRIPT;//SERVICE_FORMATTED.PRINTABLE 
            // 定位默认的打印服务      
            PrintService printService = PrintServiceLookup.lookupDefaultPrintService();  // 创建打印作业  
            DocFlavor[] d=printService.getSupportedDocFlavors();
            for(DocFlavor df:d){
             System.out.println(df.getMimeType());
            }
           if( printService.isDocFlavorSupported(flavor)){
            System.out.println("支持");
           };
            DocPrintJob job = printService.createPrintJob();            // 设置打印属性     
            PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();            // 设置纸张大小,也可以新建MediaSize类来自定义大小   
            pras.add(MediaSizeName.ISO_A4); 
            DocAttributeSet das = new HashDocAttributeSet();            // 指定打印内容        
            Doc doc = new SimpleDoc(textStream, flavor, das);            // 不显示打印对话框,直接进行打印工作         
             try {
       job.print(doc, pras);// 进行每一页的具体打印操作          
       System.out.println("打印成功了");
      } catch (PrintException e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
      }
              
            } else {         
             // 如果打印内容为空时,提示用户打印将取消          
             JOptionPane.showConfirmDialog(null,"Sorry, Printer Job is Empty, Print Cancelled!","Empty", JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE); 
             }
     }
     public static void printNoWindow(String imageUrl) {     
      FileInputStream textStream = null;  
       try {
     textStream = new FileInputStream(imageUrl);
    } catch (FileNotFoundException e1) {
     // TODO Auto-generated catch block
     e1.printStackTrace();
    } 
      //String printStr = "打印测试内容";// 获取需要打印的目标文本  
           if (textStream != null) // 当打印内容不为空时 
            {            // 指定打印输出格式       
            DocFlavor flavor = DocFlavor.INPUT_STREAM.JPEG;//SERVICE_FORMATTED.PRINTABLE 
            //构建打印请求属性集 
               HashPrintRequestAttributeSet pras = new HashPrintRequestAttributeSet(); 
               //查找所有的可用的打印服务 
               PrintService allPrintService[] = PrintServiceLookup.lookupPrintServices(flavor, pras);
            // 定位默认的打印服务      
            PrintService printService = PrintServiceLookup.lookupDefaultPrintService();  // 创建打印作业  
            DocFlavor[] d=printService.getSupportedDocFlavors();
            for(DocFlavor df:d){
             System.out.println(df.getMimeType());
            }
           if( printService.isDocFlavorSupported(flavor)){
            System.out.println("支持");
           };
            DocPrintJob job = printService.createPrintJob();            // 设置打印属性     
            pras.add(MediaSizeName.ISO_A4); 
            DocAttributeSet das = new HashDocAttributeSet();            // 指定打印内容        
            Doc doc = new SimpleDoc(textStream, flavor, das);            // 不显示打印对话框,直接进行打印工作         
             try {
       job.print(doc, pras);// 进行每一页的具体打印操作          
       System.out.println("打印成功了");
      } catch (PrintException e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
      }
              
            } else {         
             // 如果打印内容为空时,提示用户打印将取消          
             JOptionPane.showConfirmDialog(null,"Sorry, Printer Job is Empty, Print Cancelled!","Empty", JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE); 
             }
     }
    
    
}