package com.xxx.modules.until;
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 com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Image;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.pdf.PdfWriter;
import lombok.SneakyThrows;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;
import javax.imageio.ImageIO;
import javax.print.PrintService;
import javax.print.PrintServiceLookup;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.awt.print.PageFormat;
import java.awt.print.Printable;
import java.awt.print.PrinterJob;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.util.List;
import java.util.*;
public class QRCodeGenerator {
private static final int QR_CODE_WIDTH = 200;
private static final int QR_CODE_HEIGHT = 200;
public static void main(String[] args) {
String templateFile = templateFile = "E:/output/image.png"; // 模板图片文件路径
Long time = new Date().getTime();//生成文件夹
String path = time.toString();
String qrCodeData = "https://www.baidu.com"; // 二维码的内容
String outputFolder = "E:/output/"+path; // 输出文件夹路径
String outputPdf = "E:/output"; // 输出文件夹路径
File file = new File(outputFolder);
if (!file.exists()){
file.mkdir();
}
int imagesPerPDF = 5; // 每个PDF包含的图片数量
//生成二维码图片
List<String> qrCodeFiles = generateQRCodeImages(qrCodeData, imagesPerPDF, outputFolder);
//将二维码和模板合成一个图片
List<String> composedFiles = composeImages(templateFile, qrCodeFiles, outputFolder);
//将所有图片合成至pdf
generatePDF(composedFiles, imagesPerPDF, outputPdf);
printPDF(outputPdf);
File[] files = file.listFiles();
for (File file1 : files) {
file1.delete();
}
file.delete();
}
//生成二维码图片
private static List<String> generateQRCodeImages(String qrCodeData, int numImages, String outputFolder) {
List<String> qrCodeFiles = new ArrayList<>();
try {
for (int i = 0; i < numImages; i++) {
String qrCodeFile = outputFolder + "/qrcode_" + i + ".png";
//设置二维码参数
Map<EncodeHintType, Object> hints = new HashMap<>();
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
//生成二维码矩阵
BitMatrix bitMatrix = bitMatrix = new MultiFormatWriter().encode(qrCodeData, BarcodeFormat.QR_CODE, QR_CODE_WIDTH1, QR_CODE_HEIGHT1, hints);
// 将二维码矩阵写入文件
Path path = FileSystems.getDefault().getPath(qrCodeFile);
MatrixToImageWriter.writeToPath(bitMatrix, "PNG", path);
qrCodeFiles.add(qrCodeFile);
}
System.out.println("QR Code images generated successfully!");
} catch (WriterException | IOException e) {
e.printStackTrace();
}
return qrCodeFiles;
}
// 合成图片
private static List<String> composeImages(String templateFile, List<String> qrCodeFiles, String outputFolder) {
List<String> composedFiles = new ArrayList<>();
int xPosition = 320;
int yPosition = 100;
int fontSize = 24;
int y = 18;
try {
BufferedImage templateImage = ImageIO.read(new File(templateFile));
int templateWidth = templateImage.getWidth();
int templateHeight = templateImage.getHeight();
for (int i = 0; i < qrCodeFiles.size(); i++) {
String qrCodeFile = qrCodeFiles.get(i);
String composedFile = outputFolder + "/composed_" + i + ".png";
// 加载二维码图片
BufferedImage qrCodeImage = ImageIO.read(new File(qrCodeFile));
// 在二维码图像上方添加文字
Graphics2D graphics = qrCodeImage.createGraphics();
graphics.setColor(Color.BLACK);
Font font = new Font("Arial", Font.PLAIN, 24);
graphics.setFont(font);
FontMetrics fontMetrics = graphics.getFontMetrics(font);
int textWidth = fontMetrics.stringWidth("aaaaa"+i);
int x = (qrCodeImage.getWidth() - textWidth) / 2;
graphics.drawString("aaaaa"+i, x, y);
graphics.dispose();
// 创建合成图片
BufferedImage composedImage = new BufferedImage(templateWidth, templateHeight, BufferedImage.TYPE_INT_ARGB);
Graphics2D g = composedImage.createGraphics();
g.drawImage(templateImage, 0, 0, null);
g.drawImage(qrCodeImage, xPosition, yPosition, null);
g.dispose();
// 将合成图片写入文件
ImageIO.write(composedImage, "PNG", new File(composedFile));
composedFiles.add(composedFile);
}
System.out.println("Images composed successfully!");
} catch (IOException e) {
e.printStackTrace();
}
return composedFiles;
}
private static void generatePDF(List<String> composedFiles, int imagesPerPDF, String outputFolder) {
try {
int numPDFs = (int) Math.ceil((double) composedFiles.size() / imagesPerPDF);
// 计算每个图像的缩放比例
com.itextpdf.text.Rectangle a4 = PageSize.A4;
float scaleWidth = a4.getWidth()/3-10;
float scaleHeight = 150f;
int rowIndex = 0;
int columnIndex = 0;
int v = (int) a4.getHeight() / (int) scaleHeight;
for (int i = 0; i < numPDFs; i++) {
String pdfFile = outputFolder + "/output_" + i + ".pdf";
Document document = new Document(a4);
PdfWriter.getInstance(document, new FileOutputStream(pdfFile));
document.open();
int startIndex = i * imagesPerPDF;
int endIndex = Math.min((i + 1) * imagesPerPDF, composedFiles.size());
for (int j = startIndex; j < endIndex; j++) {
String composedFile = composedFiles.get(j);
Image image = Image.getInstance(composedFile);
image.scaleToFit(scaleWidth, scaleHeight);
// 计算图像在页面上的坐标
float x = rowIndex * (scaleWidth+10f)+10f;
float y = a4.getHeight() - (columnIndex+1) * (scaleHeight+10f);
// 将图像添加到PDF文档中的指定位置
image.setAbsolutePosition(x, y);
document.add(image);
// 更新行和列的索引
rowIndex++;
if (rowIndex >= 3) {
rowIndex = 0;
columnIndex++;
if (columnIndex>=v){
rowIndex = 0;
columnIndex = 0;
// 新建一页
document.newPage();
}
}
}
document.close();
}
System.out.println("PDFs generated successfully!");
} catch (DocumentException | IOException e) {
e.printStackTrace();
}
}
@SneakyThrows
private static void printPDF(String outputFolder) {
try {
PrintService printService = PrintServiceLookup.lookupDefaultPrintService();
File folder = new File(outputFolder);
File[] pdfFiles = folder.listFiles((dir, name) -> name.endsWith(".pdf"));
for (File pdfFile : pdfFiles) {
PDDocument document = PDDocument.load(pdfFile);
PDFRenderer pdfRenderer = new PDFRenderer(document);
PrinterJob job = PrinterJob.getPrinterJob();
job.setPrintService(printService);
job.setPrintable(new PDFPrintable(pdfRenderer, document.getNumberOfPages()));
job.print();
document.close();
}
System.out.println("PDFs printed successfully!");
} catch (Exception e) {
e.printStackTrace();
}
}
private static class PDFPrintable implements Printable {
private PDFRenderer pdfRenderer;
private int numPages;
public PDFPrintable(PDFRenderer pdfRenderer, int numPages) {
this.pdfRenderer = pdfRenderer;
this.numPages = numPages;
}
@Override
public int print(Graphics graphics, PageFormat pageFormat, int pageIndex) {
if (pageIndex >= numPages) {
return NO_SUCH_PAGE;
}
Graphics2D g2d = (Graphics2D) graphics;
try {
java.awt.image.BufferedImage image = pdfRenderer.renderImage(pageIndex, 1.0f);
g2d.drawImage(image, 0, 0, (int) pageFormat.getImageableWidth(),
(int) pageFormat.getImageableHeight(), null);
} catch (IOException e) {
e.printStackTrace();
}
return PAGE_EXISTS;
}
}
}
在模板图片上方添加二维码并打印到pdf
最新推荐文章于 2024-09-16 09:47:29 发布