PDF文件转换成为Excel格式的实现方式

PDF转换为 Excel 可以更好地利用 Excel 表格的计算过滤排序搜索等功能,PDF文件的数据要想提取数据到数据库当中是比较困难的,但是如果我们做一步操作将pdf转换为Excel格式的文件,这样我们就很容易将数据提取到数据库中了。这样的话呢,我们就可以避免了手动输入,提高了转换的时间和效率,所以实现将PDF转换成Excel文件的格式是非常必要的, 将 PDF 文件转换为 Excel 文件之后,可以更方便地对数据进行逻辑分析,对数据进行可视化展示,更便于进行数据挖掘和分析。PDF 文件转换为 Excel 文件不仅可以提高数据处理效率、还可以方便共享和合作,帮助团队更好地进行数据处理和项目开发

使用开源组织提供的开源框架 pdfbox

https://pdfbox.apache.org/

特点:免费,功能强大

PDFTextStripper stripper = new PDFTextStripper();

stripper .setSortByPosition(sort); //sort设置为true 则按照行进行读取,默认是false

1.pdfbox 需要带入依赖
   <dependency>
            <groupId>org.apache.pdfbox</groupId>
            <artifactId>pdfbox</artifactId>
            <version>2.0.15</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.apache.pdfbox/fontbox -->
        <dependency>
            <groupId>org.apache.pdfbox</groupId>
            <artifactId>fontbox</artifactId>
            <version>2.0.15</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.apache.pdfbox/jempbox -->
        <dependency>
            <groupId>org.apache.pdfbox</groupId>
            <artifactId>jempbox</artifactId>
            <version>1.8.16</version>
        </dependency>
2.代码
/**
 * 功能 PDF读写类
 */
public class PDFUtil {

    //  public static final String CHARACTOR_FONT_CH_FILE = "SIMFANG.TTF";  //仿宋常规
    public static final String CHARACTOR_FONT_CH_FILE = "SIMHEI.TTF";  //黑体常规

    public static final Rectangle PAGE_SIZE = PageSize.A4;
    public static final float MARGIN_LEFT = 50;
    public static final float MARGIN_RIGHT = 50;
    public static final float MARGIN_TOP = 50;
    public static final float MARGIN_BOTTOM = 50;
    public static final float SPACING = 20;


    private Document document = null;

    /**
     * 功能:创建导出数据的目标文档
     * @param fileName 存储文件的临时路径
     * @return
     */
    public void createDocument(String fileName) {
        File file = new File(fileName);
        FileOutputStream out = null;
        document = new Document(PAGE_SIZE, MARGIN_LEFT, MARGIN_RIGHT, MARGIN_TOP, MARGIN_BOTTOM);
        try {
            out = new FileOutputStream(file);
//          PdfWriter writer =
            PdfWriter.getInstance(document, out);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        // 打开文档准备写入内容
        document.open();
    }

    /**
     * 将章节写入到指定的PDF文档中
     * @param chapter
     * @return
     */
    public void writeChapterToDoc(Chapter chapter) {
        try {
            if(document != null) {
                if(!document.isOpen()) document.open();
                document.add(chapter);
            }
        } catch (DocumentException e) {
            e.printStackTrace();
        }
    }

    /**
     * 功能  创建PDF文档中的章节
     * @param title 章节标题
     * @param chapterNum 章节序列号
     * @param alignment 0表示align=left,1表示align=center
     * @param numberDepth 章节是否带序号 设值=1 表示带序号 1.章节一;1.1小节一...,设值=0表示不带序号
     * @param font 字体格式
     * @return Chapter章节
     */
    public static Chapter createChapter(String title, int chapterNum, int alignment, int numberDepth, Font font) {
        Paragraph chapterTitle = new Paragraph(title, font);
        chapterTitle.setAlignment(alignment);
        Chapter chapter = new Chapter(chapterTitle, chapterNum);
        chapter.setNumberDepth(numberDepth);
        return chapter;
    }

    /**
     * 功能:创建某指定章节下的小节
     * @param chapter 指定章节
     * @param title 小节标题
     * @param font 字体格式
     * @param numberDepth 小节是否带序号 设值=1 表示带序号 1.章节一;1.1小节一...,设值=0表示不带序号
     * @return section在指定章节后追加小节
     */
    public static Section createSection(Chapter chapter, String title, Font font, int numberDepth) {
        Section section = null;
        if(chapter != null) {
            Paragraph sectionTitle = new Paragraph(title, font);
            sectionTitle.setSpacingBefore(SPACING);
            section = chapter.addSection(sectionTitle);
            section.setNumberDepth(numberDepth);
        }
        return section;
    }

    /**
     * 功能:向PDF文档中添加的内容
     * @param text 内容
     * @param font 内容对应的字体
     * @return phrase 指定字体格式的内容
     */
    public static Phrase createPhrase(String text,Font font) {
        Phrase phrase = new Paragraph(text,font);
        return phrase;
    }

    /**
     * 功能:创建列表
     * @param numbered  设置为 true 表明想创建一个进行编号的列表
     * @param lettered 设置为true表示列表采用字母进行编号,为false则用数字进行编号
     * @param symbolIndent
     * @return list
     */
    public static List createList(boolean numbered, boolean lettered, float symbolIndent) {
        List list = new List(numbered, lettered, symbolIndent);
        return list;
    }

    /**
     * 功能:创建列表中的项
     * @param content 列表项中的内容
     * @param font 字体格式
     * @return listItem
     */
    public static ListItem createListItem(String content, Font font) {
        ListItem listItem = new ListItem(content, font);
        return listItem;
    }

    /**
     * 功能:创造字体格式
     * @param fontname
     * @param size 字体大小
     * @param style 字体风格
     * @param color 字体颜色
     * @return Font
     */
    public static Font createFont(String fontname, float size, int style, BaseColor color) {
        Font font =  FontFactory.getFont(fontname, size, style, color);
        return font;
    }

    /**
     * 功能: 返回支持中文的字体---仿宋
     * @param size 字体大小
     * @param style 字体风格
     * @param color 字体 颜色
     * @return  字体格式
     */
    public static Font createCHineseFont(float size, int style, BaseColor color) {
        BaseFont bfChinese = null;
        try {
            bfChinese = BaseFont.createFont(CHARACTOR_FONT_CH_FILE,BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new Font(bfChinese, size, style, color);
    }

    /**
     * 最后关闭PDF文档
     */
    public void closeDocument() {
        if(document != null) {
            document.close();
        }
    }


    /**
     * 读PDF文件,使用了pdfbox开源项目
     * @param fileName
     */
    public static  void readPDF(String fileName) {
        File file = new File(fileName);
        FileInputStream in = null;
        try {
            in = new FileInputStream(fileName);
            // 新建一个PDF解析器对象
            PDFParser parser = new PDFParser(new RandomAccessFile(file,"rw"));
            // 对PDF文件进行解析
            parser.parse();
            // 获取解析后得到的PDF文档对象
            PDDocument pdfdocument = parser.getPDDocument();
            // 新建一个PDF文本剥离器
            PDFTextStripper stripper = new PDFTextStripper();
            // 从PDF文档对象中剥离文本
            String result = stripper.getText(pdfdocument);
            FileWriter fileWriter = new FileWriter(new File("pdf.txt"));
            fileWriter.write(result);
            fileWriter.flush();
            fileWriter.close();
            System.out.println("PDF文件的文本内容如下:");
            System.out.println(result);

        } catch (Exception e) {
            System.out.println("读取PDF文件" + file.getAbsolutePath() + "生失败!" + e);
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e1) {
                }
            }
        }
    }


    /**
     * 测试pdf文件的创建
     * @param args
     */
    public static void main(String[] args) {

        String fileName = "C:\Users\tizzy\Desktop\测试.pdf";  //这里先手动把绝对路径的文件夹给补上。
        PDFUtil pdfUtil = new PDFUtil();
        pdfUtil.writeChapterToDoc(chapter);
        pdfUtil.closeDocument();
    }
}

目前写这一种方式,后期如有需要再另行编辑。

  • 4
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要将PDF文件转换Excel,可以考虑使用第三方库或在线转换工具。 1. 使用第三方库 可以使用 PHPExcel 库来处理 Excel 文件。首先需要将 PDF 文件转换为 CSV 文件,然后再使用 PHPExcel 将 CSV 文件转换Excel 文件。 以下是示例代码: ```php require_once 'PHPExcel/Classes/PHPExcel.php'; require_once 'PHPExcel/Classes/PHPExcel/IOFactory.php'; // Convert PDF to CSV using pdftotext command $pdf_file = 'example.pdf'; $csv_file = 'example.csv'; shell_exec("pdftotext -layout $pdf_file $csv_file"); // Load CSV file into PHPExcel $objPHPExcel = PHPExcel_IOFactory::load($csv_file); // Save as Excel file $excel_file = 'example.xlsx'; $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007'); $objWriter->save($excel_file); ``` 2. 使用在线转换工具 可以使用在线转换工具如 Zamzar、PDFTables、SmallPDF 等将 PDF 文件转换Excel 文件。这些工具都提供了 API 或 SDK 可以与 PHP 集成使用。 以下是示例代码: ```php // Using Zamzar API $source_file = 'example.pdf'; $target_format = 'xlsx'; $zamzar_api_key = 'your_zamzar_api_key'; $zamzar_url = "https://api.zamzar.com/v1/jobs"; $data = array( "source_file" => curl_file_create($source_file), "target_format" => $target_format ); $headers = array( "Content-Type: multipart/form-data", "Accept: application/json", "Authorization: Basic " . base64_encode($zamzar_api_key . ":") ); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $zamzar_url); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, $data); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $result = curl_exec($ch); curl_close($ch); $job = json_decode($result); // Check status of the job $job_id = $job->id; $zamzar_api_key = 'your_zamzar_api_key'; $zamzar_url = "https://api.zamzar.com/v1/jobs/$job_id"; $headers = array( "Content-Type: application/json", "Accept: application/json", "Authorization: Basic " . base64_encode($zamzar_api_key . ":") ); while (true) { $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $zamzar_url); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $result = curl_exec($ch); curl_close($ch); $job = json_decode($result); if ($job->status == "successful") { // Download Excel file $excel_url = $job->target_files[0]->url; $excel_file = 'example.xlsx'; file_put_contents($excel_file, file_get_contents($excel_url)); break; } elseif ($job->status == "failed") { // Handle error break; } else { // Wait and check again sleep(5); } } ``` 注意:使用在线转换工具需要提供 API 密钥,并且可能需要付费。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值