目前出现的问题是会多出两张小纸(纸张大小为50mm*30mm),打印出来的一共三张,其中有条形码的一张位置还有偏移。生成的图片直接在本地打印不会出现这种情况。打印机首选项的也是自定义的纸业大小:50X30。
设置过打印区域,也没用,无论打印区域设置在多下面,主要java打印图片(PNG)就是固定会出三张小纸,修改了多次打印首选项和图片大小都不行。
// 传入文件和打印机名称
public static void JPGPrint(File file,String printerName,String printNum) throws PrintException {
String log = "C:\\log.txt";
FileWriter fw = null;
Integer number = Integer.valueOf(printNum);
File logFile = new File(log);
try {
if (!logFile.exists())
{
logFile.createNewFile();
}
fw = new FileWriter(log);
}catch (Exception e){
}
if (file == null) {
System.err.println("缺少打印文件");
}
FileInputStream fis = null;
try {
// 设置打印格式,如果未确定类型,可选择autosense
DocFlavor flavor = DocFlavor.INPUT_STREAM.PNG;
// 设置打印参数
PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
aset.add(new Copies(number)); //份数
// 设置打印区域
MediaPrintableArea mp = new MediaPrintableArea(25, 130, 25, 15, Size2DSyntax.MM);
aset.add(mp);
// aset.add(MediaSizeName.ISO_A10); //纸张
// // aset.add(Finishings.STAPLE);//装订
aset.add(OrientationRequested.PORTRAIT);
aset.add(PrintQuality.HIGH);
aset.add(Chromaticity.MONOCHROME);
// 定位打印服务
PrintService printService = null;
if (printerName != null) {
//获得本台电脑连接的所有打印机
PrintService[] printServices = PrinterJob.lookupPrintServices();
if(printServices == null || printServices.length == 0) {
System.out.print("打印失败,未找到可用打印机,请检查。");
return ;
}
//匹配指定打印机
for (int i = 0;i < printServices.length; i++) {
System.out.println(printServices[i].getName());
if (printServices[i].getName().contains(printerName)) {
printService = printServices[i];
break;
}
}
try {
fw.write(printService.toString());
fw.close();
}catch (Exception e){
}
if(printService==null){
System.out.print("打印失败,未找到名称为" + printerName + "的打印机,请检查。");
return ;
}
}
fis = new FileInputStream(file); // 构造待打印的文件流
DocAttributeSet das = new HashDocAttributeSet();
Doc doc = new SimpleDoc(fis, flavor, das);
DocPrintJob job = printService.createPrintJob(); // 创建打印作业
// 不显示打印对话框,直接进行打印工作
job.print(doc, aset);
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}finally
{
// 关闭打印的文件流
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
你打印机使用的纸张是A4,你要用自定义纸张类型