import com.itextpdf.html2pdf.HtmlConverter;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.kernel.pdf.WriterProperties;
import com.itextpdf.layout.element.IBlockElement;
import com.itextpdf.layout.property.UnitValue;
import com.itextpdf.licensing.base.LicenseKey;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
 
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
 
@Service
public class PdfService {
 
    private final ResourceLoader resourceLoader;
 
    public PdfService(ResourceLoader resourceLoader) {
        this.resourceLoader = resourceLoader;
    }
 
    public byte[] generatePdfFromHtml(String htmlTemplatePath, Map<String, Object> data) throws IOException {
        // 加载HTML模板
        Resource resource = resourceLoader.getResource("classpath:" + htmlTemplatePath);
        String htmlContent = new String(Files.readAllBytes(resource.getFile().toPath()), StandardCharsets.UTF_8);
 
        // 替换模板中的占位符
        String filledHtml = FreeMarkerTemplateUtils.processTemplateIntoString(
                new Template("templateName", new String(htmlContent)), data);
 
        // 使用iText HtmlConverter将HTML转换为PDF
        ByteArrayOutputStream pdfOutputStream = new ByteArrayOutputStream();
        HtmlConverter.convertToPdf(filledHtml, pdfOutputStream);
 
        return pdfOutputStream.toByteArray();
    }
}这段代码示例展示了如何在Spring Boot应用中使用iText库的HtmlConverter类将HTML转换为PDF格式。首先,代码通过Spring的ResourceLoader加载HTML模板文件,然后使用FreeMarker模板引擎进行数据替换。接下来,HtmlConverter的convertToPdf方法被调用,HTML内容被转换为PDF格式,最终以字节流的形式返回。