package com.ruoyi.common.utils.file;

import com.itextpdf.text.*;
import com.itextpdf.text.pdf.PdfDocument;
import com.itextpdf.text.pdf.PdfWriter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;


public class PdfUtils {
    private static final Logger log = LoggerFactory.getLogger(PdfUtils.class);

//    public static void main(String[] args) throws DocumentException, IOException {
//        addImageToPdf("E:/itextExamples/javafxLogo.png", "E:/itextExamples/addingObjects2.pdf");
//    }

    public static void addImageToPdf(String imgPath, String pdfPath) throws DocumentException, IOException {
//        log.info("addImageToPdf");
        Document document = new Document(PageSize.A4);
        try {    // 3.打开文档
            final PdfWriter pdfWriter = PdfWriter.getInstance(document, Files.newOutputStream(Paths.get(pdfPath)));
            document.setMargins(0, 0, 0, 0); // 设置边距为零
            document.open();

            // 加载图片
            Image image = Image.getInstance(imgPath);

            // 获取页面尺寸
            float pageWidth = document.getPageSize().getWidth();
            float pageHeight = document.getPageSize().getHeight();

            // 设置图片铺满整个页面
            image.scaleAbsolute(pageWidth, pageHeight);

            // 将图片插入到 PDF 中
            document.add(image);
        } catch (DocumentException | IOException e) {
            e.printStackTrace();
        } finally {
            document.close();
        }
    }
}
