【问题标题】:Writing pdf with pypdf2 gives error用 pypdf2 编写 pdf 会出错
【发布时间】:2017-04-17 03:36:31
【问题描述】:

我正在尝试编写一个简单的脚本来合并两个 PDF,但在尝试将输出保存到磁盘时遇到了问题。我的代码是

from PyPDF2 import PdfFileWriter, PdfFileReader
import tkinter as tk
from tkinter import filedialog    

### Prompt the user for the 2 files to use via GUI ###
root = tk.Tk()
root.update()
file_path1 = tk.filedialog.askopenfilename(
            filetypes=[("PDF files", "*.pdf")],
            )

file_path2 = tk.filedialog.askopenfilename(
            filetypes=[("PDF files", "*.pdf")],
            )

###Function to combine PDFs###
output = PdfFileWriter()

def append_pdf_2_output(file_handler):
    for page in range(file_handler.numPages):
        output.addPage(file_handler.getPage(page))

#Actually combine the 2 PDFs###
append_pdf_2_output(PdfFileReader(open(file_path1, "rb")))
append_pdf_2_output(PdfFileReader(open(file_path2, "rb")))

###Prompt the user for the file save###
output_name = tk.filedialog.asksaveasfile(
            defaultextension='pdf')

###Write the output to disk###
output.write(output_name)
output.close

问题是我得到一个错误

用户警告:要写入的文件不是二进制模式。它可能没有正确写入。 [pdf.py:453] Traceback(最近一次调用最后一次):文件“Combine2Pdfs.py”,第 44 行,在 output.write(output_name) 文件“/Library/Frameworks/Python.framework/Versions/3.5/lib/pytho”中​n3.5/site-packages/P‌​yPDF2/pdf.py",第 487 行,写入 stream.write(self.header + b("\n")) TypeError: write( ) 参数必须是 str,而不是字节

我哪里出错了?

【问题讨论】:

  • 你能发布完整的堆栈跟踪,而不仅仅是消息吗?
  • 请不要在评论中发布堆栈跟踪。您的问题有一个“编辑”链接,可让您编辑问题。

标签: python-3.x pdf pypdf2


【解决方案1】:

我通过在 tk.filedialog.asksaveasfile 中添加 mode = 'wb' 得到它。现在是

output_name = tk.filedialog.asksaveasfile(
        mode = 'wb',
        defaultextension='pdf')
output.write(output_name)

【讨论】:

    【解决方案2】:

    尝试使用tk.filedialog.asksaveasfilename 而不是tk.filedialog.asksaveasfile。您只需要文件名,而不是文件处理程序本身。

    ###Prompt the user for the file save###
    output_name = tk.filedialog.asksaveasfilename(defaultextension='pdf')
    

    【讨论】:

    • 这样我得到了错误“AttributeError:'str'对象没有属性'write'”所以我添加了with open("output_name", 'wb') as save: output.write(save),它没有给出任何错误但也没有写入pdf .
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-04
    • 1970-01-01
    • 1970-01-01
    • 2018-02-09
    • 2021-04-14
    相关资源
    最近更新 更多