package com.dcsoft.system.utils;

import com.itextpdf.text.Document;
import com.itextpdf.text.Image;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfGState;
import com.itextpdf.text.pdf.PdfPageEventHelper;
import com.itextpdf.text.pdf.PdfWriter;
import lombok.extern.slf4j.Slf4j;

import java.net.URL;

/**
 * 水印处理
 */
@Slf4j
public class PdfWatermark extends PdfPageEventHelper {

    private static String watermarkUrl;

    public PdfWatermark() {
    }

    public PdfWatermark(String watermarkUrl) {
        PdfWatermark.watermarkUrl = watermarkUrl;
    }


    @Override
    public void onEndPage(PdfWriter writer, Document document) {
        try {
            // 加载水印图片
            Image watermark = Image.getInstance(new URL(watermarkUrl));

            // 调整图片大小（保持比例）
            watermark.scaleToFit(100, 100);

            // 计算位置（确保在页面内）
            float x = document.right() - watermark.getScaledWidth() - 20;
            float y = document.bottom() + watermark.getScaledHeight();

            watermark.setAbsolutePosition(x, y);

            PdfContentByte canvas = writer.getDirectContentUnder();
            PdfGState gs = new PdfGState();
            gs.setFillOpacity(1f); // 调整为半透明
            canvas.setGState(gs);
            canvas.addImage(watermark);
        } catch (Exception e) {
            log.error("添加水印失败: ", e);
        }
    }

}
