因公司业务扩展快递业务,有一个功能就是将发货人相关信息、收货人相关信息使用打印机打印出来,信息不多基本一页就搞定,不涉及到分页,如果涉及到分页可以在下面的代码进行完善,因为本人的业务代码就是从分页代码中自己提炼出来的,希望对有类似需求的大家有所帮助。
- 导入itext-asian.jar ,用于生成pdf文件时字体类型的支持包。
- 导入itextpdf-5.5.13.jar,用于生成pdf文件时主要支持包。
- 导入pdfbox-2.0.12.jar,用于pdf转图片时只要支持包。
- 导入fontbox-2.0.12.jar,pdfbox-2.0.12.jar的依赖包,不可缺少。
注:如果大家不知道jar去哪里下载,可以去 https://search.maven.org进行下载
1. 第一步:订单信息生成pdf文件,生成的文件目录为当前项目(windows/linux)目录同级
/**
* Description:订单信息转pdf文件
* @param req
* @param allocatePrintInfo 所要组装数据
* @return
* @param allocatePrintInfo
* @throws IOException
*/
public static String orderStrToPdf(HttpServletRequest req, Map allocatePrintInfo) throws IOException {
// 项目目录
String objectPath = req.getServletContext().getRealPath("");
// 获取项目目录的上一级目录
File file = new File(objectPath);
String orderPath = file.getParent() + File.separator + Setting.ORDER_PRINT_PATH;
//实际打印纸张大小:40mm x 60mm
Document document = new Document(PageSize.A9);
try {
if (FileUtils.createDirectory(orderPath)){
//pdf存储目录
String pdfPath = orderPath + File.separator + Setting.ORDER_PRINT_PATH + "_" + UUIDUtil.GeneratorUUIDKey()+".pdf";
//获取实例
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(pdfPath));
document.open();
//----------------属性设置-------------------------
//字体设置
Font font = FontFactory.getFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);//字体样式支持中文
font.setSize(2);//字体大小
//块中添加直线设置
LineSeparator lingSeparator = new LineSeparator();
lingSeparator.setLineWidth(0.1f);//直线宽度
lingSeparator.setLineColor(BaseColor.GRAY);//直线颜色
Chunk Chunk = new Chunk(lingSeparator);
//----------------打印信息-------------------------
//logo
Image img = Image.getInstance(Constant.UPLOAD_SERVERPATH+Constant.ORDER_PRINT_LOGO_PATH);//图片服务器路径
img.scaleToFit(5f, 5f);//大小
img.setAlignment(Image.ALIGN_CENTER);//位置居中
document.add(img);
//收件人信息
document.add(new Paragraph(allocatePrintInfo.get("jtdz").toString(),font));
document.add(new Paragraph(allocatePrintInfo.get("lxr").toString(),font));
document.add(new Paragraph(allocatePrintInfo.get("lxdh").toString(),font));
//块
document.add(Chunk);
//订单编号、商品名称
document.add(new Paragraph("订单编号:"+allocatePrintInfo.get("orderno").toString(),font));
//块
document.add(Chunk);
//发件人信息
document.add(new Paragraph("寄件人:"+allocatePrintInfo.get("dpyjdz").toString(),font));
document.add(new Paragraph("联系电话:"+allocatePrintInfo.get("phone").toString(),font));
document.close();
writer.close();
return pdfPath;
}else{
return null;
}
} catch (DocumentException e) {
e.printStackTrace();
return null;
} catch (FileNotFoundException e) {
e.printStackTrace();
return null;
}
}
2. 第二步:将生成完成的pdf文件转换成图片,目录同pdf文件目录
/**
* Description:订单pdf文件转img文件
* @param pdfPath
*/
public static String orderPdfToImg(String pdfPath) {
File file = new File(pdfPath);
PDDocument pdDocument;
try {
//order目录
String orderPath = file.getParent();
//转换后的img目录
String imgPath = orderPath + File.separator + Setting.ORDER_PRINT_PATH+"_"+UUIDUtil.GeneratorUUIDKey()+".png";
pdDocument = PDDocument.load(file);
PDFRenderer renderer = new PDFRenderer(pdDocument);
/* 第二位参数越大转换后越清晰,相对转换速度越慢 */
BufferedImage image = renderer.renderImageWithDPI(0, 1000);
ImageIO.write(image, "png", new File(imgPath));
pdDocument.close();
return imgPath;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
3. 第三步:将生成的png图片调用打印机打印
/**
* Description:打印订单图片信息
* @param imgPath
* @return
*/
public static int printOrderImgInfo(String imgPath) {
File file = new File(imgPath);
// 构建打印请求属性集
HashPrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();
// 设置打印格式
DocFlavor flavor = DocFlavor.INPUT_STREAM.PNG;
// 查找所有的可用的打印服务
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);
return 1;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
return 1;
}
4. 第四步:根据实际需求删除pdf、png图片
//删除临时图片
File pdfFile = new File(pdfPath);
File imgFile = new File(imgPath);
if (pdfFile.exists()) {
pdfFile.delete();
}
if (imgFile.exists()) {
imgFile.delete();
}
@Override
public int allocatePrint(String ddid,HttpServletRequest req) throws IOException {
Map allocatePrintInfo = dtOrderMapper.selectAllocatePrintInfo(ddid);
//生成pdf
String pdfPath = PrintUtils.orderStrToPdf(req,allocatePrintInfo);
if (null==pdfPath) {
return 0;
}
//pdf转图片
String imgPath = PrintUtils.orderPdfToImg(pdfPath);
if (null==imgPath) {
return 0;
}
//调用java print
int i = PrintUtils.printOrderImgInfo(imgPath);
if (i==1) {
//删除临时图片
File pdfFile = new File(pdfPath);
File imgFile = new File(imgPath);
if (pdfFile.exists()) {
pdfFile.delete();
}
if (imgFile.exists()) {
imgFile.delete();
}
return 1;
} else {
return 0;
}
}
package com.chw.system.util;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Map;
import javax.imageio.ImageIO;
import javax.print.Doc;
import javax.print.DocFlavor;
import javax.print.DocPrintJob;
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.servlet.http.HttpServletRequest;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;
import com.chw.system.common.Constant;
import com.chw.system.common.Setting;
import com.chw.util.UUIDUtil;
import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Chunk;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Font;
import com.itextpdf.text.FontFactory;
import com.itextpdf.text.Image;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.text.pdf.draw.LineSeparator;
/**
* Description: 打印公共类
* @date 2018年11月19日 下午3:22:34
*/
public class PrintUtils {
/**
* Description:订单信息转pdf文件
* @param req
* @param allocatePrintInfo 所要组装数据
* @return
* @param allocatePrintInfo
* @throws IOException
*/
public static String orderStrToPdf(HttpServletRequest req, Map allocatePrintInfo) throws IOException {
// 项目目录
String objectPath = req.getServletContext().getRealPath("");
// 获取项目目录的上一级目录
File file = new File(objectPath);
String orderPath = file.getParent() + File.separator + Setting.ORDER_PRINT_PATH;
//实际打印纸张大小:40mm x 60mm
Document document = new Document(PageSize.A9);
try {
if (FileUtils.createDirectory(orderPath)){
//pdf存储目录
String pdfPath = orderPath + File.separator + Setting.ORDER_PRINT_PATH + "_" + UUIDUtil.GeneratorUUIDKey()+".pdf";
//获取实例
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(pdfPath));
document.open();
//----------------属性设置-------------------------
//字体设置
Font font = FontFactory.getFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);//字体样式支持中文
font.setSize(2);//字体大小
//块中添加直线设置
LineSeparator lingSeparator = new LineSeparator();
lingSeparator.setLineWidth(0.1f);//直线宽度
lingSeparator.setLineColor(BaseColor.GRAY);//直线颜色
Chunk Chunk = new Chunk(lingSeparator);
//----------------打印信息-------------------------
//logo
Image img = Image.getInstance(Constant.UPLOAD_SERVERPATH+Constant.ORDER_PRINT_LOGO_PATH);//图片服务器路径
img.scaleToFit(5f, 5f);//大小
img.setAlignment(Image.ALIGN_CENTER);//位置居中
document.add(img);
//收件人信息
document.add(new Paragraph(allocatePrintInfo.get("jtdz").toString(),font));
document.add(new Paragraph(allocatePrintInfo.get("lxr").toString(),font));
document.add(new Paragraph(allocatePrintInfo.get("lxdh").toString(),font));
//块
document.add(Chunk);
//订单编号、商品名称
document.add(new Paragraph("订单编号:"+allocatePrintInfo.get("orderno").toString(),font));
//块
document.add(Chunk);
//发件人信息
document.add(new Paragraph("寄件人:"+allocatePrintInfo.get("dpyjdz").toString(),font));
document.add(new Paragraph("联系电话:"+allocatePrintInfo.get("phone").toString(),font));
document.close();
writer.close();
return pdfPath;
}else{
return null;
}
} catch (DocumentException e) {
e.printStackTrace();
return null;
} catch (FileNotFoundException e) {
e.printStackTrace();
return null;
}
}
/**
* Description:订单pdf文件转img文件
* @param pdfPath
*/
public static String orderPdfToImg(String pdfPath) {
File file = new File(pdfPath);
PDDocument pdDocument;
try {
//order目录
String orderPath = file.getParent();
//转换后的img目录
String imgPath = orderPath + File.separator + Setting.ORDER_PRINT_PATH+"_"+UUIDUtil.GeneratorUUIDKey()+".png";
pdDocument = PDDocument.load(file);
PDFRenderer renderer = new PDFRenderer(pdDocument);
/* 第二位参数越大转换后越清晰,相对转换速度越慢 */
BufferedImage image = renderer.renderImageWithDPI(0, 1000);
ImageIO.write(image, "png", new File(imgPath));
pdDocument.close();
return imgPath;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
/**
* Description:打印订单图片信息
* @param imgPath
* @return
*/
public static int printOrderImgInfo(String imgPath) {
File file = new File(imgPath);
// 构建打印请求属性集
HashPrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();
// 设置打印格式
DocFlavor flavor = DocFlavor.INPUT_STREAM.PNG;
// 查找所有的可用的打印服务
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);
return 1;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
return 1;
}
}