当前位置: 首页 > news >正文

termux下python编程尝试,转换全能扫描王生成pdf文件

#创造灵感# 因为经常使用全能扫描王,这次没有电脑要传一个扫描的文件给同事,发现只能发有二维码水印的(免费版),于是,我想起最近使用termux,在手机安装一个Ubuntu系统,可以用python编程,直接用vnc进入ubuntu系统,进行转换。这个是以前在windows系统写的程序:https://blog.csdn.net/2401_82434226/article/details/143474940

我要在Ubuntu系统,编写同样的程序。

import tkinter as tk
from tkinter import ttk
import re
try:from tkinterdnd2 import DND_FILES, TkinterDnD
except ImportError:# 回退到标准 tkinterTkinterDnD = tk.TkDND_FILES = None
from PIL import Image
import os
import glob
import time
import zipfile
import random
import statdef create_tmp_folder():tmp_path = "/root/tmp"try:# 检查文件夹是否存在if not os.path.exists(tmp_path):# 创建文件夹(包括父目录)os.makedirs(tmp_path, exist_ok=True)print(f"✅ 文件夹已创建: {tmp_path}")else:print(f"📁 文件夹已存在: {tmp_path}")# 设置权限为 777 (所有人都可读、写、执行)os.chmod(tmp_path, stat.S_IRWXU | stat.S_IRWXG | stat.S_IRWXO)print(f"🔓 权限已设置为 777 (所有人都可读写)")# 验证权限current_mode = os.stat(tmp_path).st_modeprint(f"📊 当前权限: {oct(current_mode)[-3:]}")except PermissionError:print("❌ 权限不足,请使用 sudo 运行此脚本")except Exception as e:print(f"❌ 发生错误: {e}")# 执行
create_tmp_folder()
# 防止字符串乱码
os.environ['NLS_LANG'] = 'SIMPLIFIED CHINESE_CHINA.UTF8'
def unzip_file(zip_path, extract_to):with zipfile.ZipFile(zip_path, 'r') as zip_ref:zip_ref.extractall(extract_to)# 转化图片为统一宽度
def resize_images(input_dir, output_dir, width, height):for filename in glob.glob(os.path.join(input_dir, '*.jpg')):  # 假设处理的是jpg图片,你可以根据需要修改文件扩展名image = Image.open(filename)kgb = image.width / image.height # 图片的宽高比bzkgb = width / height # 要转化图片的宽高比paste_w = 0 #粘贴图片在画布上的位置,以左上角为原点 初设x为0paste_h = 0 #初设y为0if kgb <= bzkgb:resized_image = image.resize((int(image.width * (height / image.height)), height)) # 保持宽高比,根据高度调整宽度paste_w = int((width - int(image.width * (height / image.height))) / 2)else:resized_image = image.resize((width, int(image.height * (width / image.width))))  # 保持宽高比,根据宽度调整高度paste_h = int((height - int(image.height * (width / image.width))) / 2)canvasnew = Image.new('RGB', (width, height), 'white') #创建一块画布canvasnew.paste(resized_image, (paste_w, paste_h)) # 居中粘贴图片output_path = os.path.join(output_dir, os.path.basename(filename))image.close()canvasnew.save(output_path)  # 保存调整尺寸后的图片canvasnew.close()# 转换为pdf
def pic2pdf(img_path, pdf_path):file_list = os.listdir(img_path)sources = []jpg_files = []replacestr = ''for file in file_list:if 'png' in file or 'jpg' in file:jpg_files.append(file)if replacestr == '':replacestr = os.path.basename(file).split('_')[0] + '_'jpg_files.sort(key=lambda x: int(x.replace(replacestr,'').split('.')[0]))output = Image.open(img_path + jpg_files[0])jpg_files.pop(0)for file in jpg_files:jpg_file = Image.open(img_path + file)if jpg_file.mode == "RGB":jpg_file = jpg_file.convert("RGB")sources.append(jpg_file)output.save(pdf_path, "pdf", save_all=True, append_images=sources)def get_random_image_size(folder_path):"""随机获取一张图片的尺寸"""image_extensions = {'.jpg', '.jpeg', '.png', '.gif', '.bmp', '.tiff', '.webp'}# 先收集所有图片文件image_files = []for filename in os.listdir(folder_path):file_path = os.path.join(folder_path, filename)if os.path.isfile(file_path):file_ext = os.path.splitext(filename)[1].lower()if file_ext in image_extensions:image_files.append(filename)if not image_files:return None, None# 随机选择一张图片random_image = random.choice(image_files)file_path = os.path.join(folder_path, random_image)try:with Image.open(file_path) as img:width, height = img.sizereturn width, heightexcept Exception as e:print(f"无法打开图片 {random_image}: {e}")return None, None
import shutildef delete_folder_safe(folder_path):"""安全删除文件夹"""try:# 检查文件夹是否存在if os.path.exists(folder_path) and os.path.isdir(folder_path):print(f"🗑️  准备删除文件夹: {folder_path}")# 使用 shutil.rmtree 递归删除文件夹及其所有内容shutil.rmtree(folder_path)print(f"✅ 文件夹删除成功: {folder_path}")else:print(f"❌ 文件夹不存在或不是目录: {folder_path}")except PermissionError:print(f"❌ 权限不足,无法删除: {folder_path}")except Exception as e:print(f"❌ 删除失败: {e}")def dec_to_36(num):base = [str(x) for x in range(10)] + [chr(x) for x in range(ord('A'),ord("A")+26)]# 前者把 0 ~ 9 转换成字符串存进列表 base 里,后者把 A ~ Z 存进列表l = []if num<0:return "-"+dec_to_36(abs(num))while True:num,rem = divmod(num,36) # 求商 和 留余数l.append(base[rem])if num == 0:return "".join(l[::-1])def nowtime_to_str():#将当前时间戳转化为36进制,约6位字符,减少文件名长度unix_timestamp = int(time.time())return(dec_to_36(unix_timestamp))def turn_file(file0):fileurl = ''fileurl = file0if fileurl != '' and os.path.splitext(fileurl)[1] == '.zip':zippath = fileurlzip_file_path = zippath  # 替换为你的zip文件路径filename0 = os.path.basename(fileurl).replace('.zip','') + nowtime_to_str()extract_to_path = f'/root/tmp/{filename0}/'  # 指定解压后文件存放的目录unzip_file(zip_file_path, extract_to_path)# 待转换图像路径img_path = f'/root/tmp/{filename0}/'# 转换后的pdfpdf_path = fileurl.replace('.zip','.pdf')# 使用示例:将"input_directory"目录下的所有PNG图片调整为宽度为200像素,并保存到"output_directory"目录中width0,height0 = get_random_image_size(img_path)resize_images(img_path, img_path, width0,height0) # 打印A4纸210*297 按这个比例图片是1980*2800pic2pdf(img_path=img_path, pdf_path=pdf_path)print('生成PDF文件位置:' + pdf_path)delete_folder_safe(f'/root/tmp/{filename0}')class DragDropApp:def __init__(self, root):self.root = rootself.root.title("支持文件拖拽的 Tkinter 应用 - 修复空格问题")self.root.geometry("500x300")# 创建文本区域self.text = tk.Text(root, wrap=tk.WORD)self.text.pack(fill=tk.BOTH, expand=True, padx=10, pady=10)# 如果支持拖拽,注册拖拽目标if DND_FILES is not None:self.text.drop_target_register(DND_FILES)self.text.dnd_bind('<<Drop>>', self.on_file_drop)self.text.insert(tk.END, "将文件拖拽到此区域...\n")self.text.insert(tk.END, "支持包含空格的文件路径\n")def parse_dropped_files(self, data):"""解析拖拽的文件路径,正确处理包含空格的情况"""files = []# 方法1: 使用花括号匹配# tkinterdnd2 用花括号包裹包含空格的文件路径brace_pattern = r'\{[^}]+\}'brace_matches = re.findall(brace_pattern, data)for match in brace_matches:# 移除花括号file_path = match[1:-1]files.append(file_path)# 从原始数据中移除已匹配的部分data = data.replace(match, '', 1)# 方法2: 处理剩余的不带花括号的文件路径remaining_files = [f.strip() for f in data.split() if f.strip()]files.extend(remaining_files)return filesdef on_file_drop(self, event):files = self.parse_dropped_files(event.data)self.text.insert(tk.END, f"\n接收到 {len(files)} 个文件:\n")for i, file_path in enumerate(files, 1):self.text.insert(tk.END, f"  {i}. {file_path}\n")print(file_path)turn_file(file_path)if __name__ == "__main__":root = TkinterDnD.Tk() if TkinterDnD != tk.Tk else tk.Tk()app = DragDropApp(root)root.mainloop()

程序试运行后,可以

pyinstaller --onefile --windowed your_script.py

进行打包,后添加到桌面的快捷方式。

拖放zip文件后就能生成无水印的PDF文件在手机上。

http://www.dtcms.com/a/536897.html

相关文章:

  • 做用户名和密码网站页面设计最简单的企业网站
  • wordpress设置数字形链接报404长沙做网站seo
  • 山区农产品售卖系统
  • 做微信的网站有哪些永久免费企业建站官网大全
  • 如何在linux抓包tcpdumpwireshark如何使用
  • FFmpeg 基本数据结构 AVCodec分析
  • QtQuick3D入门(2):材质 material
  • 怎么做网上卖菜网站酒店管理专业建设规划
  • 20251027 Prism.Unity依赖注入Demo
  • MES系统:论工单计划在智能制造中的核心串联作用​
  • 【C语言】程序控制结构
  • 厦门做网站哪家公司好非交互式网站可以做商城吗
  • OpenSSL3.5.2实现SM3数据摘要生成
  • 现代机器人学习入门:一份来自Hugging Face与牛津大学的综合教程开源SOTA资源库
  • 2D SLAM 主流算法推荐汇总和扫地机应用场景
  • 运维实战:SSL 证书故障避坑指南(精简版)
  • google网站管理员中心wordpress 字号 插件
  • 南通智能模板建站群晖wordpress安装
  • 网站建设时图片和文字北京网站定制报价
  • YOLOv5核心代码深度解析
  • SELinux 安全机制
  • 爱奇艺的网站是用什么做的网站tdk建设
  • 网站名是域名吗浙江华企 做网站怎么样
  • 基于python的化妆品推荐系统
  • 深圳网站的公司注册公司流程及费用查询
  • C++仿Muduo库Server服务器模块实现 基于Reactor模式的高性
  • 对IDC(数据中心)运维了解
  • Hyperopt 强大的分布式参数优化框架全解析
  • 网站都必须要备案吗建设一个视频网站首页
  • 前端页面连接后端fastapi实现模型本地部署和open ai接入