gpt4 book ai didi

python - 在 python 中使用 PyPDF2 合并 pdf 文件时找不到 EOF 标记

转载 作者:太空宇宙 更新时间:2023-11-03 15:53:00 25 4
gpt4 key购买 nike

当我使用下面的代码时

from PyPDF2 import PdfFileMerger

merge = PdfFileMerger()

for newFile in nlst:
merge.append(newFile)
merge.write("newFile.pdf")

发生了如下事情:

raise utils.PdfReadError("EOF marker not found")

PyPDF2.utils.PdfReadError: EOF marker not found

谁能告诉我发生了什么事?

最佳答案

在使用 camelotPyPDF2 遇到这个问题后,我做了一些挖掘并解决了这个问题。

文件结束标记 '%%EOF' 本来是最后一行,但有些 PDF 文件在这一行之后放了一大块 javascript,读者找不到 EOF .

打开 EOF 和 javascript 后的样子:

 b'>>\r\n',
b'startxref\r\n',
b'275824\r\n',
b'%%EOF\r\n',
b'\n',
b'\n',
b'<script type="text/javascript">\n',
b'\twindow.parent.focus();\n',
b'</script><!DOCTYPE html>\n',
b'\n',
b'\n',
b'\n',

所以你只需要在 javascript 开始之前截断文件。

解决方法:

def reset_eof_of_pdf_return_stream(pdf_stream_in:list):
# find the line position of the EOF
for i, x in enumerate(txt[::-1]):
if b'%%EOF' in x:
actual_line = len(pdf_stream_in)-i
print(f'EOF found at line position {-i} = actual {actual_line}, with value {x}')
break

# return the list up to that point
return pdf_stream_in[:actual_line]

# opens the file for reading
with open('data/XXX.pdf', 'rb') as p:
txt = (p.readlines())

# get the new list terminating correctly
txtx = reset_eof_of_pdf_return_stream(txt)

# write to new pdf
with open('data/XXX_fixed.pdf', 'wb' as f:
f.writelines(txtx)

fixed_pdf = PyPDF2.PdfFileReader('data/XXX_fixed.pdf')

关于python - 在 python 中使用 PyPDF2 合并 pdf 文件时找不到 EOF 标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45390608/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com