Project 1082

by Sarah E


""" This program will add bookmarks to the Code in Place Assignment3 HO PDF """ from PyPDF2 import PdfFileWriter, PdfFileReader #import the pdf libraries to manipulate pdf document def write_pdf(path): output_file = PdfFileWriter() #file we will rewrite to adding bookmarks input_file = PdfFileReader(open(path, 'rb')) #source file for i in range(4): #4 pages in this specific file, could also use the numPage operator from the PDF2 library output_file.addPage(input_file.getPage(i)) #insert page name_bookmarks(output_file) #names bookmarks of all 4 pages passing the output file we just created as a parameter outputStream = open('result.pdf', 'wb') #create result pdf output_file.write(outputStream) #writing to result pdf file outputStream.close() #closing result with open('result.pdf', 'rb') as f: #display pagenumbers and bookmark metadata to terminal pdf = PdfFileReader(f) bookmarks = pdf.getOutlines() #gets metadata of bookmarks such as title, page, etc. for b in bookmarks: print(str(pdf.getDestinationPageNumber(b) + 1) + '| ' + str(b)) # lists pages and bookmark info to terminal def name_bookmarks(output_file): output_file.addBookmark('Image Filter', 0, parent=None) # add bookmark output_file.addBookmark('Forest Flames', 1, parent=None) # add Bookmark output_file.addBookmark('Reflection', 2, parent=None) # add bookmark output_file.addBookmark('Warhol', 3, parent=None) # add bookmark if __name__ == '__main__': path = 'Assignment3 HO.pdf' write_pdf(path)