知识库RAG应用--文档转换(Docs转PDF)

Docs转PDF

在构建知识库应用时,发现在文档解析步骤,PDF解析(使用pdfplumber)的效果(在处理表格方面)要强于Docs文档(使用unstructured);
分析该现象,发现一些专门文档的解析工具包在处理文档时的效果会优于一些通用类的工具;
故在文档加载阶段,初步定了两种处理方案:

  1. 不同文档类型使用效果较优的工具进行处理;
  2. 将非PDF文档转换为PDF文档后(转换后无法修改),进行处理;
    本笔记是记录Docs转换为PDF的使用过程;

工具选择

由于服务系统环境为Linux,故只考虑Linux环境下的工具使用

  • LibreOffice
1. 安装LibreOffice
sudo apt-get install libreoffice

2. 工具命令行方式
libreoffice --headless --convert-to pdf your_document.docx --outdir /path/to/output

3. python方式使用
import subprocess
import os
def convert_doc_to_pdf(input_path, output_dir):
    # 确保输入文件存在
    if not os.path.exists(input_path):
        raise FileNotFoundError(f"输入文件不存在: {input_path}")

    # 构造命令
    cmd = [
        "libreoffice",
        "--headless",
        "--convert-to", "pdf",
        input_path,
        "--outdir", output_dir
    ]

    # 执行命令
    result = subprocess.run(cmd, capture_output=True, text=True)
    if result.returncode != 0:
        raise RuntimeError(f"转换失败: {result.stderr}")
    else:
        print(f"转换成功!PDF 保存至: {output_dir}")

# 示例用法
convert_doc_to_pdf("input.doc", "/tmp/output")

  • Pandoc + LaTeX
1. 安装依赖
apt-get install pandoc texlive-full

2. 命令行方式
pandoc -s your_document.docx -o output.pdf

3. python方式使用
import pypandoc

def word_to_pdf(word_path, pdf_path):
    output = pypandoc.convert_file(word_path, 'pdf', outputfile=pdf_path,extra_args=['--pdf-engine=xelatex'])
    assert output == ""
# 将Word文档转换为PDF
word_to_pdf("docs/test_01.docx", "pdfs/trans_test_01.pdf")

过程问题处理

  • LaTeX升级到最新版本
通过apt-get安装的版本较老,若要升级到最新版本,可通过从官网下载安装包进行安装,步骤如下:
a.) wget http://mirror.ctan.org/systems/texlive/tlnet/install-tl-unx.tar.gz
b.) 解压并安装(安装的时间比较长)
tar -xzf install-tl-unx.tar.gz
cd install-tl-*
./install-tl
PS:在安装过程中,如果磁盘空间足够,可以选择安装完整版(scheme-full),这样会包含所有可用的 TeX Live 包;
c.) 配置PATH
echo 'export PATH=/usr/local/texlive/2025/bin/x86_64-linux:$PATH' >> ~/.bashrc
source ~/.bashrc
d.) 验证安装
tlmgr --version 或则 tlmgr info --list
  • 执行libreoffice命令时提示错误
1. 错误信息如下:
/usr/lib/libreoffice/program/javaldx: error while loading shared libraries: libreglo.so: cannot open shared object file: No such file or directory
Warning: failed to read path from javaldx

2. 原因分析
javaldx找不到libreglo.so,查看/usr/lib/libreoffice/program/ 目录下是否存在libreglo.so;
该目录下已经存在libreglo.so,执行命令 ldd /usr/lib/libreoffice/program/javaldx,发现: libreglo.so => not found

3. 处理方式
强制刷新系统的库缓存:
echo '/usr/lib/libreoffice/program' | sudo tee /etc/ld.so.conf.d/libreoffice.conf
sudo ldconfig

4. 如果依旧不能执行该命令,则
a.) 重新安装
先清除配置文件(如果有):
rm -rf ~/.config/libreoffice
rm -rf ~/.local/share/libreoffice
再进行重新安装:
sudo apt purge libreoffice*
sudo apt autoremove
sudo apt install libreoffice

或则
b.) 使用容器化运行(Ubuntu)
拉取镜像:
docker pull libreoffice

运行libreoffice容器:
docker run -d --name libreoffice -v /path/to/your/documents:/documents libreoffice

测试功能:
docker exec -it libreoffice /bin/bash
libreoffice --version
libreoffice --headless --convert-to pdf --outdir /documents /documents/input.docx
同时Python的使用方式修改如下:
import subprocess
container_name = "img_libreoffice"
command_to_run = ["libreoffice", "--headless","--convert-to","pdf","--outdir","/documents","/documents/test.docx"]

docker_exec_command = ["docker", "exec", container_name] + command_to_run

process = subprocess.Popen(docker_exec_command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)

stdout, stderr = process.communicate()
if process.returncode == 0:
    print("Command executed successfully!")
    print("Output:")
    print(stdout)
else:
    print("Failed to execute command in container.")
    print("Error:", stderr)

  • pandoc转换时,提示无法在指定的字体中找到字符
1. 错误信息如下:
[WARNING] Missing character: There is no 有 (U+6709) (U+6709) in font [lmroman10-regular]:mapping=t

2. 处理方式
指定引擎(xelatex)和字符集,先查看系统支持中文的字符集(fc-list :lang=zh);
在pandoc命令中指定字符集如: pandoc -s your_document.docx -o output.pdf --pdf-engine=xelatex -V mainfont="Noto Sans CJK TC"
python代码如下:
import pypandoc

def word_to_pdf(word_path, pdf_path):
    output = pypandoc.convert_file(word_path, 'pdf', outputfile=pdf_path,extra_args=['--pdf-engine=xelatex','-V', 'mainfont="Noto Sans CJK TC"'])
    assert output == ""
# 将Word文档转换为PDF
word_to_pdf("docs/01.docx", "pdfs/trans_01.pdf")
print(f'deal finish!!')

## 如果总是提示"xelatex not found"则直接使用完全路径,如:/usr/local/texlive/2025/bin/x86_64-linux/xelatex
PS:如果word文档中的表格是合并单元格之类的复杂表格,pandoc转换后,表格的信息可能丢失。
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容