我怎么知道我的文件是使用 PyPDF2 附加到我的 PDF 中的?

How do I know my file is attached in my PDF using PyPDF2?

我正在尝试使用 PyPDF2 将 .exe 文件附加到 PDF 中。

我运行下面的代码,但是我的PDF文件还是一样大小。
我不知道我的文件是否已附加。

from PyPDF2 import PdfFileWriter, PdfFileReader

writer = PdfFileWriter()
reader = PdfFileReader("doc1.pdf")

# check it's whether work or not
print("doc1 has %d pages" % reader.getNumPages())

writer.addAttachment("doc1.pdf", "client.exe")

我做错了什么?

首先,你要正确使用PdfFileWriterclass

您可以使用 appendPagesFromReader to copy pages from the source PDF ("doc1.pdf") to the output PDF (ex. "out.pdf"). Then, for addAttachment, the 1st parameter is the filename of the file to attach and the 2nd parameter is the attachment data (it's not clear from the docs, but it has to be a bytes-like sequence). To get the attachment data, you can open the .exe file in binary mode, then read() it. Finally, you need to use write 实际 将 PdfFileWriter 对象保存到 实际 PDF 文件。

这是一个更有效的例子:

from PyPDF2 import PdfFileReader, PdfFileWriter

reader = PdfFileReader("doc1.pdf")
writer = PdfFileWriter()

writer.appendPagesFromReader(reader)

with open("client.exe", "rb") as exe:
    writer.addAttachment("client.exe", exe.read())

with open("out.pdf", "wb") as f:
    writer.write(f)

接下来,要检查附加是否成功,您可以使用os.stat.st_size比较附加.exe文件前后的文件大小(以字节为单位)。

这是检查文件大小的相同示例:
我使用 Python 3.6+ for f-strings

import os
from PyPDF2 import PdfFileReader, PdfFileWriter


reader = PdfFileReader("doc1.pdf")
writer = PdfFileWriter()
writer.appendPagesFromReader(reader)

with open("client.exe", "rb") as exe:
    writer.addAttachment("client.exe", exe.read())

with open("out.pdf", "wb") as f:
    writer.write(f)

# Check result
print(f"size of SOURCE: {os.stat('doc1.pdf').st_size}")
print(f"size of EXE: {os.stat('client.exe').st_size}")
print(f"size of OUTPUT: {os.stat('out.pdf').st_size}")

以上代码打印出来

size of SOURCE: 42942
size of EXE: 989744
size of OUTPUT: 1031773

...哪种显示 .exe 文件已添加到 PDF。

当然可以在Adobe中打开PDF手动查看Reader:

附带说明一下,我不确定您想要将 exe 文件附加到 PDF 上做什么,但您似乎可以附加它们,但 Adobe treats them as security risks 并且可能无法打开。您可以使用上面的相同代码附加另一个 PDF 文件(或其他文档)而不是可执行文件,它应该仍然有效。