18910140161

如何使用Python PDFMiner将PDF转换为HTML?-堆栈溢出

顺晟科技

2022-10-18 13:24:37

104

是否有任何代码片段将工作?我已经尝试将PDF转换为HTML.

from pdfminer.pdfinterp import PDFResourceManager
from pdfminer.pdfpage import PDFPage
from pdfminer.converter import HTMLConverter, TextConverter
from pdfminer.layout import LAParams
import os
import contextlib 
import tempfile
rsrcmgr = PDFResourceManager()
laparams = LAParams()
converter = HTMLConverter if format == 'html' else TextConverter
out_file = "A:\folder"
in_file = "A:\folder\pyhtml.html"
pdf_filename = 'insurance.pdf'
device = converter(rsrcmgr, out_file, codec='utf-8', laparams=laparams)
PDFPage.get_pages(rsrcmgr, device, in_file, pagenos=[1], maxpages=1)

with contextlib.closing(tempfile.NamedTemporaryFile(mode='r', suffix='.xml')) as xmlin:
    cmd = 'pdftohtml -xml -nodrm -zoom 1.5 -enc UTF-8 -noframes "%s" "%s"' % (
            pdf_filename, xmlin.name.rpartition('.')[0])
    os.system(cmd + " >/dev/null 2>&1")
    result = xmlin.read().decode('utf-8')

当我运行上面的代码时,它给我以下错误

Traceback (most recent call last):
  File "a:\folder\new - Copy.py", line 14, in <module>
    device = converter(rsrcmgr, out_file, codec='utf-8', laparams=laparams)
AttributeError: 'str' object has no attribute 'write'

顺晟科技:

AttributeError: 'str' object has no attribute 'write'

如果有.write的尝试,这意味着您应该提供可写的文件句柄,而不是str,您可以使用with open

使用

_文件中的
<代码>=";A:\folder\pyhtml.HTML";使用OPEN(在_文件中,";W";)作为输出_文件:设备=转换器(rsrcmgr,输出_文件,编解码器=' UTF-8 ',LAPARAMS=LAPARAMS)

如果您想了解有关in_file = "A:\folder\pyhtml.html" device = converter(rsrcmgr, out_file, codec='utf-8', laparams=laparams) 的更多信息,请阅读内置函数文档

  • TAG:
相关文章
我们已经准备好了,你呢?
2024我们与您携手共赢,为您的企业形象保驾护航