上传双层pdf文档,提取pdf文字数据

该代码段处理MultipartFile对象,从中提取PDF内容。它使用PDFBox库解析PDF,按位置排序文本,提取特定页码的内容,并将数据存储到数据库中。如果对比文件名后缀失败,会抛出ServiceException。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

private boolean pdfPersistence(MultipartFile multipartFile, String url, String pafName, String fileName) throws IOException {
    // 是否排序
    boolean sort = false;
    // 开始提取页数
    int startPage = 1;
    // 结束提取页数
    int endPage = Integer.MAX_VALUE;
    SysHitch bean = new SysHitch();
    ArcDocuments documents = new ArcDocuments();
    String content = null;
    InputStream input = null;
    PDDocument document = null;
    try {
        long size = multipartFile.getSize() / 1024;

        input = multipartFile.getInputStream();
        // 加载 pdf 文档
        PDFParser parser = new PDFParser(input);
        parser.parse();
        document = parser.getPDDocument();
        // 获取内容信息
        PDFTextStripper pts = new PDFTextStripper();
        pts.setSortByPosition(sort);
        endPage = document.getNumberOfPages();

        for (int s = 1; s <= endPage; s++) {
            String[] split = fileName.split("/");
            String suffix = null;
            if (split.length > 1) {
                suffix = split[split.length - 1];
            }
            String suffixName = "";
            for (int i = 0; i < suffix.length(); i++) {
                char item = suffix.charAt(i);
                if (item == '.') {
                    break;
                }
                suffixName = suffixName + item;
            }
            String contrast = arcHitchMapper.contrast(suffixName);
            if (contrast == null) {
                throw new ServiceException(fileName + "失败");
            } else {
                try {
                    pts.setStartPage(s);
                    pts.setEndPage(s);
                    content = pts.getText(document);
                    bean.setPagination(s);
                    bean.setPageMaterials(content);
                    bean.setFileName(contrast);
                    bean.setUrl(url);
                    bean.setCapacity((int) size);
                    int i = arcHitchMapper.addUrl(bean);
                    if (i != 1) {
                        return false;
                    }
                } catch (Exception e) {
                    throw e;
                }
            }

        }
    } catch (Exception e) {
        throw e;
    } finally {
        if (null != input)
            input.close();
        if (null != document)
            document.close();
    }
    return true;
}
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值