我怎么知道我的文件是使用PyPDF2附加在我的PDF中的? [英] How do I know my file is attached in my PDF using PyPDF2?

查看:62
本文介绍了我怎么知道我的文件是使用PyPDF2附加在我的PDF中的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我运行了代码.它可以完美运行,但是我的PDF文件仍然是相同大小.
我不知道我的文件是否已附加.

这就是我想要做的:

从PyPDF2中的

 导入PdfFileWriter,PdfFileReader输出= PdfFileWriter()input1 = PdfFileReader(打开("doc1.pdf","rb"))#检查是否有效print("doc1有%d页"%input1.getNumPages())output.addAttachment("doc1.pdf","client.exe") 

我不知道我是否做对了.如果有人知道这一点,请帮帮我.

解决方案

首先,您必须使用

作为旁注,我不确定要将exe文件附加到PDF的目的,但是似乎可以附加它们,但是

I don't know if I am doing this right or not. Please if anyone know about this help me out.

First of all, you have to use the PdfFileWriter class properly.

You can use 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 to actually save the PdfFileWriter object to an actual PDF file.

Here is a more working example:

from PyPDF2 import PdfFileWriter, PdfFileReader

output = PdfFileWriter()

input_pdf = PdfFileReader("doc1.pdf")
output.appendPagesFromReader(input_pdf)

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

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

Next, to check if attaching was successful, you can use os.stat.st_size to compare the file size (in bytes) before and after attaching the .exe file.

Here is the same example with checking for file sizes:
(I'm using Python 3.6+ for f-strings)

from PyPDF2 import PdfFileWriter, PdfFileReader
import os

output = PdfFileWriter()

print(f"size of SOURCE: {os.stat('doc1.pdf').st_size}")
input_pdf = PdfFileReader("doc1.pdf")
output.appendPagesFromReader(input_pdf)

print(f"size of EXE: {os.stat('client.exe').st_size}")
with open("client.exe", "rb") as exe:
    output.addAttachment("client.exe", exe.read())

with open("out.pdf", "wb") as f:
    output.write(f)
print(f"size of OUTPUT: {os.stat('out.pdf').st_size}")

The above code prints out

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

...which sort of shows that the .exe file was added to the PDF.

Of course, you can manually check it by opening the PDF in Adobe Reader:

As a side note, I am not sure what you want to do with attaching exe files to PDF, but it seems you can attach them but Adobe treats them as security risks and may not be possible to be opened. You can use the same code above to attach another PDF file (or other documents) instead of an executable file, and it should still work.

这篇关于我怎么知道我的文件是使用PyPDF2附加在我的PDF中的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆