PyPDF模块无法生成有效的pdf fi

2024-09-29 02:26:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试用python编写一些程序来操作我的pdf beamer演示文稿。教授使用点击动态转换,所以一个页面有几个点击转换。我想打印这些报告,但我有大约5000页。所以我只想使用最后一个点击转换页面,所以我将页面数量减少到500个左右。我使用的是PyPDF2模块,但它不能生成有效的pdf文件。代码如下:

from pyPdf import PdfFileWriter, PdfFileReader
import os,sys

pdful = raw_input("Uneti ime fajla:")
output = PdfFileWriter()
input1 = PdfFileReader(open(pdful, "rb"))

m = []
f = True
print ("Uneti strane koje zelite da zadrzite.String 0 kraj unosa:\n")

while f:
   l = int(raw_input("Uneti broj stranice:"))
   if l == 0:
      f = not f
   else: m.append(l-1)

for i in range(len(m)):
    strana  = input1.getPage(int(m[i]))

    output.addPage(strana)

outputStream = file("Mat8.pdf","wb")
output.write(outputStream)
# string writings are in Serbian, but that's not so important. Program should take input from user: name of file to manipulate, and pages that should copy.

Tags: infromimportinputoutputrawpdfnot
1条回答
网友
1楼 · 发布于 2024-09-29 02:26:36

from pyPdf import PdfFileWriter, PdfFileReaderpyPdf已经停止,由PyPDF2继承。我不确定Python2,但在Python3中您应该import PyPDF2。在

  1. 不需要import os, sys。但是,如果您确实使用了sys.argv,那么您可以在bash中调用python3 xyz.py some_arg。这边sys.argv[1] == some_arg
  2. 我更喜欢使用映射,只要您不需要逐行读取输入。例如

    print ("Uneti strane koje zelite da zadrzite.String 0 kraj unosa:\n")
    m = map (lambda x: int(x) - 1, raw_input("Uneti broj stranice:").split())
    
  3. 而不是while循环。另外,迭代对象而不是索引。在

    for page_number in m:
        strana = input1.getPage(page_number)
        output.addPage(strana)
    
  4. 最后,使用with来包含文件操作。Python将自动处理文件的关闭,以免您忘记这样做。在

    with open (pdful, 'wb') as outputStream:
        output.write(outputStream)
    

相关问题 更多 >