python - PDF转换后文件打开异常

标签 python pdf python-3.6

使用 pdftotext 终端命令(我运行的是 Ubuntu 17.04)将 PDF 中的文本剥离为文本 (.txt) 文件,然后尝试从文件中读取内容后,我得到了非常奇怪的输出。我用一个txt测试了代码,其中只有一个单词:test。该代码有效。它完美地从文件中打印出来,这告诉我这要么是 pdftotext 的错误,要么是编码的错误。真正吸引我并让我来到这里的是该文件可以正常在文本编辑器中打开,并且所有测试都表明该文件采用标准 UTF-8。这是我的PDF stripped text file ,创建于:

import tkinter
from tkinter.filedialog import askopenfilename
import subprocess
from subprocess import *
import os
from tkinter import Listbox
import sys
from tkinter import Scrollbar
from tkinter import Frame
from tkinter import Label
from tkinter import messagebox
from tkinter import Button

#win32, cygwin, linux, linux2, darwin

def chooser():
    returnedValue['filename'] = askopenfilename(**opts)
    try:
        subprocess.run(['pdftotext', returnedValue['filename'], '-raw'], check = True)
    except (TypeError, subprocess.CalledProcessError) as e:
        messagebox.showerror("Null error", "No file selected")
    if sys.platform == "linux" or sys.platform == "linux2" or sys.platform == "darwin":
        label = returnedValue['filename'].split('/')
        file2['file2'] = label[len(label)-1]
    else:
        label = returnedValue['filename'].split('\\')
        file2['file2'] = label[len(label)-1]

    L.insert(0, label[len(label)-1])

def trello():
    with open(returnedValue['filename'], 'r', encoding='utf8', errors='ignore') as f:
        content = f.readlines()
    content = [x.strip() for x in content]
    for line in content:
        print(line)


opts = {}
opts['filetypes'] = [('Portable Document Format','.pdf'),('all files','.*')]
opts['defaultextension'] = '.pdf'
opts['title'] = 'Select File'
opts['initialdir'] = [os.path.expanduser('~/')]

returnedValue = {}
returnedValue['filename'] = ""
file2 = {}
file2['file2'] = ""
root = tkinter.Tk()

B = Button(root, text = "Convert PDF", command = chooser)
B.pack()

F = Frame(root)

La = Label(F, text="PDFs Converted:")
La.pack()

S = Scrollbar(F)
S.pack(side=tkinter.RIGHT, fill=tkinter.Y)

L = Listbox(F, height=5, yscrollcommand=S.set)
L.pack()

S.config(command=L.yview)

F.pack()

Bue = Button(root, text="Send to Trello", command = trello)
Bue.pack()

root.geometry('{}x{}'.format(500, 500))
root.attributes("-topmost", True)
root.wm_title("PDF Chooser")
root.mainloop()

这是我在 open() 函数中不使用 errors='ignore' 时收到的错误:

Exception in Tkinter callback
Traceback (most recent call last):
  File "/usr/lib/python3.6/tkinter/__init__.py", line 1702, in __call__
    return self.func(*args)
  File "./pdftotextCVM.py", line 34, in trello
    content = f.readlines()
  File "/usr/lib/python3.6/codecs.py", line 321, in decode
    (result, consumed) = self._buffer_decode(data, self.errors, final)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 11:     invalid start byte

here这是我使用 errors=ignore 时得到的结果。最后的粘贴可以追溯到我的 Ubuntu 终端历史记录,所以可能还有更多,但你明白了。旁注:如果你看不出来,我正在使用 Python 3.6。

最佳答案

errors=ignore 向下滚动,经过二进制垃圾。输出,我看到:

22 0 obj
<<
/Type /Font
/Subtype /Type0
/BaseFont /OXSVSB+TimesNewRoman/Encoding /Identity-H
/ToUnicode 23 0 R
/DescendantFonts[ 24 0 R ]
>>

这些是 PDF 说明。好像输入.pdf。正在打开文件,而不是输出 .txt 文件。

在打开文件之前,trello() 函数可能需要将扩展​​名从 .pdf 更改为 .txt

关于python - PDF转换后文件打开异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41754011/

相关文章:

javascript - 使用 Google Apps 脚本,如何将每张演示文稿幻灯片下载为 pdf 格式?

python - 为什么在 Python 中不允许单一类型约束?

python - python-3.6 中带有 'f' 前缀的字符串

python - 苹果系统; Python3; FileNotFoundError : [Errno 2] No such file or directory: '' . 如何修复?

python - 在 Python 中从日期中减去 n 天

python - Google Drive API v3(googleapiclient.errors.HttpError 404 找不到文件)

Python——计算共现矩阵

python - 在同一台 OSX 机器上使用多个开发环境?

Java 生成的 PDF 在屏幕上呈现良好,但打印不正确

java - 从 Jasper Reports 生成的 PDF 中的 SVG 标记