Python converts a picture in a folder into a PDF

Source: Internet
Author: User

Import OS
Import string
From PIL import Image
From reportlab.lib.pagesizes import A4, landscape
From Reportlab.pdfgen import Canvas
Import Sys

def file_name (file_dir, suffix = ". jpg"):
L=[]
For root, dirs, files in Os.walk (File_dir):
For file in Files:
If Os.path.splitext (file) [1] = = suffix:
L.append (Os.path.join (root, file))
Return L

#f_pdf PDF file path, include filename
#filedir pic file path
#suffix pic file suffix examples:. jpg
def CONP DF (f_pdf, Filedir, suffix):
(w, h) = Landscape (A4)
C = Canvas. Canvas (f_pdf, pagesize = Landscape (A4))
FileList = file_name (filedir, suffix)

for F in fileList:
(Xsize, ysize) = Image.open (f). Size

Ratx = xsize/w
Raty = ysize/h
Ratxy = xsize/(1.0 * ysize)
If RATX > 1 :
Ratx = 0.99
If Raty > 1:
Raty = 0.99

Rat = Ratx

If Ratx < raty:
Rat = Raty
Widthx = w * Rat
Widthy = h * Rat
Widthx = widthy * Ratxy
Posx = (w-widthx)/2
If posx < 0:
Posx = 0
Posy = (h-widthy)/2
If posy < 0:
pos = 0

C.drawimage (F, Posx, Posy, Widthx, widthy)
C.showpage ()
C.sav E ()
print "Image to PDF success!"

if __name__ = = ' __main__ ':
If Len (sys.argv) = = 4:
Conpdf (Sys.argv[1], sys.argv[2], sys.argv[3])
Elif len (sys.argv) = = 3:
#default. jpg
Conpdf (Sys.argv[1], sys.argv[2])
Else
Conpdf ("C:\\users\\pzf\\test.pdf", "C:\\magn", ". jpg")

Python converts a picture in a folder into a PDF

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.