package com.fastbee.data.controller.printer.yilianyun;
 
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.awt.print.Printable;
import java.awt.print.PrinterJob;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.imageio.ImageIO;
import javax.print.PrintService;
import javax.print.PrintServiceLookup;
 
public class MainPrint {
 
	public static void main(String[] args) {
		try {
			// 二维码内容
			String qrCodeContent = "https://www.example.com";

			// 生成二维码
			BitMatrix bitMatrix = generateQRCode(qrCodeContent, 180, 180);

			// 将二维码转换为BufferedImage
			BufferedImage qrCodeImage = MatrixToImageWriter.toBufferedImage(bitMatrix);

			// 创建一个新的BufferedImage，包含二维码和文字
			int qrCodeWidth = qrCodeImage.getWidth();
			int qrCodeHeight = qrCodeImage.getHeight();
			int textWidth = 200; // 文字区域宽度
			int textHeight = qrCodeHeight; // 文字区域高度，与二维码相同
			int imageWidth = qrCodeWidth + textWidth + 20; // 间距20像素
			int imageHeight = qrCodeHeight;

			BufferedImage finalImage = new BufferedImage(imageWidth, imageHeight, BufferedImage.TYPE_INT_ARGB);
			Graphics2D g2d = finalImage.createGraphics();

			// 绘制背景颜色
			g2d.setColor(Color.WHITE);
			g2d.fillRect(0, 0, imageWidth, imageHeight);

			// 绘制二维码
			g2d.drawImage(qrCodeImage, 0, 0, qrCodeWidth, qrCodeHeight, null);

			// 绘制文字
			g2d.setColor(Color.BLACK);
			g2d.setFont(new Font("黑体", Font.BOLD, 15));
			String text1 = "设备名称";
			FontMetrics fontMetrics = g2d.getFontMetrics();
			int textX = qrCodeWidth ; // 间距20像素
			int textY1 = (imageHeight - fontMetrics.getHeight()) / 2 + fontMetrics.getAscent()-40;
			g2d.drawString(text1, textX, textY1);

			// 绘制第二段文字
			String text2 = "设备编码";
			int textY2 = textY1 + fontMetrics.getHeight() + 20; // 在第一段文字下方添加一些间距
			g2d.drawString(text2, textX, textY2);
			// 绘制第三段文字
			String text3 = "XXXX公司";
			int textY3 = textY2 + fontMetrics.getHeight() + 20; // 在第一段文字下方添加一些间距
			g2d.drawString(text3, textX, textY3);
			// 释放Graphics2D资源
			g2d.dispose();

			// 保存图片到文件
			File outputfile = new File("C:\\Users\\admin\\Desktop\\sa.png");
			ImageIO.write(finalImage, "png", outputfile);

			System.out.println("二维码和文字图片已生成：" + outputfile.getAbsolutePath());
		} catch (WriterException | IOException e) {
			e.printStackTrace();
		}
	}
	private static BitMatrix generateQRCode(String text, int width, int height) throws WriterException {
		Map<EncodeHintType, Object> hints = new HashMap<>();
		hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
		return new MultiFormatWriter().encode(text, BarcodeFormat.QR_CODE, width, height, hints);
	}
}