packagecom.example.demo; importcom.google.zxing.BarcodeFormat; importcom.google.zxing.WriterException; importcom.google.zxing.client.j2se.MatrixToImageWriter; importcom.google.zxing.common.BitMatrix; importcom.google.zxing.oned.Code128Writer; importorg.apache.commons.lang3.StringUtils; importjavax.print.PrintService; importjavax.print.attribute.HashPrintRequestAttributeSet; importjavax.print.attribute.PrintRequestAttributeSet; importjavax.print.attribute.standard.Copies; importjava.awt.*; importjava.awt.image.BufferedImage; importjava.awt.print.*; importjava.io.IOException; importjava.util.ArrayList; publicclassPdfTaoDaPrinterDemoimplementsPrintable{ privatestaticStringprinterName="Microsoft Print to PDF"; privateString[] value= {"测试","信息与计算科学","数学物理学院","2023年9月1日","XX校区","2023","7","24","1234567890","1234567890"}; privateint[][] positions= {{70,220},{150,400},{300,400},{150,420},{300,420},{490,375},{530,375},{560,375},{560,100},{585,142}}; publicstaticvoidmain(String []args) throwsException { PrintServiceprintService=getPrintService(); if(printService==null){ //无可用的打印机System.out.println("打印失败,未找到可用打印机,请检查。"); }else{ PdfTaoDaPrinterDemopdfTaoDaPrinterDemo=newPdfTaoDaPrinterDemo(); printReport(pdfTaoDaPrinterDemo,printService); } } publicintprint(Graphicsg,PageFormatpf,intpageIndex){ if(pageIndex>0){ returnPrintable.NO_SUCH_PAGE; } Graphics2Dg2d= (Graphics2D) g; for(inti=0;i<value.length;i++){ Stringstr=value[i]; inttemp[] =positions[i]; intx=temp[0]; inty=temp[1]; if(i==0){ Fontfont=newFont("微软雅黑",Font.PLAIN,16); g2d.setFont(font); g2d.drawString(str,x,y); }elseif((i>=5&&i<=7)){ Fontfont=newFont("宋体",Font.PLAIN,12); g2d.setFont(font); g2d.drawString(str,x,y); }elseif(i>0&&i<5&&i!=2){ Fontfont=newFont("宋体",Font.PLAIN,16); g2d.setFont(font); g2d.drawString(str,x,y); }elseif(i==2){ if(str.contains("(") ||str.contains("(")){ Fontfont=newFont("宋体",Font.PLAIN,14); g2d.setFont(font); java.util.List<String>line_list=newArrayList<String>(); if(str.contains("(")){ StringpreStr=str.substring(0,str.indexOf("(")); StringaffStr=str.substring(str.indexOf("(")+1); line_list.add(preStr); line_list.add(affStr); }elseif(str.contains("(")){ StringpreStr=str.substring(0,str.indexOf("(")); StringaffStr=str.substring(str.indexOf("(")); line_list.add(preStr); line_list.add(affStr); } for(intj=0;j<line_list.size();j++){ Stringline_str=line_list.get(j); intstrWidth=g2d.getFontMetrics().stringWidth(line_str); intwordStartX=x+(+150-strWidth) /2; g.drawString(line_str, wordStartX, y+(j-1)*14) ;//35为每行的高度 } }else { Fontfont=newFont("宋体",Font.PLAIN,16); g2d.setFont(font); g2d.drawString(str, x, y); } } elseif(i==8){ BufferedImagelogoImg=null; try { logoImg=insertWords(getBarcode(str),str); g2d.drawImage(logoImg, x, y, logoImg.getWidth(), logoImg.getHeight(), null); } catch (Exceptione) { e.printStackTrace(); }finally { if(logoImg!=null){ logoImg.flush(); } } } } returnPrintable.PAGE_EXISTS; } privatevoidsetColorWhite(Graphics2Dg2d){ g2d.setColor(Color.WHITE); //填充整个屏幕g2d.fillRect(0,0,600,600); //设置笔刷g2d.setColor(Color.BLACK); } publicBufferedImageinsertWords(BufferedImageimage, Stringwords){ // 新的图片,把带logo的二维码下面加上文字if (StringUtils.isNotEmpty(words)) { BufferedImageoutImage=newBufferedImage(image.getWidth(), image.getHeight()+20, BufferedImage.TYPE_INT_RGB); Graphics2Dg2d=outImage.createGraphics(); setColorWhite(g2d); // 画条形码到新的面板g2d.drawImage(image, 0, 0, image.getWidth(), image.getHeight(), null); // 画文字到新的面板Colorcolor=newColor(0, 0, 0); g2d.setColor(color); // 字体、字型、字号g2d.setFont(newFont("新宋体", Font.PLAIN, 10)); //文字长度intstrWidth=g2d.getFontMetrics().stringWidth(words); //总长度减去文字长度的一半 (居中显示)intwordStartX=(image.getWidth() -strWidth) /2; intwordStartY=image.getHeight()+10; // 画文字g2d.drawString(words, wordStartX, wordStartY); g2d.dispose(); outImage.flush(); returnoutImage; } returnnull; } publicBufferedImagegetBarcode(Strings) throwsIOException { try { Code128Writerwriter=newCode128Writer(); BitMatrixbar=writer.encode(s, BarcodeFormat.CODE_128, 80, 50, null); returnMatrixToImageWriter.toBufferedImage(bar); } catch (WriterExceptione){ thrownewRuntimeException(e); } } privatestaticvoidprintReport(PdfTaoDaPrinterDemopdfTaoDaModel, PrintServiceprintService){ PrinterJobprinterJob=PrinterJob.getPrinterJob(); try { printerJob.setPrintService(printService); PageFormatpf=printerJob.defaultPage(); Paperpaper=pf.getPaper(); doublepageWidth=496; doublepageHeight=765; paper.setSize(pageWidth,pageHeight); paper.setImageableArea(0,0,pageWidth,pageHeight); pf.setOrientation(PageFormat.LANDSCAPE); pf.setPaper(paper); printerJob.setPrintable(pdfTaoDaModel,pf); PrintRequestAttributeSetaset=newHashPrintRequestAttributeSet(); aset.add(newCopies(1)); //份数printerJob.print(aset); } catch (PrinterExceptione) { e.printStackTrace(); System.out.println("PrinterException:"+e.getLocalizedMessage()); } } privatestaticPrintServicegetPrintService(){ if (printerName!=null) { // 查找并设置打印机//获得本台电脑连接的所有打印机PrintService[] printServices=PrinterJob.lookupPrintServices(); if(printServices==null||printServices.length==0) { System.out.println("打印失败,未找到可用打印机,请检查。"); returnnull; } PrintServiceprintService=null; //匹配指定打印机for (inti=0;i<printServices.length; i++) { System.out.println(printServices[i].getName()); if (printServices[i].getName().contains(printerName)) { printService=printServices[i]; } } if(printService!=null){ returnprintService; }else{ System.out.println("打印失败,未找到名称为"+printerName+"的打印机,请检查。"); returnnull; } } returnnull; } publicString[] getValue() { returnvalue; } publicvoidsetValue(String[] value) { this.value=value; } publicint[][] getPositions() { returnpositions; } publicvoidsetPositions(int[][] positions) { this.positions=positions; } }
<dependency><groupId>com.google.zxing</groupId><artifactId>core</artifactId><version>3.0.0</version></dependency><dependency><groupId>com.google.zxing</groupId><artifactId>javase</artifactId><version>3.0.0</version></dependency>
printerName替换为实际的打印机名称,这里面需要服务器跟打印机网络互联,本例子是本机的Microsoft Print to PDF,即可导出为pdf。value是套打的内容,positions为套打的点位,主要是调整这三个地方,根据套打的模板去定位。字体颜色和大小可以修改print方法里的相应位置,也可以自己针对特定的位置调整,二维码采用的是zxing第三方库,引入相应的依赖以后,代码可以直接运行看到输出效果