[英]pyPdf PdfFileReader vs PdfFileWriter
我有以下代碼:
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()
直到現在我只是從PDF文檔閱讀,后來才從PDF寫為TXT ...但是現在這...為什么PdfFileReader
相差這么多從PdfFileWriter
有人可以解釋嗎? 我希望這樣的事情:
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)
最后,這會將存儲在內存中的對象寫入文件,構建標頭,交叉引用表,並將所有內容鏈接在一起。
編輯:大概是,JUST CREATED標志表明PyPDF開始建立適當的表並將事物鏈接在一起。
-
回應為什么vs .txt和csv:
從文本或CSV文件復制時,沒有現有的數據結構可以理解和移動,以確保正確保存和創建格式,圖像放置和表單數據(輸入節等)之類的東西。
之所以很有可能這樣做是因為PDF並不是完全線性的-“標題”實際上位於文件的末尾。
如果每次進行更改時都將文件寫入磁盤,則您的計算機需要繼續將數據推送到磁盤上。 取而代之的是,模塊(可能)將有關文檔的信息存儲在對象(PdfFileWriter)中,然后在您請求時將其轉換為實際的PDF文件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.