gpt4 book ai didi

python - pyPdf PdfFileReader 与 PdfFileWriter

转载 作者:太空宇宙 更新时间:2023-11-03 17:55:09 34 4
gpt4 key购买 nike

我有以下代码:

import os
from pyPdf import PdfFileReader, PdfFileWriter

path = "C:/Real Python/Course materials/Chapter 12/Practice files"

input_file_name = os.path.join(path, "Pride and Prejudice.pdf")
input_file = PdfFileReader(file(input_file_name, "rb"))
output_PDF = PdfFileWriter()

for page_num in range(1, 4):
output_PDF.addPage(input_file.getPage(page_num))

output_file_name = os.path.join(path, "Output/portion.pdf")
output_file = file(output_file_name, "wb")
output_PDF.write(output_file)
output_file.close()

到目前为止,我只是从 Pdfs 中阅读,后来学会了从 Pdf 写入 txt...但是现在这个...为什么 PdfFileReaderPdfFileWriter

差异如此之大

有人能解释一下吗?我期望类似的东西:

import os
from pyPdf import PdfFileReader, PdfFileWriter

path = "C:/Real Python/Course materials/Chapter 12/Practice files"

input_file_name = os.path.join(path, "Pride and Prejudice.pdf")
input_file = PdfFileReader(file(input_file_name, "rb"))

output_file_name = os.path.join(path, "out Pride and Prejudice.pdf")
output_file = PdfFileWriter(file(output_file_name, "wb"))

for page_num in range(1,4):
page = input_file.petPage(page_num)
output_file.addPage(page_num)
output_file.write(page)

有什么帮助吗???谢谢

编辑0: .addPage() 的作用是什么?

for page_num in range(1, 4):
output_PDF.addPage(input_file.getPage(page_num))

它只是创建 3 个空白页吗?

编辑1:有人可以解释一下发生了什么:

1) output_PDF = PdfFileWriter()

2) output_PDF.addPage(input_file.getPage(page_num))

3) output_PDF.write(output_file)

第三个将 JUST CREATED(!) 对象传递给 output_PDF ,为什么?

最佳答案

问题基本上是 PDF 交叉引用表。

这是一个有点困惑的意大利面条怪物,引用了页面、字体、对象、元素,而这些都需要链接在一起以允许随机访问。

每次更新文件时,都需要重建该表。该文件首先在内存中创建,因此这只需要发生一次,并进一步减少文件被烧毁的机会。

output_PDF = PdfFileWriter()

这会在内存中创建供 PDF 进入的空间。 (从您的旧 pdf 中提取)

output_PDF.addPage(input_file.getPage(page_num))

将输入 pdf 中的页面添加到内存中创建的 PDF 文件中(您想要的页面。)

output_PDF.write(output_file)

最后,这会将内存中存储的对象写入文件,构建 header 、交叉引用表,并将所有内容链接在一起。

编辑:据推测,JUST CREATED 标志指示 PyPDF 开始构建适当的表并将事物链接在一起。

--

回应 .txt 和 csv 的原因:

当您从文本或 CSV 文件进行复制时,没有任何现有数据结构可供理解和移动,以确保正确保留和创建格式、图像位置和表单数据(输入部分等)等内容。

关于python - pyPdf PdfFileReader 与 PdfFileWriter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28573256/

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