imgToPdf.py
# -*- coding: utf-8 -*-
import datetime
import shutil
import time
import os
from urllib.request import urlretrieve
from qiniu import Auth, put_file
from PIL import Image
# 通过地址下载图片到指定文件夹
os.makedirs('./img/', exist_ok=True)
IMAGE_URL = '线上图片地址'
urlretrieve(IMAGE_URL, './img/img1.png') # 对下载的图片命名
t = time.time()
time_ = str(t)[0:10]
#生成PDF文件的名称
pdf_name = time_
if ".pdf" in pdf_name:
pdf_name = pdf_name
else:
pdf_name = "{}.pdf".format(pdf_name)
#遍历图片文件夹
file_list = os.listdir('./img')
print(file_list)
pic_name = []
im_list = []
for x in file_list:
if "jpg" in x or 'png' in x or 'jpeg' in x:
pic_name.append(x)
pic_name.sort()
new_pic = []
for x in pic_name:
if "jpg" in x:
new_pic.append(x)
for x in pic_name:
if "png" in x:
new_pic.append(x)
for x in pic_name:
if "jpeg" in x:
new_pic.append(x)
print("hec", new_pic)
im1 = Image.open('./img/{}'.format(new_pic[0]))
new_pic.pop(0)
for i in new_pic:
img = Image.open('./img/{}'.format(i))
if img.mode == "RGBA":
img = img.convert('RGB')
im_list.append(img)
else:
im_list.append(img)
im1.save("./pdf/{}".format(pdf_name), "PDF", resolution=100.0, save_all=True, append_images=im_list)
print("输出文件名称:", pdf_name)
# 需要填写你的 Access Key 和 Secret Key
AK = ''
SK = ''
# 要上传的文件夹绝对路径
dir = './pdf/{}'.format(pdf_name)
# 要上传的空间
bucket_name = ' '
# 构建鉴权对象
q = Auth(AK, SK)
# 生成上传 Token,可以指定过期时间等
token = q.upload_token(bucket_name)
fpath, fname = os.path.split(dir)
patharr = fpath.split('\\')
if len(patharr) >= 2:
#上传后的路径
key = '/'.join(patharr[2:]) + 'printer' + '/' + 'files' + '/' + fname
else:
#上传后的路径
key = 'printer' + '/' + 'files' + '/' + fname
print(key)
ret, info = put_file(token, key, dir)
print(ret)
# 上传完成后删除本地存储文件,防止服务器瘫痪
delDir = "./img"
delList = list(os.listdir(delDir))
for f in delList:
filePath = os.path.join(delDir, f)
if os.path.isfile(filePath):
os.remove(filePath)
print(filePath + " was removed!")
elif os.path.isdir(filePath):
shutil.rmtree(filePath, True)
print("Directory: " + filePath + " was removed!")
delDir = "./pdf"
delList = list(os.listdir(delDir))
for f in delList:
filePath = os.path.join(delDir, f)
if os.path.isfile(filePath):
os.remove(filePath)
print(filePath + " was removed!")
elif os.path.isdir(filePath):
shutil.rmtree(filePath, True)
print("Directory: " + filePath + " was removed!")