PdfCreateUtil.java 6.1 KB
package com.aigeo.util;

import com.itextpdf.io.image.ImageData;
import com.itextpdf.io.image.ImageDataFactory;
import com.itextpdf.kernel.colors.ColorConstants;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Image;
import com.itextpdf.layout.element.Paragraph;
import com.itextpdf.layout.properties.TextAlignment;
import com.itextpdf.layout.properties.UnitValue;

import java.io.File;
import java.io.FileOutputStream;
import java.net.URL;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class PdfCreateUtil {
    public static String create(String content) {
        try {
            long l = System.currentTimeMillis();
            String fileName = "D:/LsYwxProject/YwxErpApi/yiwaixiaoerp/YwxErp/upload/aidocx/" + l + ".pdf";
            createFormattedPdfWithIText(content, fileName);
            System.out.println("文档创建成功:自然的诗篇.pdf");
            return fileName;
        } catch (Exception e) {
            System.err.println("创建文档时出错: " + e.getMessage());
            e.printStackTrace();
        }
        return "success";
    }

    public static void createFormattedPdfWithIText(String content, String fileName) throws Exception {
        // 确保输出目录存在
        File outputFile = new File(fileName);
        File parentDir = outputFile.getParentFile();
        if (parentDir != null && !parentDir.exists()) {
            parentDir.mkdirs();
        }

        // 创建PDF文档
        PdfWriter writer = new PdfWriter(new FileOutputStream(outputFile));
        PdfDocument pdf = new PdfDocument(writer);
        Document document = new Document(pdf);

        // 尝试设置中文字体
        try {
            PdfFont chineseFont = PdfFontFactory.createFont("STSong-Light", "UniGB-UCS2-H");
            document.setFont(chineseFont);
            System.out.println("中文字体设置成功");
        } catch (Exception e) {
            System.err.println("无法设置中文字体,将使用默认字体: " + e.getMessage());
        }

        try {
            // 按段落分割内容(两个换行符)
            String[] paragraphs = content.split("\n");

            System.out.println("检测到 " + paragraphs.length + " 个段落");

            // 遍历所有段落
            for (int i = 0; i < paragraphs.length; i++) {
                String paragraph = paragraphs[i].trim();
                System.out.println("处理第 " + (i+1) + " 段: " + (paragraph.length() > 50 ? paragraph.substring(0, 50) + "..." : paragraph));

                if (paragraph.isEmpty()) {
                    continue;
                }

                // 检查是否是标题
                if (paragraph.startsWith("# ")) {
                    // 处理以 # 开头的标题
                    String title = paragraph.substring(2).trim(); // 移除 "# "
                    System.out.println("发现标题: " + title);
                    //.setTextAlignment(TextAlignment.CENTER)
                    Paragraph titlePara = new Paragraph(title)
                            .setFontSize(18)
                            .setBold()
                            .setMarginBottom(20);
                    document.add(titlePara);
                }
                else if (paragraph.startsWith("**") && paragraph.endsWith("**")) {
                    // 处理以 ** 开头和结尾的标题
                    String title = paragraph.substring(2, paragraph.length() - 2).trim(); // 移除开头和结尾的 **
                    System.out.println("发现标题: " + title);

                    Paragraph titlePara = new Paragraph(title)
                            .setFontSize(18)
                            .setBold()

                            .setMarginBottom(20);
                    document.add(titlePara);
                }
                // 检查是否是图片
                else if (paragraph.startsWith("![")) {
                    String imageUrl = extractImageUrl(paragraph);
                    if (imageUrl != null) {
                        System.out.println("发现图片,URL: " + imageUrl);
                        try {
                            ImageData imageData = ImageDataFactory.create(new URL(imageUrl));
                            Image image = new Image(imageData);
                            image.setAutoScale(true);
                            image.setMaxWidth(UnitValue.createPointValue(400));
                            image.setTextAlignment(TextAlignment.CENTER);
                            document.add(image);
                        } catch (Exception e) {
                            System.err.println("无法加载图片: " + e.getMessage());
                            Paragraph errorPara = new Paragraph("[图片加载失败: " + imageUrl + "]")
                                    .setFontColor(ColorConstants.RED);
                            document.add(errorPara);
                        }
                    }
                }
                // 普通文本段落
                else {
                    System.out.println("发现文本段落,长度: " + paragraph.length());
                    if (!paragraph.isEmpty()) {
                        Paragraph textPara = new Paragraph(paragraph)
                                .setFontSize(12)
                                .setMarginBottom(10)
                                .setFirstLineIndent(20);
                        document.add(textPara);
                    }
                }
            }

            System.out.println("所有内容处理完成");
        } finally {
            document.close();
            System.out.println("PDF文档已关闭");
        }
    }


    private static String extractImageUrl(String markdown) {
        Pattern pattern = Pattern.compile("!\\[.*?\\]\\((.*?)\\)");
        Matcher matcher = pattern.matcher(markdown);
        if (matcher.find()) {
            return matcher.group(1);
        }
        return null;
    }
}