本文用到的第三方工具冰蓝的Spire.PDF
1.首先导入依赖
我这里用的是项目路径下的jar包,如果可正常下载依赖 去掉框中的两行
2.使用流程
1.构建pdf文档模板
@GetMapping(value = "/sample/{id}")
public void sample(Model model, HttpServletRequest request, @PathVariable("id") String id,
HttpServletResponse response) {
JianguanSample sample= sampleMapper.selectJianguanSampleById(Long.valueOf(id));
String saveDir = "D:\\tpl模版\\cy\\"; //文件保存的路径
File file_saveDir = new File(saveDir);
if (!file_saveDir.exists()) {
file_saveDir.mkdirs();
}
//创建PdfDocument对象
PdfDocument pdf = new PdfDocument();
//这里因为用的免费版,pdf第一页会有水印,移除第一页去除水印
pdf.getPages().add();
PdfPageBase page = pdf.getPages().add();
pdf.getPages().removeAt(0);
//初始化y变量
double y = 15;
//初始化x变量
double x=0;
int sampleNum=sample.getSampleNum();
JianguanSampleCode code=new JianguanSampleCode();
String date=DateUtils.dateTime();
String maxCode=codeMapper.selectMaxSampleCode(date);
List<JianguanSampleCode> codeList=new ArrayList<>();
for (int i = 0; i < sampleNum; i++) {
//创建唯一编码
if (maxCode==null){
maxCode=date + String.format("%05d", 1);
}else {
Integer maxNum = Integer.parseInt(maxCode.substring(8));
maxNum++;
maxCode=date+String.format("%05d", maxNum);
}
//生成唯一编码
codeList.add(generateCode(sample,maxCode,i));
if (i+1==sampleNum){ //每次生成一个定位下一个条码位置
for (int j = 1; j <=codeList.size() ; j++) {
y=paint(codeList.get(j-1).getSampleCode(),page,x,y);
if(j%11==0){ //每隔11条码换列
x=x+180;
y=15;
}
if (j%33==0){ //每张超33个条码换纸
page= pdf.getPages().add();
x=0;
y=15;
}
}
}
}
String savePdfPath = saveDir + "/" + id+sample.getSiteId() + ".pdf";
pdf.saveToFile(savePdfPath);
FileUtils.inline1(savePdfPath, id, "pdf", request, response); //预览文件的方法
}
2.创建唯一的编码
private JianguanSampleCode generateCode(JianguanSample sample,String codeNum,int i){
//查询该场所此任务是否已生成编号
JianguanSampleCode code=new JianguanSampleCode();
code.setSiteId(sample.getSiteId());
code.setTaskId(sample.getId());
List<JianguanSampleCode> codeList= codeMapper.selectJianguanSampleCodeList(code);
if(codeList.size()<sample.getSampleNum()){
code.setSampleCode(codeNum);
code.setCreateTime(new Date());
codeMapper.insert(code);
return code;
}else {
return codeList.get(i);
}
}
3.画条码
private double paint(String maxCode,PdfPageBase page,double x,double y){
PdfCodabarBarcode codebar= new PdfCodabarBarcode(maxCode);
//设置条码的样式
codebar.setBarcodeToTextGapHeight(1f);
codebar.setBarHeight(50f);
codebar.setEnableCheckDigit(true);
codebar.setShowCheckDigit(true);
codebar.setTextDisplayLocation(TextLocation.Bottom);
PdfRGBColor black = new PdfRGBColor(Color.black);
codebar.setTextColor(black);
Point2D.Float point = new Point2D.Float();
point.setLocation(x,y); //条码的位置
codebar.draw(page,point);
y = codebar.getBounds().getY()+ codebar.getBounds().getHeight() + 5;
return y;
}
附***预览文件的工具类
public static void inline1(String savePath, String fileName,String ext,
HttpServletRequest request, HttpServletResponse response) {
OutputStream toClient = null;
try {
//String path = savePath + "/" + fileName + "." + ext;
File file = new File(savePath);
if (!file.exists()) {
// 不存在
request.setAttribute("name", fileName);// 返回预览文件不存在
throw new Exception("模板未找到");
}
if (!inOnLineExt(ext)) {
response.setContentType("application/octet-stream");
}
// 根据不同浏览器 设置response的Header
String userAgent = request.getHeader("User-Agent").toLowerCase();
if (userAgent.indexOf("msie") > 0 ||(userAgent.indexOf("gecko")>0 && userAgent.indexOf("rv:11")>0)) {
// ie浏览器
// System.out.println("ie浏览器");
response.addHeader("Content-Disposition", "inline;filename="
+ URLEncoder.encode(fileName+"."+ext, "utf-8"));
} else {
response.addHeader("Content-Disposition", "inline;filename="
+ new String((fileName+"."+ext).getBytes("utf-8"), "ISO8859-1"));
}
response.addHeader("Content-Length", "" + file.length());
response.setContentType("application/"+ext+";charset=UTF-8");
// 以流的形式预览文件
InputStream fis = new BufferedInputStream(new FileInputStream(savePath));
byte[] buffer = new byte[fis.available()];
fis.read(buffer);
fis.close();
toClient = new BufferedOutputStream(response.getOutputStream());
toClient.write(buffer);
toClient.flush();
} catch (Exception e) {
e.printStackTrace();
response.reset();
} finally {
if (toClient != null) {
try {
toClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
4.前端绑定事件对应打印方法并预览
效果图如下:
另外免费版的spire.pdf限制了10页(如果是打印或转换页码不多的文件还是够用的)