package cn.teammodel.utils;

import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Font;
import com.itextpdf.text.Image;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.AcroFields;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfStamper;

import java.io.IOException;
import java.util.Map;

/**
 * @author winter
 * @create 2024-01-24 16:02
 */
public class PdfUtil {
    public static void fillPdfForm(PdfStamper stamper, Map<String, String> data) throws IOException, DocumentException {
        BaseFont baseFont = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
        Font boldFont = new Font(baseFont, 16, Font.BOLD);
        AcroFields fields = stamper.getAcroFields();
        for (Map.Entry<String, String> entry : data.entrySet()) {
            fields.setFieldProperty(entry.getKey(), "textsize", boldFont.getSize(), null);
            fields.setFieldProperty(entry.getKey(), "textfont", baseFont, null);  // 设置字体为加粗
            fields.setField(entry.getKey(), entry.getValue());
        }
    }

    public static void fillImage(PdfStamper stamper, String imgFieldName, byte[] data) throws DocumentException, IOException {
        AcroFields acroFields = stamper.getAcroFields();
        Image image = Image.getInstance(data);
        int pageNo = acroFields.getFieldPositions(imgFieldName).get(0).page;
        Rectangle rectangle = acroFields.getFieldPositions(imgFieldName).get(0).position;
        float x = rectangle.getLeft();
        float y = rectangle.getBottom();
        PdfContentByte content = stamper.getOverContent(pageNo);
        image.scaleToFit(rectangle.getWidth(), rectangle.getHeight());
        image.setAbsolutePosition(x, y);
        content.addImage(image);
    }
}