angular如何生成下载多条条形码(仅供参考)

angular如何生成下载多条条形码(仅供参考),第1张

后端代码都可以用,前端接受需要接收io流,本文写的是angular前端。如有错误请大佬指出,俺新手多多关照

本文章后端参考了网上大佬的写法

java 批量生成条形码,打包zip(springboot)_洛心尘8的博客-CSDN博客_java批量生成条形码

1.导入pom文件

            com.google.zxing
            core
            3.3.3
        
        
            com.google.zxing
            javase
            3.3.3
        
2.工具类 直接复制就能用
package com.lianzhan.estate.affairs.instrument;


import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.oned.Code128Writer;
import org.apache.commons.lang3.StringUtils;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.HashMap;
import java.util.Map;

public class Barcode {

    /** 条形码宽度 */
    private static final int WIDTH = 332;

    /** 条形码高度 */
    private static final int HEIGHT = 50;

    /** 加文字 条形码 */
    private static final int WORDHEIGHT = 80;

    /**
     * 设置 条形码参数
     */
    private static Map hints = new HashMap() {
        private static final long serialVersionUID = 1L;
        {
            // 设置编码方式
            put(EncodeHintType.CHARACTER_SET, "utf-8");
        }
    };

    /**
     * 生成 图片缓冲
     * @author fxbin
     * @param vaNumber  VA 码
     * @return 返回BufferedImage
     */
    public static BufferedImage getBarCode(String vaNumber){
        try {
            Code128Writer writer = new Code128Writer();
            // 编码内容, 编码类型, 宽度, 高度, 设置参数
            BitMatrix bitMatrix = writer.encode(vaNumber, BarcodeFormat.CODE_128, WIDTH, HEIGHT, hints);
            return MatrixToImageWriter.toBufferedImage(bitMatrix);
        } catch (WriterException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 把带logo的条形码下面加上文字
     * @author fxbin
     * @param image  条形码图片
     * @param words  文字
     * @return 返回BufferedImage
     */
    public static BufferedImage insertWords(BufferedImage image, String words,boolean needCompress){
        // 新的图片,把带logo的二维码下面加上文字
        if (StringUtils.isNotEmpty(words)) {

            BufferedImage outImage = new BufferedImage(WIDTH, WORDHEIGHT, BufferedImage.TYPE_INT_RGB);

            Graphics2D g2d = outImage.createGraphics();

            // 抗锯齿
            setGraphics2D(g2d);
            // 设置白色
            setColorWhite(g2d);

            // 画条形码到新的面板
            g2d.drawImage(image, 0, 0, image.getWidth(), image.getHeight(), null);
            // 画文字到新的面板
            Color color=new Color(0, 0, 0);
            g2d.setColor(color);
            // 字体、字型、字号
            g2d.setFont(new Font("微软雅黑", Font.PLAIN, 18));
            //文字长度
            int strWidth = g2d.getFontMetrics().stringWidth(words);
            //总长度减去文字长度的一半  (居中显示)
            int wordStartX=(WIDTH - strWidth) / 2;
            //height + (outImage.getHeight() - height) / 2 + 12
            int wordStartY=HEIGHT+20;

            // 画文字
            g2d.drawString(words, wordStartX, wordStartY);
            g2d.dispose();
            outImage.flush();
            return outImage;
        }
        return null;
    }

    /**
     * 设置 Graphics2D 属性  (抗锯齿)
     * @param g2d  Graphics2D提供对几何形状、坐标转换、颜色管理和文本布局更为复杂的控制
     */
    private static void setGraphics2D(Graphics2D g2d){
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g2d.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_DEFAULT);
        Stroke s = new BasicStroke(1, BasicStroke.CAP_ROUND, BasicStroke.JOIN_MITER);
        g2d.setStroke(s);
    }

    /**
     * 设置背景为白色
     * @param g2d Graphics2D提供对几何形状、坐标转换、颜色管理和文本布局更为复杂的控制
     */
    private static void setColorWhite(Graphics2D g2d){
        g2d.setColor(Color.WHITE);
        //填充整个屏幕
        g2d.fillRect(0,0,600,600);
        //设置笔刷
        g2d.setColor(Color.BLACK);
    }

    public static BufferedImage encode(String content,boolean needCompress) throws Exception {
        BufferedImage image = insertWords(getBarCode(content),content,needCompress);
        return image;
    }


}
3.contrller层
@PostMapping(value = "/barcode")
	public void barCode(@RequestParam(value = "barcode" , required = false) List barcode,HttpServletResponse response) throws Exception {
		System.out.println(barcode+"=============barcode===============");
			String  downloadFilename = "导出条码";
			//转换中文;否则可能会产生乱码
			downloadFilename = URLEncoder.encode(downloadFilename, "UTF-8");
			// 指明response的返回对象是文件流
			response.setContentType("application/octet-stream");
			// 设置在下载框默认显示的文件名
			response.setHeader("Content-Disposition", "attachment;filename=" + downloadFilename+".zip");
			ZipOutputStream zos = new ZipOutputStream(response.getOutputStream());
			if(barcode!=null) {
				for (int i = 0; i < barcode.size(); i++) {
					zos.putNextEntry(new ZipEntry(barcode.get(i) + ".png"));
					ImageIO.write(BarCodeUtil.encode(barcode.get(i), true), "jpg", zos);
				}
			}else {
				List infos = infoService.listAll();
				System.out.println(infos+"=============info====================");
				for (int i = 0; i
4.angular前端代码,我这里code是发送的数组到前端,大家可以按需求更改
/**
   *
   * @param reset 生成条形码多条
   * @returns
   */
  async createBarcode(path?: any) {
    let name1 = 'barCode.zip'; //给下载的文件命名
    const xhr = new XMLHttpRequest(); //创建对象
    xhr.open('post', path);//post接收文件流
    xhr.responseType = 'blob';
    xhr.setRequestHeader('Access-Token', this.token['token']);
    xhr.send();

    /* 可以获取下载进度 */
    xhr.addEventListener(
      'progress',
      function (event) {
        // 响应头要有Content-Length
        if (event.lengthComputable) {
          // 下载进度 = 已下载 / 总大小
          let percentComplete = event.loaded / event.total;
          console.log(percentComplete); // 最后输出1
        }
      },
      false
    );

    xhr.onload = function () {
      if (this.status === 200 || this.status === 304) {
        // 如果是IE10及以上,不支持download属性,采用msSaveOrOpenBlob方法,但是IE10以下也不支持msSaveOrOpenBlob
        // if ('msSaveOrOpenBlob' in navigator) {
        //   navigator.msSaveOrOpenBlob(this.response, name1);
        //   return;
        // }
        // const blob = new Blob([this.response], { type: xhr.getResponseHeader('Content-Type') });
        // const url = URL.createObjectURL(blob);
        const url = URL.createObjectURL(this.response);
        const a = document.createElement('a');
        a.style.display = 'none';
        a.href = url;
        a.download = name1;
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        URL.revokeObjectURL(url);
      }
    };
  }

  /**
   *
   * @param reset 选择生成条形码
   * @returns
   */
  barcode: any = [];
  selectCreate() {
    this.barcode = this.ztable.checkedDataIds; //获取被选中的数据
    console.log(this.ztable.listOfCurrentPageData,'========barcode=========')
    let path = `${environment['frontPath']}/ml/info/barcode?barcode=${this.barcode}`;
    this.createBarcode(path);
  }

  /**
   *
   * @param reset 全部生成条形码
   * @returns
   */
  totalCreate() {
    let path = `${environment['frontPath']}/ml/info/barcode`;
    this.createBarcode(path);
  }
5.获取token, ng alain中有如何获取token
import { DA_SERVICE_TOKEN, ITokenService } from '@delon/auth';
token: any
constructor(@Inject(DA_SERVICE_TOKEN) private tokenService: ITokenService){}
 ngOnInit(): void {
    this.listPageData();
    this.token = this.tokenService.get();
  }

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/939979.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-17
下一篇 2022-05-17

发表评论

登录后才能评论

评论列表(0条)