1.导入依赖
<!--hutool -->
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>4.3.0</version>
</dependency>
2.下面直接上代码
- controller层
@GetMapping("/downloadQrCode")
public void downloadQrCode(@RequestParam Map<String, Object> params, HttpServletResponse response) {
try {
String fileName = String.format("%s二维码.zip", params.get("storeSysCode"));
response.setContentType("application/x-msdownload");
response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "utf-8"));
response.addHeader("Access-Control-Allow-Origin", "*");
OutputStream output = response.getOutputStream();
ZipOutputStream zip = new ZipOutputStream(output);
service.downloadQrCode(params, zip);
zip.flush();
zip.close();
} catch (IOException e) {
e.printStackTrace();
}
}
- service层
downloadQrCode方法
@Override
public void downloadQrCode(Map<String, Object> params, ZipOutputStream zos) {
List<TbDto> selectStoreTables = this.baseMapper.selectStoreTables(params);
for(TbDto tbDto : selectStoreTables) {
QrConfig qrConfig = new QrConfig();
qrConfig.setWidth(300);
qrConfig.setHeight(300);
String doaminUrl = aposPropertiesConfig.getdoaminUrl();
// /MWT/{storeSysCode}/{areaCode}/{tableCode}
String wxShopUri = CommonConstant.WXSHOP_MWT_URI
.replace("{storeSysCode}",tbDto.getStoreSysCode())
.replace("{areaCode}", tbDto.getAreaCode())
.replace("{tableCode}", tbDto.getTableCode());
//生成二维码
BufferedImage image = QrCodeUtil.generate(doaminUrl + wxShopUri, qrConfig);
//二维码绘制tableCode
drawTableCode(tbDto, image);
//打包成zip
try(ByteArrayOutputStream out = new ByteArrayOutputStream()) {
ImageUtil.write(image, ImageUtil.IMAGE_TYPE_PNG, out);
String fileName = String.format("%s__%s.png", tbDto.getAreaName(), tbDto.getTableName());
ZipUtil.doZip(fileName, out.toByteArray(), zos);
} catch (IOException e) {
e.printStackTrace();
}
}
}
二维码绘制tableCode,drawTableCode方法
private void drawTableCode(TbDto tbDto, BufferedImage image) {
Graphics2D g2d = (Graphics2D) image.getGraphics();
//设置抗锯齿
g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
int fontSize = 15;
Font font = new Font(null, Font.PLAIN, fontSize);
g2d.setFont(font);
g2d.setColor(Color.black);
//int strWidth = graphics.getFontMetrics().stringWidth(tableCode);
String fileName = String.format("%s(%s)", tbDto.getTableCode(), tbDto.getTableName());
g2d.drawString(fileName, 20, image.getHeight() - 5);
g2d.dispose();
}
ZipUtil工具类
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class ZipUtil {
public static void doZip(String name, byte[] bytes, ZipOutputStream zos) throws IOException {
zos.putNextEntry(new ZipEntry(name));
ByteArrayInputStream fis = new ByteArrayInputStream(bytes);
byte[] buffer = new byte[1024];
int r = 0;
while ((r = fis.read(buffer)) != -1)
zos.write(buffer, 0, r);
zos.flush();
fis.close();
}
}