Python论坛  - 讨论区

标题:[python-chinese] Jpg 转换到 PDF 的程序

2007年02月16日 星期五 11:39

Ben Luo benluo在gmail.com
星期五 二月 16 11:39:14 HKT 2007

ÒòΪÐèÒª°ÑɨÃèµÄJPGÎļþ£¨1ÕÅ»ò¶àÕÅ£©×ª»»³ÉPDFÎļþ¡£ÎÒдÁËÒÔϳÌÐò¡£¾õµÃ´úÂëÌ«³ó£¬ÇëͬÈÊÖ¸Õý¡£Ä¿Ç°ÊÇ¿ÉÒÔ¹¤×÷µÄ¡£
from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import A4
from PIL import Image
import sys
import os
import glob

def resizeKeepRatio(image, cSize, method=3):
    """
    Resize the image, after converting, the ratio of the image was not
changed.

    """
    if image.size[0] <= cSize[0] and image.size[1] <= cSize[1]:
        return
    cr = float(cSize[0])/float(cSize[1])
    pr = float(image.size[0])/float(image.size[1])
    if cr <= pr:
        iSize = (cSize[0], int(cSize[0]/pr))
        return image.resize(iSize)
    else:
        iSize = (int(cSize[1]*pr), cSize[1])
        return image.resize(iSize)

def picconvertpdf(picList, pdfName):
    myCanvas = canvas.Canvas(pdfName, pagesize=A4)
    w, h = A4 #keep for later
    pageCanvas = (int(w)-20,int(h)-20) #ÁôÏÂÅÔ°×£¬ºÃ¿´Ò»µã
    for pic in picList:
        image = Image.open(pic)
        p1 = resizeKeepRatio(image, pageCanvas)
        tmppic = "c:\\tmp\\" + os.path.split(pic)[1]
#ÕâÀïÓÐûÓÐʲô·½·¨¿ÉÒԸĽøµÄ¡£ÎÒ¿´drawImage Ö»½ÓÊÕÎļþ£¬²»½ÓÊÕ Image ¶ÔÏó
        p1.save(tmppic)
        myCanvas.drawImage(tmppic, 10,10)
        myCanvas.showPage()
        os.remove(tmppic)
    myCanvas.save()

if __name__ == '__main__':
# argv[1] is pdf file name. argv[2:] are pictures list µÚÒ»¸ö²ÎÊýÊÇPDF
ÎļþÃû£¬ÒÔºóµÄ²ÎÊýÊÇJPGÎļþ£¬Ó¦¸ÃÓÃtry ÅжϲÎÊýµÄ£¬×Ô¼ºµÄ³ÌÐò£¬ËùÒÔ͵ÀÁÁË
    sys.argv[2:] = [item for arg in sys.argv[2:] for item in glob.glob(arg)]
    picconvertpdf(sys.argv[2:],sys.argv[1])

Çë¸÷λ¿´ÎÒÖÐÎÄ×¢Ê͵ĵط½£¬Çë¸ø°ïÖú¡£Ð»Ð»£¡
-------------- 下一部分 --------------
Ò»¸öHTML¸½¼þ±»ÒƳý...
URL: http://python.cn/pipermail/python-chinese/attachments/20070216/daaf063b/attachment.html 

[导入自Mailman归档:http://www.zeuux.org/pipermail/zeuux-python]

如下红色区域有误,请重新填写。

    你的回复:

    请 登录 后回复。还没有在Zeuux哲思注册吗?现在 注册 !

    Zeuux © 2025

    京ICP备05028076号