【发布时间】:2016-07-05 18:29:29
【问题描述】:
脚本创建了正确的 pdf 文件(遗憾的是,它的输出不能直接写入标准输出)。假设文件名是“myfile.pdf”。
我想将准确的 pdf 内容打印到标准输出。 (中间没有处理)。
为了测试这一点,我编写了这个简短的read_pdf.py 脚本:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
with open('myfile.pdf', mode='rb') as pdf_file:
for line in pdf_file:
print(str(line))
我使用'rb' 模式,因为在文本模式下阅读会导致UnicodeDecodeError: 'utf-8' codec can't decode byte 0xd0 in position 10: invalid continuation byte。所以,看起来没有其他选择(如果文本模式不起作用,那么二进制模式)。
现在问题当然是输出包含不能用作 pdf 文件的 b'blablabla' 行。为了检查它,我将read_pdf.py 重定向到一个文件并尝试用pdf查看器打开它,当然它不起作用:
$ ./read_pdf.py > test_output.pdf
$ evince test_output.pdf
Syntax Error: Couldn't find trailer dictionary
Syntax Error: Couldn't read xref table
Syntax Error: Couldn't find trailer dictionary
Syntax Error: Couldn't read xref table
那么,正确的做法是什么?我没有检查任何 pdf 专用库,因为它看起来没有必要,我希望能够阅读和打印正确的内容,而无需为此导入 pdf 库。
chardet.detect(pdf_file.read()) 忍不住(它返回了{'encoding': None, 'confidence': 0.0})。
编辑: * 我正在寻找适用于 python3 和 Linux/Unix 系统的解决方案,而不是 windows。 * 我需要知道如何在 python 中执行此操作,因为它实际上是一个完全用 python 编写的更大项目的一部分
【问题讨论】:
-
有什么理由你不能只是
cat some.pdf? -
@armandino 因为它实际上是一个完全用 python 编写的更大项目的一部分
-
@Robᵩ 但这是针对 python3 而不是关于 Windows。我将把这个精确度添加到问题中。
标签: python linux python-3.x pdf readfile