pythonproject/creare_pdf.py
2024-06-25 14:15:07 +08:00

140 lines
4.5 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import os
import tempfile
import cv2
from sqlalchemy import create_engine, Table, Column, Integer, String, MetaData, DateTime,TIMESTAMP
from fpdf import FPDF
import io
import hashlib
import requests
import secrets
from PIL import Image
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import demo
# from demo import perspective_transform
def init_sqlserver():
# 创建连接引擎
engine = create_engine('postgresql://postgres:!1q2w3E*@8.134.85.73:5432/postgres')
# 连接数据库
connection = engine.connect()
print("Connection to PostgreSQL DB successful")
# 声明表结构
metadata = MetaData()
qrcode_data = Table('qrcode_data', metadata,
Column('key', String),
Column('circles', String),
# createdate 时间类型
Column('createdate', TIMESTAMP)
)
return qrcode_data
def get_images(key, secret, api, count=1):
images = []
urls = []
for i in range(count):
random_number = ''.join([str(secrets.randbelow(9) + 1) for _ in range(16)])
parm = f"api_key={key}&cliD={random_number}&cliT=D1&return_file={secret}"
params = {
"api_key": key,
"cliT": "D2",
"cliD": random_number,
"return_file": ""
}
# 排序
sorted_params = sorted(params.items())
concatenated_params = '&'.join(f"{key}={value}" for key, value in sorted_params)
data = concatenated_params + secret
hash_object = hashlib.md5(data.encode())
md5_hash = hash_object.hexdigest()
url = f"{api}?api_key={key}&cliT=D2&cliD={random_number}&sign={md5_hash}&return_file="
urls.append(url)
for url in urls:
response = requests.get(url)
images.append(response.content)
return images
def ndarray_to_binary(image_array):
# 将numpy数组转换为PIL图像对象
img = Image.fromarray(image_array)
# 创建一个字节流对象
byte_arr = io.BytesIO()
# 将图像保存到字节流中格式可以自选如PNG
img.save(byte_arr, format='PNG')
# 获取二进制数据
binary_data = byte_arr.getvalue()
return binary_data
def create_pdf(images, fileName):
# 创建 PDF 类实例
pdf = FPDF('P', 'mm', 'A4')
# 添加一页
pdf.add_page()
# 设置图片的尺寸
image_width = 15 # 图片宽度 30 mm
image_height = 15 # 图片高度 30 mm
margin = 20 # 页边距 10 mm
images_per_row = 5
# 当前行的开始位置
x_offset = margin
y_offset = margin
# 自定义临时文件路径
custom_temp_dir = './temp'
os.makedirs(custom_temp_dir, exist_ok=True)
# 循环处理图片二进制数据
for i, binary_image in enumerate(images):
if i % images_per_row == 0 and i != 0:
# 开始新的一行
x_offset = margin
y_offset += image_height + margin
# # 将binary_image保存为本地文件
# with open(f"{i}.png", "wb") as f:
# f.write(binary_image)
# 创建一个临时文件来保存图像
with tempfile.NamedTemporaryFile(delete=False, suffix=".TIFF", dir=custom_temp_dir) as tmpfile:
tmpfile.write(binary_image)
tmp_filename = tmpfile.name
print(tmp_filename)
if os.access(tmp_filename, os.R_OK):
print("File is readable.")
else:
print("File is not readable.")
img_path = demo.exec_image_result(tmp_filename)
# 将img_path返回来 tiff 格式转换 png 格式
img = Image.open(img_path)
png_path = img_path.replace('.tiff', '.png')
img.save(png_path, format='PNG')
# 添加图片
pdf.image(png_path, x=x_offset, y=y_offset, w=image_width, h=image_height)
# 更新x坐标
x_offset += image_width + margin
# 删除文件
os.remove(tmp_filename)
# 输出 PDF
pdf.output(fileName)
key = "CL8ca5c629b676d724"
secret = "7a92463b491be3d0aa9704a8980e46ad"
api = "https://open-api.cli.im/cli-open-platform-service/v1/labelStyle/createWithKey"
# 初始化数据库
# qrcode_entity = init_sqlserver()
images = get_images(key, secret, api, count=1)
create_pdf(images, "qr_v2.pdf")
# for i in range(10):
# # 生成16位随机数字
# random_number = ''.join([str(secrets.randbelow(10)) for _ in range(16)])
# # 将随机数字每两位分为一组
# # groups = [random_number[i:i + 2] for i in range(0, len(random_number), 2)]
# # print(groups)