0

I'm trying to write a simple script to merge two PDFs but have run into an issue when trying to save the output to disk. My code is

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

The problem is that I get an error of

UserWarning: File to write to is not in binary mode. It may not be written to correctly. [pdf.py:453] Traceback (most recent call last): File "Combine2Pdfs.py", line 44, in output.write(output_name) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/pytho‌​n3.5/site-packages/P‌​yPDF2/pdf.py", line 487, in write stream.write(self.header + b("\n")) TypeError: write() argument must be str, not bytes

Where have I gone wrong?

pgcudahy
  • 1,542
  • 13
  • 36

2 Answers2

2

I got it by adding mode = 'wb' to tk.filedialog.asksaveasfile. Now it's

output_name = tk.filedialog.asksaveasfile(
        mode = 'wb',
        defaultextension='pdf')
output.write(output_name)
pgcudahy
  • 1,542
  • 13
  • 36
1

Try to use tk.filedialog.asksaveasfilename instead of tk.filedialog.asksaveasfile. You just want the filename, not the file handler itself.

###Prompt the user for the file save###
output_name = tk.filedialog.asksaveasfilename(defaultextension='pdf')
Marvo
  • 523
  • 7
  • 16
  • With that I got the error "AttributeError: 'str' object has no attribute 'write'" So then I added `with open("output_name", 'wb') as save: output.write(save)` which doesn't give any errors but doesn't write the pdf either. – pgcudahy Dec 05 '16 at 06:44