java 二维码生成及其标签打印

本文主要内容

  • 二维码生成
  • 二维码标签预览及打印

二维码生成

笔者此次的二维码是通过调用第三方接口生成的,具体流程如下:

  1. 根据规范要求调用第三方接口,返回二维码下载地址及二维码图片的属性值(图片大小等)
  2. 根据返回的值获取二维码下载地址,根据地址下载二维码图片,保存至本地磁盘及记录数据信息
  3. 扫描二维码跳转相应地址,显示资产的基本信息
  4. 最终生成的二维码如下图所示:
    在这里插入图片描述

预览并批量打印二维码标签

先给大家看最终预览效果:
在这里插入图片描述
事先配置好标签打印机(标签亚银纸、树脂碳带等),点击右上方打印按钮,即可打印。打印标签效果如图:
在这里插入图片描述

前端

目前前端用的是 easyui,直接上代码:

{
                    id: 'print',
                    text: '打印',
                    iconCls: 'icon-print',
                    handler: function () {
                        var rows = $('#dg').datagrid('getSelections');
                        if (rows.length > 0) {
                            var ids = "";
                            for (var i = 0; i < rows.length; i++) {
                                ids += rows[i].ID + ","
                            }
                            var id = ids.substring(0, ids.length - 1);
                            window.open("${hostPrefix}swjEqu/qrCodeManageAction!printQr.action?id=" + id);
                        } else {
                            alert("请选择一条记录!");
                        }
                    }
                }

后端

主要用 itextPdf 处理


package com.whread.common.web.action;

import com.opensymphony.xwork2.ActionSupport;

import org.apache.log4j.Logger;
import org.apache.struts2.interceptor.ApplicationAware;
import org.apache.struts2.interceptor.ParameterAware;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
import org.apache.struts2.interceptor.SessionAware;
import org.apache.struts2.util.ServletContextAware;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.Writer;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@SuppressWarnings("serial")
public class BaseAction extends ActionSupport implements ServletRequestAware,
		ServletContextAware, ServletResponseAware, SessionAware,
		ApplicationAware, ParameterAware {

	protected HttpServletRequest request;
	protected HttpServletResponse response;
	protected HttpSession httpSession;
	protected Map session;
	protected Map parameters;
	protected Map application;
	private ServletContext servletContext;
	protected String msg;

	protected Logger log = Logger.getLogger(this.getClass());

	public BaseAction() {
		super();
	}

	public HttpServletRequest getServletRequest() {
		return this.request;
	}

	public void setServletRequest(HttpServletRequest req) {
		this.request = req;
		if (request != null) {
			this.httpSession = request.getSession();
		}
	}

	public HttpSession getHttpSession() {
		return this.httpSession;
	}

	public HttpServletResponse getServletResponse() {
		return this.response;
	}

	public void setServletResponse(HttpServletResponse rep) {
		this.response = rep;
	}

	public Map getSession() {
		return this.session;
	}

	public void setSession(Map session) {
		this.session = session;
	}

	public ServletContext getServletContext() {
		return this.servletContext;
	}

	public void setServletContext(ServletContext servletContext) {
		this.servletContext = servletContext;
	}

	public Map getApplication() {
		return this.application;
	}

	public void setApplication(Map application) {
		this.application = application;
	}

	public Map getParameters() {
		return this.parameters;
	}

	public void setParameters(Map parameters) {
		this.parameters = parameters;
	}

	public HttpServletRequest getRequest() {
		return request;
	}

	public void setRequest(HttpServletRequest request) {
		this.request = request;
	}

	public HttpServletResponse getResponse() {
		return response;
	}

	public void setResponse(HttpServletResponse response) {
		this.response = response;
	}

	public String getMsg() {
		return msg;
	}

	public void setMsg(String msg) {
		this.msg = msg;
	}

	public Logger getLog() {
		return log;
	}

	public void setLog(Logger log) {
		this.log = log;
	}

	public void setHttpSession(HttpSession httpSession) {
		this.httpSession = httpSession;
	}

	public void writeResponseTxt(String responseTxt) {
		Writer writer;
		try {
			this.response.setContentType("text/html;charset=UTF-8");
			writer = this.response.getWriter();
			writer.write(responseTxt);
			writer.flush();
			writer.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	protected void responseOutWithJson(String content) {
		try (PrintWriter out = response.getWriter()) {
			response.setContentType("application/json;charset=UTF-8");
			out.println(content);
			out.flush();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}


//需导入的核心jar包
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;
import com.itextpdf.text.pdf.draw.DottedLineSeparator;

public class QrCodeManageAction extends BaseAction {
/**
     * 预览二维码信息,并可批量打印
     * @return
     */
    public void printQr() {
        String path = request.getServletContext().getRealPath("/");
        response.setContentType("application/pdf");
        try {
            response.setHeader("content-disposition", "filename=资产信息.pdf");
            OutputStream out = response.getOutputStream();
            float[] rectSize = {4, 1, 4, 2};
            printQrInfo(out, rectSize, path);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

/**
	 * 预览、打印二维码pdf
	 * @param out
	 * @param reportMap
	 * @param rectSize
	 * @param path
	 */
    public static void printQrInfo(OutputStream out, float[] rectSize, String path) throws IOException, DocumentException {
    
    // SIMHEI.TTF 文件字体文件,可下载至本地 ,此处更改为相应本地地址
		BaseFont bfChinese = BaseFont.createFont( path+"/fonts/SIMHEI.TTF", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
		Rectangle rect = new Rectangle(170F, 85.0F);// A4纸张
		rect.setBackgroundColor(BaseColor.WHITE);
		//方正小标送简 常规 -标签标题
		BaseFont bfChinese1 = BaseFont.createFont( path+"/fonts/FZXBSJW.TTF", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);

		Font song22 = new Font(bfChinese1, 8, Font.BOLD);
		BaseFont bfChinese2 = BaseFont.createFont( path+"/fonts/SIMFANG.TTF", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
		Font fang16 = new Font(bfChinese2, 6, Font.BOLD);
		BaseFont bfChinese3 = BaseFont.createFont( path+"/fonts/simkai.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
		Font kai16 = new Font(bfChinese3, 7, Font.BOLD);
		//西文 16号 Times New Roman
		BaseFont bfChinese4 = BaseFont.createFont( path+"/fonts/TIMES.TTF", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
		Font roman16 = new Font(bfChinese4, 7, Font.BOLD);

		//人名 方正行楷 FZXKJW.TTF
		BaseFont bfChinese5 = BaseFont.createFont( path+"/fonts/FZXKJW.TTF", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
		Font fzxk16 = new Font(bfChinese5, 9);

		Document doc = new Document(rect, rectSize[0], rectSize[1], rectSize[2], rectSize[3]);

		PdfWriter writer = PdfWriter.getInstance(doc, out);

		writer.setPdfVersion(PdfWriter.PDF_VERSION_1_2);
		//文档属性
		doc.addTitle("资产信息");
		doc.open();

		//加入内容
		PdfPTable tab = new PdfPTable(1);
		PdfPCell cell = new PdfPCell();

		for (int i=0;i<infos.size();i++) {
			createPrintQrInfo(doc, tab, cell, song22, fang16, kai16, roman16, fzxk16);
		}
		doc.newPage();
		doc.close();
    }

private static void createPrintQrInfo(Document doc, PdfPTable tab, PdfPCell cell, Font titleFont1, Font  valueFont,  Font kai16, Font roman16, Font fzxk16) throws DocumentException {
		//这里打印的是  60mm * 30mm 大小的标签,故这里参数很重要
		int [] cellWidth = {35,70,65};
		tab = new PdfPTable(3);
		tab.setLockedWidth(true);
		tab.setTotalWidth(165);
		tab.getDefaultCell().setMinimumHeight(15f);
		tab.setHorizontalAlignment(Element.ALIGN_CENTER);
		tab.setWidths(cellWidth);

		cell = PdfCellUtill.createCell(ObjUtils.defaultIfNull("", titleFont1,PdfPCell.ALIGN_CENTER,PdfPCell.ALIGN_MIDDLE,3,0);
		cell.setFixedHeight(15f);
		cell.setBorderWidthTop(0.5f);
		cell.setBorderWidthLeft(0.5f);
		cell.setBorderWidthRight(0.5f);
		cell.setUseAscender(true);
		cell.setVerticalAlignment(cell.ALIGN_MIDDLE);
		cell.setHorizontalAlignment(Element.ALIGN_CENTER); //水平居中
		cell.setVerticalAlignment(Element.ALIGN_MIDDLE); //垂直居中
		tab.addCell(cell);

		cell = PdfCellUtill.createCell("资产名称", kai16,PdfPCell.ALIGN_CENTER,PdfPCell.ALIGN_MIDDLE,1,0);
		cell.setFixedHeight(15f);
		cell.setBorderWidthTop(0.5f);
		cell.setBorderWidthLeft(0.5f);
		tab.addCell(cell);
		cell = PdfCellUtill.createCell("资产名称1", valueFont,PdfPCell.ALIGN_LEFT,PdfPCell.ALIGN_MIDDLE,1,0);
		cell.setBorderWidthTop(0.5f);
		cell.setBorderWidthLeft(0.5f);
		tab.addCell(cell);
		
		Image imageQjPhoto = null;
		// 二维码图片路径
		try{
			imageQjPhoto = Image.getInstance("g://qrcode.png");
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		imageQjPhoto.scaleAbsoluteWidth(59);
		imageQjPhoto.scaleAbsoluteHeight(59);
		cell = PdfCellUtill.createCell("", valueFont,PdfPCell.ALIGN_CENTER,PdfPCell.ALIGN_MIDDLE,1,4);
		cell.setBorderWidthTop(0.5f);
		cell.setBorderWidthLeft(0.5f);
		cell.setBorderWidthRight(0.5f);
		cell.setBorderWidthBottom(0.5f);
		cell.addElement(imageQjPhoto);
		tab.addCell(cell);

		cell = PdfCellUtill.createCell("资产编号", kai16,PdfPCell.ALIGN_CENTER,PdfPCell.ALIGN_MIDDLE,1,0);
		cell.setFixedHeight(15f);
		cell.setBorderWidthTop(0.5f);
		cell.setBorderWidthLeft(0.5f);
		tab.addCell(cell);
		cell = PdfCellUtill.createCell("资产编号1", roman16,PdfPCell.ALIGN_LEFT,PdfPCell.ALIGN_MIDDLE,1,0);
		cell.setBorderWidthTop(0.5f);
		cell.setBorderWidthLeft(0.5f);
		tab.addCell(cell);

		cell = PdfCellUtill.createCell("购置日期", kai16,PdfPCell.ALIGN_CENTER,PdfPCell.ALIGN_MIDDLE,1,0);
		cell.setFixedHeight(15f);
		cell.setBorderWidthTop(0.5f);
		cell.setBorderWidthLeft(0.5f);
		tab.addCell(cell);
		
		cell = PdfCellUtill.createCell("2021-01-01", roman16,PdfPCell.ALIGN_LEFT,PdfPCell.ALIGN_MIDDLE,1,0);
		cell.setBorderWidthTop(0.5f);
		cell.setBorderWidthLeft(0.5f);
		tab.addCell(cell);

		cell = PdfCellUtill.createCell("使 用 人", kai16,PdfPCell.ALIGN_CENTER,PdfPCell.ALIGN_MIDDLE,1,0);
		cell.setFixedHeight(15f);
		cell.setBorderWidthTop(0.5f);
		cell.setBorderWidthLeft(0.5f);
		cell.setUseAscender(true);
		cell.setVerticalAlignment(cell.ALIGN_MIDDLE);
		cell.setHorizontalAlignment(Element.ALIGN_CENTER); //水平居中
		cell.setVerticalAlignment(Element.ALIGN_MIDDLE); //垂直居中
		cell.setBorderWidthBottom(0.5f);
		tab.addCell(cell);

		cell = PdfCellUtill.createCell("张三", fzxk16,PdfPCell.ALIGN_LEFT,PdfPCell.ALIGN_MIDDLE,1,0);
		cell.setBorderWidthTop(0.5f);
		cell.setBorderWidthLeft(0.5f);
		cell.setBorderWidthBottom(0.5f);
		tab.addCell(cell);

		doc.add(tab);
	}
import com.itextpdf.text.Font;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.pdf.PdfPCell;

public class PdfCellUtill {
	private static PdfPCell pdfCell;
	/**
	 * 创建PdfCell
	 * @param content 内容文本(短语)
	 * @param font  字体
	 * @return 返回PdfCell
	 */
	public static PdfPCell createCell(String content,Font font){
		pdfCell = new PdfPCell(new Phrase(content, font));   
		pdfCell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
		pdfCell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
		pdfCell.setBorder(0);
		return pdfCell;
	}
	/**
	 * 
	 * 创建PdfCell
	 * @param content 内容文本(短语)
	 * @param font  字体
	 * @param horizontalAlignment 水平位置对齐
	 * @param verticalAlignment 垂直位置对齐
	 * @return 返回PdfCell
	 */
	public static PdfPCell createCell(String content,Font font,int horizontalAlignment,int verticalAlignment){
		pdfCell = new PdfPCell(new Phrase(content, font));
		pdfCell.setHorizontalAlignment(horizontalAlignment);
		pdfCell.setVerticalAlignment(verticalAlignment);
		pdfCell.setBorder(0);
		return pdfCell;
	}
	/**
	 * 
	 * 创建PdfCell
	 * @param content 内容文本(短语)
	 * @param font  字体
	 * @param horizontalAlignment 水平位置对齐
	 * @param verticalAlignment 垂直位置对齐
	 * @param colspan 合并列数
	 * @param rowspan 合并行数
	 * @return 返回PdfCell
	 */
	public static PdfPCell createCell(String content,Font font,int horizontalAlignment,int verticalAlignment ,int colspan,int rowspan){
		pdfCell = new PdfPCell(new Phrase(content, font));
		pdfCell.setHorizontalAlignment(horizontalAlignment);
		pdfCell.setVerticalAlignment(verticalAlignment);
		if(colspan>0){
			pdfCell.setColspan(colspan);
		}
		if(rowspan>0){
			pdfCell.setRowspan(rowspan);
		}
		pdfCell.setBorder(0);
		return pdfCell;
	}
	/**
	 * 
	 * @param content 内容文本(段落)
	 * @param font 字体
	 * @return 返回PdfCell
	 */
	public static PdfPCell createCellParagraph(String content,Font font){
		pdfCell = new PdfPCell(new Paragraph(content, font));
		pdfCell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
		pdfCell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
		pdfCell.setBorder(0);
		return pdfCell;
	}
	/**
	 * 
	 * @param content 内容文本(段落)
	 * @param font 字体
	 * @param horizontalAlignment 水平对齐
	 * @param verticalAlignment 垂直位置对齐
	 * @return 返回PdfCell
	 */
	public static PdfPCell createCellParagraph(String content,Font font,int horizontalAlignment,int verticalAlignment){
		pdfCell = new PdfPCell(new Paragraph(content, font));
		pdfCell.setHorizontalAlignment(horizontalAlignment);
		pdfCell.setVerticalAlignment(verticalAlignment);
		pdfCell.setBorder(0);
		return pdfCell;
	}
	/**
	 * 
	 * @param content 内容文本(段落)
	 * @param font 字体
	 * @param horizontalAlignment 水平对齐
	 * @param verticalAlignment 垂直位置对齐
	 * @param colspan 合并列数
	 * @param rowspan 合并行数
	 * @return 返回PdfCell
	 */
	public static PdfPCell createCellParagraph(String content,Font font,int horizontalAlignment,int verticalAlignment,int colspan,int rowspan){
		pdfCell = new PdfPCell(new Paragraph(content, font));
		pdfCell.setHorizontalAlignment(horizontalAlignment);
		pdfCell.setVerticalAlignment(verticalAlignment);
		if(colspan>0){
			pdfCell.setColspan(colspan);
		}
		if(rowspan>0){
			pdfCell.setRowspan(rowspan);
		}
		pdfCell.setBorder(0);
		return pdfCell;
	}



}
  • 4
    点赞
  • 32
    收藏
    觉得还不错? 一键收藏
  • 17
    评论
### 回答1: 您好,关于前端使用Lodash打印二维码标签的问题,可以使用QRCode.js库来生成二维码图片,然后使用Lodash的模板功能将二维码图片嵌入到标签模板中,最后通过浏览器的打印功能打印标签。 具体步骤如下: 1. 在前端页面中引入QRCode.js库,可以使用CDN链接或下载后引入本地。 2. 使用QRCode.js库生成二维码图片,将生成的图片插入到标签模板中,可以使用Lodash的template函数或template方法来生成标签HTML代码。 3. 在打印按钮的点击事件中调用浏览器的打印功能,将标签HTML代码打印出来。 示例代码如下: ```javascript // 引入QRCode.js库 <script src="https://cdn.bootcdn.net/ajax/libs/qrcodejs/1.0.0/qrcode.min.js"></script> // 生成二维码图片 var qrcode = new QRCode(document.getElementById("qrcode"), { text: "http://www.example.com", width: 128, height: 128, colorDark : "#000000", colorLight : "#ffffff", correctLevel : QRCode.CorrectLevel.H }); // 生成标签HTML代码 var labelTemplate = _.template(` <div class="label"> <div class="title">产品名称:{{ productName }}</div> <div class="qrcode"><img src="{{ qrCodeSrc }}"></div> </div> `); var labelHtml = labelTemplate({ productName: "测试产品", qrCodeSrc: qrcode._el.firstChild.src }); // 点击打印按钮打印标签 document.getElementById("printButton").onclick = function() { window.print(); }; ``` 其中,示例代码中的labelTemplate变量是使用Lodash的template函数生成的标签模板,其中{{ }}表示模板变量,可以根据实际情况修改。 总的来说,这是一种简单的使用Lodash和QRCode.js库生成和打印二维码标签的方法,您可以根据实际需求进行调整和优化。 ### 回答2: 前端使用lodap(指Lodash库)打印二维码标签可以通过以下步骤实现: 1. 确保已经引入了Lodash库并进行了正确的配置。 2. 创建一个包含需要打印的二维码标签信息的数据对象。可以使用JavaScript对象或者数组的形式存储多个标签的数据。 3. 使用Lodash提供的方法,例如`_.forEach`或者`_.map`,遍历二维码标签数据对象。 4. 在遍历过程中,可以使用HTML模板或者字符串插值的方式,根据标签数据生成相应的HTML标签元素,其中包括二维码的图片源。 5. 将生成的HTML标签元素插入到指定的打印区域中,可以是一个指定的div容器或者直接插入到打印页面中。 6. 使用浏览器的打印功能,可以通过JavaScript调用`window.print`方法来触发打印操作。 7. 在打印之前,可以调整打印页面的样式,例如设置合适的页面宽度、高度、边距等,以确保打印效果符合预期。 请注意,前端使用Lodash库打印二维码标签的具体步骤可能会根据实际需求和环境有所不同,以上步骤仅供参考。另外,需要在浏览器的设置中确保允许JavaScript调用打印功能,以便实现打印操作。 ### 回答3: 使用Lodap打印二维码标签需要以下步骤: 1. 安装Lodap库:在前端项目中使用npm或yarn等包管理工具安装Lodap库。 2. 引入Lodap库:在需要使用Lodap打印二维码标签的文件中,使用import或require语句引入Lodap库。 3. 创建Lodap打印机实例:使用Lodap库提供的API创建Lodap打印机实例。 4. 设置打印机参数:通过设置Lodap打印机实例的参数,如纸张尺寸、打印方向等,以适应二维码标签打印要求。 5. 创建二维码标签模板:使用Lodap库的API创建二维码标签模板,并设置二维码内容和样式。 6. 打印二维码标签:通过调用Lodap打印机实例的打印方法,将二维码标签模板发送给打印机进行打印。 7. 监听打印事件:可以通过监听打印机实例的打印事件,获取打印状态和结果信息,以及处理打印完成后的逻辑。 需要注意的是,以上仅为大致的步骤,具体使用Lodap打印二维码标签还需要详细了解Lodap库的API文档,并在实际开发中根据需求进行相应的调整和处理。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 17
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值