package org.dromara.knowledge.data;

import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfReader;
import com.itextpdf.kernel.pdf.canvas.parser.PdfTextExtractor;
import com.itextpdf.kernel.pdf.canvas.parser.listener.LocationTextExtractionStrategy;
import org.dromara.common.core.exception.ServiceException;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;

/**
 * PDF 文档解析器
 *
 * @author pengles
 */
@Component
public class PdfDocumentParser implements DocumentParser {
    @Override
    public String parse(byte[] bytes, String filename) {
        try (ByteArrayInputStream is = new ByteArrayInputStream(bytes)) {
            PdfReader reader = new PdfReader(is);
            PdfDocument pdf = new PdfDocument(reader);
            StringBuilder sb = new StringBuilder();
            for (int i = 1; i <= pdf.getNumberOfPages(); i++) {
                String text = PdfTextExtractor.getTextFromPage(pdf.getPage(i), new LocationTextExtractionStrategy());
                if (text != null && !text.isEmpty()) {
                    sb.append(text).append("\n");
                }
            }
            pdf.close();
            return sb.toString();
        } catch (Exception e) {
            throw new ServiceException("PDF解析失败: " + e.getMessage());
        }
    }
}
