Java生成二维码并在二维码下添加文字,并导出为word

琢磨了很久,也搜了网上的不少资源,最后总结出来的这套代码功能算是比较全的了。
首先在pom文件中引入用于生成二维码和word的jar包

        <!--二维码生成-->
		<dependency>
			<groupId>com.google.zxing</groupId>
			<artifactId>core</artifactId>
			<version>2.3.0</version>
		</dependency>
		<!--word相关jar-->
		<dependency>
			<groupId>com.lowagie</groupId>
			<artifactId>itext</artifactId>
			<version>2.1.7</version>
		</dependency>
		<dependency>
			<groupId>com.lowagie</groupId>
			<artifactId>itext-rtf</artifactId>
			<version>2.1.7</version>
		</dependency>
		<dependency>
			<groupId>com.itextpdf</groupId>
			<artifactId>itext-asian</artifactId>
			<version>5.2.0</version>
		</dependency>

直接上代码

生成二维码;

package com.tfjybj.library.template;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.lowagie.text.*;
import com.lowagie.text.Image;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.Font;
import java.awt.List;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.HashMap;
import java.util.Map;
import com.tfjybj.library.template.CreateWord;

/**
 * @author 信息二班郄先生
 * @date 2019-3-24 14:34:47
 * 二维码生成
 */
public class ZXingCode {
    /**
     * 颜色
     */
    private static final int QRCOLOR = 0xFF000000;
    /**
     * 背景颜色
     */
    private static final int BGWHITE = 0xFFFFFFFF;

//    private CreateWord createWord;
    /**
     * 存放路径
     */
//    private static final String CODEPATH = ".\\library2-provider\\src\\main\\java\\com\\tfjybj\\library\\template\\codeImage\\";
//    public static void main(String[] args) {
        CreateWord createWord = new CreateWord();
//        try {
//            System.out.println(System.currentTimeMillis());
//            getQRCode("傻呗呗", "扫一扫有惊喜");
            java.util.List<Image> imageList = null;
            imageList.add(imageByte);
            createWord.createDocContext(imageList,httpServletRequest,httpServletResponse);
//            System.out.println(System.currentTimeMillis());
//            System.out.println("生成ok");
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }

    /**
     * 生成二维码方法
     *
     * @param data 索书号
     * @param belowText 书名
     * @return
     */
    public static com.lowagie.text.Image getQRCode(String data, String belowText) {
        com.lowagie.text.Image imageByte =null;
        try {
            ZXingCode zp = new ZXingCode();
            BufferedImage bim = zp.generateQRCodeBufferedImage(data, BarcodeFormat.QR_CODE, 230, 230, zp.getDecodeHintType());
            //字节数组
            imageByte = zp.addTextForQRCode(bim, belowText);

//            return imageByte;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return imageByte;
    }

    /**
     * @param bim       放在内存中图片
     * @param belowText 二维码下方显示文字
     * @return
     */
    public com.lowagie.text.Image addTextForQRCode(BufferedImage bim, String belowText) {
        try {
            BufferedImage image = bim;
            if (belowText != null && !belowText.equals("")) {
                BufferedImage outImage = new BufferedImage(230, 245, BufferedImage.TYPE_4BYTE_ABGR);
                Graphics2D outg = outImage.createGraphics();
                outg.drawImage(image, 0, 0, image.getWidth(), image.getHeight(), null);
                outg.setColor(Color.BLACK);
                //获得本地字体列表
//                String[] fonts = this.getFontName();
                outg.setFont(new Font("SansSerif", Font.PLAIN, 18));
                int strWidth = outg.getFontMetrics().stringWidth(belowText);
                outg.drawString(belowText, 100 - strWidth / 2 + 8, image.getHeight() + (outImage.getHeight() - image.getHeight()) / 2 + 5);
                outg.dispose();
                outImage.flush();
                image = outImage;
            }
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            baos.flush();
            ImageIO.write(image, "png", baos);
            BufferedImage newBufferedImage = new BufferedImage(
                    image.getWidth(), image.getHeight(),
                    BufferedImage.TYPE_INT_RGB);
            newBufferedImage.createGraphics().drawImage(image, 0, 0,
                    Color.WHITE, null);
//            存放本地
//            ImageIO.write(newBufferedImage, "png", new File(CODEPATH + "SZ-" + System.currentTimeMillis() + "code.png"));
            com.lowagie.text.Image imageByte = com.lowagie.text.Image.getInstance(baos.toByteArray());
            baos.close();
            image.flush();
            return imageByte;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 绘制二维码,不带文字
     *
     * @param content       扫描内容
     * @param barcodeFormat 格式
     * @param width
     * @param height
     * @param hints         二维码属性设置
     * @return 放到内存中,后续再二维码下方添加文字
     */
    public BufferedImage generateQRCodeBufferedImage(String content, BarcodeFormat barcodeFormat, int width, int height, Map<EncodeHintType, ?> hints) {
        MultiFormatWriter multiFormatWriter = null;
        BitMatrix bm = null;
        BufferedImage image = null;
        try {
            multiFormatWriter = new MultiFormatWriter();
            bm = multiFormatWriter.encode(content, barcodeFormat, width, height, hints);
            int w = bm.getWidth();
            int h = bm.getHeight();
            image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
            for (int x = 0; x < w; x++) {
                for (int y = 0; y < h; y++) {
                    image.setRGB(x, y, bm.get(x, y) ? QRCOLOR : BGWHITE);
                }
            }
        } catch (WriterException e) {
            e.printStackTrace();
        }
        return image;
    }

    /**
     * 设置二维码属性
     *
     * @return
     */
    public Map<EncodeHintType, Object> getDecodeHintType() {
        Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
        hints.put(EncodeHintType.MARGIN, 0);
        hints.put(EncodeHintType.MAX_SIZE, 350);
        hints.put(EncodeHintType.MIN_SIZE, 100);
        return hints;
    }

    /**
     * 获得本地字体列表
     * @return 字体数组
     */
    public String[] getFontName(){
        GraphicsEnvironment e = GraphicsEnvironment.getLocalGraphicsEnvironment();
        String[] fontName = e.getAvailableFontFamilyNames();
        return fontName;
    }

}

排列二维码放入word并批量导出

package com.tfjybj.library.template;

import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.*;
import com.lowagie.text.Image;
import com.lowagie.text.rtf.RtfWriter2;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;

//将二维码输出到word中
/**
 * @author 信息二班郄先生
 * @date 2019-3-24 14:34:47
 */
public class CreateWord {
    //HttpServletRequest request, HttpServletResponse response可以不加这两个参数

    /**
     *
     * @param imageList 图片字节流集合
     * @param response 返回word
     * @throws DocumentException 文档错误抛出
     * @throws IOException 输入输出错误抛出
     */
    public static void createDocContext(List<Image> imageList,HttpServletResponse response) throws DocumentException, IOException {
        File file1 = new File("TwoCodeImage.doc");
//        judeFileExists(file1);
        Document document = new Document();
        // 建立一个书写器(Writer)与document对象关联,通过书写器(Writer)可以将文档写入到磁盘中
        RtfWriter2.getInstance(document, new FileOutputStream(file1));
        document.open();
        Paragraph title = new Paragraph("图书索书号二维码");
        //设置标题格式对齐方式
        title.setAlignment(Element.ALIGN_CENTER);
        document.add(title);
        // 设置 Table 表格
        //设置表格,将图片加到表格中进行方便定位
        Table aTable = new Table(4);
        // 设置每列所占比例
        // 占页面宽度 90%
        aTable.setWidth(100);
        // 自动填满
        // aTable.setAutoFillEmptyCells(true);
        //这里是imagelist集合,就是图片字节流的集合,图片从流中去获取放到word中
        for (int i = 0; i < imageList.size(); i++) {
            //设置图片等比例缩小
            imageList.get(i).scalePercent(55);
            aTable.addCell(new Cell(imageList.get(i)));
        }
        document.add(aTable);
        document.add(new Paragraph("\n"));
        System.out.println("word----success");
        document.close();
        //响应浏览器 返回下载
        response.setContentType("applicaiton/x-download");
        response.addHeader("Content-Disposition", "attachment;filename=" + "TwoCodeImage.doc");
        InputStream is = null;
        OutputStream os = null;
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        is = new FileInputStream(new File("TwoCodeImage.doc"));
        bis = new BufferedInputStream(is);
        os = response.getOutputStream();
        bos = new BufferedOutputStream(os);
        byte[] b = new byte[1024];
        int len = 0;
        while ((len = bis.read(b)) != -1) {
            bos.write(b, 0, len);
        }
        bis.close();
        is.close();
        bos.close();
        os.close();
        //删除本地临时文件
        file1.delete();
    }
}

最后上效果图:
在这里插入图片描述
在这里插入图片描述

  • 0
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 16
    评论
Java二维码添加字体Logo,你可以使用第三方库,如zxingjavase等。下面是一个使用zxing库的示例代码: ```java import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.io.File; import javax.imageio.ImageIO; import com.google.zxing.BarcodeFormat; import com.google.zxing.EncodeHintType; import com.google.zxing.MultiFormatWriter; import com.google.zxing.common.BitMatrix; import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel; public class QRCodeGenerator { private static final int QRCODE_WIDTH = 300; private static final int QRCODE_HEIGHT = 300; private static final int LOGO_WIDTH = 80; private static final int LOGO_HEIGHT = 80; public static void main(String[] args) throws Exception { String text = "https://www.example.com"; String logoPath = "logo.png"; String outputPath = "qrcode_with_logo.png"; // 创建二维码参数 MultiFormatWriter writer = new MultiFormatWriter(); BitMatrix bitMatrix = writer.encode(text, BarcodeFormat.QR_CODE, QRCODE_WIDTH, QRCODE_HEIGHT); // 加载Logo图片 BufferedImage logoImage = ImageIO.read(new File(logoPath)); // 创建带Logo的二维码 BufferedImage qrcodeImage = new BufferedImage(QRCODE_WIDTH, QRCODE_HEIGHT, BufferedImage.TYPE_INT_RGB); Graphics2D graphics = (Graphics2D) qrcodeImage.getGraphics(); graphics.drawImage(bitMatrixToImage(bitMatrix), 0, 0, null); int x = (QRCODE_WIDTH - LOGO_WIDTH) / 2; int y = (QRCODE_HEIGHT - LOGO_HEIGHT) / 2; graphics.drawImage(logoImage, x, y, LOGO_WIDTH, LOGO_HEIGHT, null); graphics.dispose(); // 保存带Logo的二维码图片 ImageIO.write(qrcodeImage, "png", new File(outputPath)); } private static BufferedImage bitMatrixToImage(BitMatrix matrix) { int width = matrix.getWidth(); int height = matrix.getHeight(); BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { image.setRGB(x, y, matrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF); } } return image; } } ``` 在上面的代码,我们首先根据给定的URL文本生成了一个普通的二维码。然后,我们加载Logo图片,并使用Graphics2D对象将Logo绘制在二维码间。最后,将带有Logo的二维码保存为一个新的图片文件。 请确保将`logo.png`替换为你想要添加的Logo图片的路径,并将`outputPath`设置为保存带有Logo的二维码的文件路径。你还可以根据需要调整二维码和Logo的大小。 希望这可以帮助到你!如果还有其他问题,请随时提问。
评论 16
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值