1. 程式人生 > >Python批量將多張圖片拼接為PDF

Python批量將多張圖片拼接為PDF

參考部落格:http://ilovin.me/2017-04-18/stitch-img-to-pdf/   算是技術雜談類的吧......

最近碰到一個問題,想要把一個資料夾下的圖片拼接起來生成一個PDF檔案,並且該PDF檔案每頁都具有相同的A4大小。其實生成PDF這件事有許多方法可以辦到,最簡單可以用word或者acrobat,然而通過這些軟體來生成PDF檔案有些問題無法避免,一是樣式無法自定義,二是不太好把它做成一個模組嵌入到其他需要使用的地方。於是就想能否自己來寫,好在Python輪子多,簡單搜尋了一下,用ReportLab似乎可以達到自己的要求。

實現方法

程式碼實現起來倒是不復雜,但是有一點需要注意,那就是用PIL開啟一個圖片的時候,當它是JPEG格式的時候,我發現它總是旋轉過的,因此我們需要讀取一下該圖片的exif資訊,將它轉過來。

def rotate_img_to_proper(image): try: if hasattr(image, '_getexif'): # only present in JPEGs for orientation in PIL.ExifTags.TAGS.keys(): if PIL.ExifTags.TAGS[orientation] == 'Orientation': break e = image._getexif() # returns None if no EXIF data
if e is not None: #log.info('EXIF data found: %r', e) exif = dict(e.items()) orientation = exif[orientation] # print('found, ',orientation) if orientation == 3: image = image.transpose(Image.ROTATE_180) elif
orientation == 6: image = image.transpose(Image.ROTATE_270) elif orientation == 8: image = image.rotate(90,expand=True) except: pass return image

什麼是影象 exif 資訊?掃盲:

基本上, Exif檔案格式與JPEG 檔案格式相同. Exif按照JPEG的規格在JPEG中插入一些 影象/數字相機 的資訊資料以及縮圖像. 於是你能通過與JPEG相容的網際網路瀏覽器/圖片瀏覽器/影象處理等一些軟體 來檢視Exif格式的影象檔案. 就跟瀏覽通常的JPEG影象檔案一樣.

隨後我們就可以將圖片保持長寬比地resize到A4頁面中

# new a DocimgDoc = canvas.Canvas(output_file_name)#pagesize=letterimgDoc.setPageSize(A4)document_width,document_height = A4# fill each page with a imageimage_file = PIL.Image.open(image)image_file = rotate_img_to_proper(image_file)image_width,image_height = image_file.sizeif not(image_width>0 and image_height>0): raise Exceptionimage_aspect = image_height/float(image_width)#Determins the demensions of the image in the overviewprint_width = document_widthprint_height = document_width*image_aspectimgDoc.drawImage(ImageReader(image_file),document_width-print_width, document_height-print_height,width=print_width, height=print_height,preserveAspectRatio=True)#inform the reportlab we want a new pageimgDoc.showPage()imgDoc.save()

原博的github地址:github