package thyyxxk.webserver.utils;

import com.itextpdf.text.*;
import com.itextpdf.text.pdf.PdfWriter;

import javax.xml.bind.DatatypeConverter;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class Base64ImageToPdf {

    public static byte[] imageToPdf(List<String> images) throws DocumentException, IOException {
        // 创建 A4 尺寸 PDF 文档
        Document document = new Document(com.itextpdf.text.PageSize.A4, 0, 0, 0, 0);
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        PdfWriter.getInstance(document, byteArrayOutputStream);
        document.open();
        float a4Width = document.getPageSize().getWidth();
        float a4Height = document.getPageSize().getHeight();
        // 将图像添加到 PDF
        for (String item : images) {
            // 解析 Base64 数据为字节数组
            byte[] imageBytes = DatatypeConverter.parseBase64Binary(item);
            // 创建图像对象
            Image img = Image.getInstance(imageBytes);
            // 计算图像的宽高比例
            float imgWidth = img.getScaledWidth();
            float imgHeight = img.getScaledHeight();
            // 设置缩放系数以控制宽度
            float scaleFactor = Math.min(a4Width / imgWidth, a4Height / imgHeight);
            img.scaleAbsolute(imgWidth * scaleFactor, imgHeight * scaleFactor);
            document.add(img);
            document.newPage();
        }
        // 关闭文档
        document.close();
        // 返回 PDF 的字节数组
        return byteArrayOutputStream.toByteArray();
    }

    public static byte[] imageToPdf(String images) throws DocumentException, IOException {
        List<String> imagesList = new ArrayList<>();
        imagesList.add(images);
        return imageToPdf(imagesList);
    }

}
