如何从PDF转换的XML文件中识别实际空格或可见空格与其他类型的空格

0 投票
1 回答
41 浏览
提问于 2025-04-12 18:32

在把PDF文件转换成XML文件的时候,有时候会发现一些不想要的空格出现在单词或句子的中间(比如不换行的空格、零宽空格等等)。这些空格在PDF文件里是看不见的。但是如果我想要在转换后的XML文件中只保留PDF里实际可见的空格,而忽略其他类型的空格,该怎么办呢?

def convert(case, input_file_path, targetfilepath, pages=0):
    if not pages:
        pagenums = set();
    else:
        pagenums = set(100);
    manager = PDFResourceManager()
    codec = 'utf-8'
    caching = True

    if case == 'text':
        output = io.StringIO()
        converter = TextConverter(manager, output, codec=codec, laparams=LAParams())
    if case == 'HTML':
        output = io.BytesIO()
        converter = HTMLConverter(manager, output, codec=codec, laparams=LAParams())
    if case == 'XML':
        output = io.BytesIO()
        converter = XMLConverter(manager, output, codec=codec, laparams=LAParams())

    interpreter = PDFPageInterpreter(manager, converter)
    infile = open(input_file_path, 'rb')

    for page in PDFPage.get_pages(infile, pagenums, caching=caching, check_extractable=True):
        interpreter.process_page(page)

    convertedPDF = output.getvalue()

    infile.close();
    converter.close();
    output.close()

    convertedFile = open(targetfilepath, 'wb')
    convertedFile.write(convertedPDF)
    convertedFile.close()


(convert('XML', input_file_path, directory_path_xml1, pages=None))

这是我把PDF转换成XML文件的方法

1 个回答

0

如果你使用的是 pdfminer.six 这个工具,下面这段代码应该能生成一个有效的 XML 输出文件:

from pdfminer.high_level import extract_text_to_fp
from io import BytesIO

with open('PDFSample.pdf', 'rb') as pdf_file:
    xml_output = BytesIO()
    extract_text_to_fp(pdf_file, xml_output, output_type='xml')
    xml_output.seek(0)
    xml_content = xml_output.read()

with open('output.xml', 'wb') as output_file:
    output_file.write(xml_content)

xml_output.close()

撰写回答