1、整体
2、实例
以下代码个人已经执行–非转载
1、DocPrintJobHandler --已经执行
打印JPG图片格式的文件,本次采用的Java原生的打印方式。
优点:jdk的原生支持的打印功能,可直接使用,支持设置各项打印参数。
缺点:局限性较大,只能打印一些图片和文本格式的文
package com.my.print.handler;
import org.springframework.util.StringUtils;
import javax.print.*;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.PrintRequestAttributeSet;
import javax.print.attribute.standard.Copies;
import javax.print.attribute.standard.Sides;
import java.awt.print.PrinterJob;
import java.io.*;
/**
* @author lixiong
* @Date: 2022/4/14
* @Description:
*/
public class DocPrintJobHandler {
/*
* 局限性较大,只能打印一些图片和文本格式的文件。
*
*
* */
public static void main(String[] args) throws PrintException, IOException {
String filePath = "C:\\Users\\13987\\Desktop\\a.png";
File file = new File(filePath);
byte[] bytesFile = File2byte(file);
// ”[B“ 类型否则会报错
Doc doc = new SimpleDoc(bytesFile, DocFlavor.BYTE_ARRAY.PNG, null);
// 获取默认打印机
PrintService ps = PrintServiceLookup.lookupDefaultPrintService();
// 根据打印机的名称查找打印机
// ps = getPrintService("HPB0227A5BE9CF(HP Laser MFP 131 133 135-138)");
DocPrintJob job = ps.createPrintJob();
// 设置打印参数
PrintRequestAttributeSet attributeSet = new HashPrintRequestAttributeSet();
// 份数 调取打印机有效
attributeSet.add(new Copies(2));
// 纸张
// aset.add(MediaSize.ISO.A4);
//单双面
// attributeSet.add(Sides.DUPLEX);
job.print(doc, attributeSet);
}
/**
* 将文件转换成byte数组
* @param
* @return
*/
public static byte[] File2byte(File tradeFile){
byte[] buffer = null;
try
{
FileInputStream fis = new FileInputStream(tradeFile);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] b = new byte[1024];
int n;
while ((n = fis.read(b)) != -1)
{
bos.write(b, 0, n);
}
fis.close();
bos.close()