Fork me on GitHub

java套打快递单

package org.sq.common.utils;

import org.apache.commons.codec.binary.Base64;
import org.apache.http.entity.StringEntity;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.sq.core.tool.utils.OkHttpUtil;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.print.*;

public class EMSTest implements Printable{

private String[] value = null;// 所要打印的数据{ "001", "002", "003"};
private int[][] position = null;// 每个数据在图片中的坐标 { { 10, 50 }, { 30, 70 }, { 50, 90 }};

public static void main(String[] args) throws DocumentException {


printReport();




}

@Override
public int print(Graphics g, PageFormat pageFormat, int pageIndex) throws PrinterException {
// TODO Auto-generated method stub

if(pageIndex>0)
{
return Printable.NO_SUCH_PAGE;
}
Graphics2D g2d = (Graphics2D) g;
for (int i = 0; i < value.length; i++) {
String str = value[i];
int[] temp = position[i];
int x = temp[0];
int y = temp[1];
// 设置打印字体(字体名称、样式和点大小)
Font font = new Font("新宋体", Font.PLAIN, 9);
g2d.setFont(font); //设置字体
g2d.drawString(str, x, y);
}
return Printable.PAGE_EXISTS;
}

public String[] getValue() {
return value;
}

public void setValue(String[] value) {
this.value = value;
}

public int[][] getPosition() {
return position;
}

public void setPosition(int[][] position) {
this.position = position;
}

public static void printReport(){
PrinterJob pj = PrinterJob.getPrinterJob();//创建一个打印任务
PageFormat pf = PrinterJob.getPrinterJob().defaultPage();
Paper paper = pf.getPaper();
// 设置页面高和宽,A4纸为595,842
double pageWidth = 595;
double pageHeight = 810;
paper.setSize(pageWidth, pageHeight);
paper.setImageableArea(0, 0, pageWidth, pageHeight);
pf.setOrientation(PageFormat.LANDSCAPE); //设置打印方向,LANDSCAPE为横向,打印方向默认为纵向
pf.setPaper(paper);
EMSTest printTest=new EMSTest();
printTest.setValue(new String []{"寄件人", "", "张三","寄件地址", "", "山东济南高新区","收件人", "", "李四","收件地址", "", "山东济南历城区" });
printTest.setPosition(new int [][]{{ 30, 100 }, { 90,100}, { 150,100},{ 30, 130 }, { 90,130}, { 150,130} ,{ 30, 150 }, { 90,150}, { 150,150},{ 30, 170 }, { 90,170}, { 150,170} });
pj.setPrintable(printTest, pf);
if (pj.printDialog()) { //弹出打印对话框,打印对话框,用户可以通过它改变各种选项,例如:设置打印副本数目,页面方向,或者目标打印机。
try {
pj.print();
} catch (PrinterException e) {
e.printStackTrace();
}

}

}
}

posted @ 2020-03-10 09:01  梳碧湖砍柴的人  阅读(1024)  评论(0编辑  收藏  举报