开源 企业版 高校版 私有云 模力方舟 AI 队友
代码拉取完成,页面将自动刷新
加入 Gitee
与超过 1400万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
已有帐号? 立即登录
文件
master
分支 (1)
master
master
分支 (1)
master
克隆/下载
克隆/下载
提示
下载代码请复制以下命令到终端执行
为确保你提交的代码身份被 Gitee 正确识别,请执行以下命令完成配置
初次使用 SSH 协议进行代码克隆、推送等操作时,需按下述提示完成 SSH 配置
1 生成 RSA 密钥
2 获取 RSA 公钥内容,并配置到 SSH公钥
在 Gitee 上使用 SVN,请访问 使用指南
使用 HTTPS 协议时,命令行会出现如下账号密码验证步骤。基于安全考虑,Gitee 建议 配置并使用私人令牌 替代登录密码进行克隆、推送等操作
Username for 'https://gitee.com': userName
Password for 'https://userName@gitee.com': # 私人令牌
master
分支 (1)
master
pdfTest.py 11.79 KB
一键复制 编辑 原始数据 按行查看 历史
linght 提交于 2025年07月16日 22:12 +08:00 . pdf生成测试代码.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235
import os
import platform
import subprocess
import time
from loguru import logger
from reportlab.lib import colors
from reportlab.lib.pagesizes import A4
from reportlab.lib.styles import ParagraphStyle
from reportlab.lib.styles import getSampleStyleSheet
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
from reportlab.platypus import Paragraph, Spacer
from reportlab.platypus import Table, TableStyle, SimpleDocTemplate
class PdfGenerator:
def __init__(self, outputPath="通讯设备出厂检验报告.pdf"):
self.outputPath = outputPath
self.styles = getSampleStyleSheet()
self.styleN = self.styles["Normal"]
self.story = []
self._registerFonts()
self.styleN.fontName = "SimSun"
self.styleN.alignment = 1 # 居中
self.styleLeft = ParagraphStyle(name="LeftAlign", parent=self.styleN, alignment=0) # 0=LEFT, 1=CENTER
def _registerFonts(self):
# Windows 字体路径,如非 Windows 环境请改为实际路径
pdfmetrics.registerFont(TTFont("SimSun", "C:/Windows/Fonts/simsun.ttc"))
pdfmetrics.registerFont(TTFont("ArialUnicodeMS", "C:/Windows/Fonts/arialuni.ttf")) # 示例路径,需自行准备字体文件
def _buildHeader(self):
styleTitle = ParagraphStyle(
name="SimSunTitle",
parent=self.styles["Title"],
fontName="SimSun",
fontSize=20,
leading=24,
alignment=1, # 居中
)
self.story.append(Paragraph("<b>操作台出厂检验报告</b>", styleTitle))
self.story.append(Spacer(1, 12))
def _buildResultParagraph(self, result: bool | None) -> Paragraph:
if result:
text = (
'<font face="ArialUnicodeMS" size="13">☑</font>'
'<font face="SimSun" size="11" color="green"><b>OK</b> </font>'
'<font face="ArialUnicodeMS" size="13">☐</font>'
'<font face="SimSun" size="11" color="red"><b>NG</b></font>'
)
elif result is False:
text = (
'<font face="ArialUnicodeMS" size="13">☐</font>'
'<font face="SimSun" size="11" color="green"><b>OK</b> </font>'
'<font face="ArialUnicodeMS" size="13">☑</font>'
'<font face="SimSun" size="11" color="red"><b>NG</b></font>'
)
else:
text = '<font face="SimSun">--</font>'
return Paragraph(text, self.styleN)
def _buildStaticResultText(self, result: bool | None) -> Paragraph:
checked, unchecked = "☑", "☐"
if result:
text = (
'<font face="SimSun"><b>结果判定</b> </font>'
f'<font face="ArialUnicodeMS" size="13">{checked}</font>'
'<font face="SimSun" color="green">合格 </font>'
f'<font face="ArialUnicodeMS" size="13">{unchecked}</font>'
'<font face="SimSun" color="red">不合格</font>'
)
else:
text = (
'<font face="SimSun"><b>结果判定</b> </font>'
f'<font face="ArialUnicodeMS" size="13">{unchecked}</font>'
'<font face="SimSun" color="green">合格 </font>'
f'<font face="ArialUnicodeMS" size="13">{checked}</font>'
'<font face="SimSun" color="red">不合格</font>'
)
return Paragraph(text, self.styleLeft)
def _buildTable(self, checkResults: dict[str, str]):
checkUserWidthSpace = "&nbsp" * 18 # 10个全角空格
checkUser = (
f'<font face="SimSun" ><b>检验员:{checkUserWidthSpace}</b></font>'
f'<font face="SimSun" >审核:{checkUserWidthSpace}</font>'
f'<font face="SimSun" >日期:{checkUserWidthSpace}</font>'
)
table_data = [
["序列号", Paragraph(checkResults.get("serialNum", self.styleLeft)), "", ""],
["检验名称", "测试项", "实测情况", "结果判定"],
["系统检验", "硬盘容量", "符合要求", self._buildResultParagraph(checkResults.get("HardDiskCapacity"))],
["", "软件版本", "符合要求", self._buildResultParagraph(checkResults.get("SoftwareVersion"))],
["", "硬件版本", "符合要求", self._buildResultParagraph(checkResults.get("HardwareVersion"))],
["喇叭检验", "喇叭播放", "符合要求", self._buildResultParagraph(checkResults.get("SpeakerPlay"))],
["", "喇叭静默", "符合要求", self._buildResultParagraph(checkResults.get("SpeakerMute"))],
["鹅颈检验", "鹅颈采集", "符合要求", self._buildResultParagraph(checkResults.get("GooseneckCapture"))],
["前面板PTT检验", "机身PTT", "符合要求", self._buildResultParagraph(checkResults.get("BodyPTT"))],
["", "机身扩展按钮", "符合要求", self._buildResultParagraph(checkResults.get("BodyExtButton"))],
["手咪检验", "手咪PTT", "符合要求", self._buildResultParagraph(checkResults.get("HandMicPTT"))],
["", "手咪采集", "符合要求", self._buildResultParagraph(checkResults.get("HandMicCapture"))],
["话筒检验", "话筒摘", "符合要求", self._buildResultParagraph(checkResults.get("MicPickup"))],
["", "话筒挂", "符合要求", self._buildResultParagraph(checkResults.get("MicHang"))],
["", "话筒I键", "符合要求", self._buildResultParagraph(checkResults.get("MicKeyI"))],
["", "话筒II键", "符合要求", self._buildResultParagraph(checkResults.get("MicKeyII"))],
["", "话筒播放", "符合要求", self._buildResultParagraph(checkResults.get("MicPlay"))],
["", "话筒采集", "符合要求", self._buildResultParagraph(checkResults.get("MicCapture"))],
["", "话筒静默", "符合要求", self._buildResultParagraph(checkResults.get("MicMute"))],
["触摸屏检验", "触摸屏按压", "符合要求", self._buildResultParagraph(checkResults.get("TouchScreenPress"))],
["综合信息", self._buildStaticResultText(checkResults.get("Result")), "", ""],
["", Paragraph(checkUser, self.styleLeft), "", ""],
]
rowCount = len(table_data)
table = Table(table_data, colWidths=[100, 200, 100, 100], rowHeights=[25] * rowCount)
table.setStyle(
TableStyle(
[
# 合并"系统检验"
("SPAN", (0, 2), (0, 4)),
("VALIGN", (0, 2), (0, 4), "MIDDLE"),
("SPAN", (1, 0), (3, 0)), # 序列号显示区域
# 合并"喇叭检验"
("SPAN", (0, 5), (0, 6)),
("VALIGN", (0, 5), (0, 6), "MIDDLE"),
# 合并"前面板PTT检验"
("SPAN", (0, 8), (0, 9)),
("VALIGN", (0, 8), (0, 9), "MIDDLE"),
# 合并"手咪检验"
("SPAN", (0, 10), (0, 11)),
("VALIGN", (0, 10), (0, 11), "MIDDLE"),
# 合并"话筒检验"多行首列
("SPAN", (0, 12), (0, 18)),
("VALIGN", (0, 12), (0, 18), "MIDDLE"), # 合并第13到19行第1列 # 垂直居中对齐 合并"综合信息"
("SPAN", (0, 20), (0, 21)),
("VALIGN", (0, 20), (0, 21), "MIDDLE"),
("SPAN", (1, 20), (3, 20)), # 结果判定
("SPAN", (1, 21), (3, 21)), # 检验员等
# 水平/垂直居中对齐
("VALIGN", (0, 0), (-1, -1), "MIDDLE"),
("ALIGN", (0, 0), (-1, -1), "CENTER"), # 所有单元格水平居中
# 综合信息 左对齐
("FONTNAME", (0, 0), (-1, -1), "SimSun"),
("GRID", (0, 0), (-1, -1), 0.5, colors.grey),
("BOTTOMPADDING", (3, 2), (3, 22), 8), # 第5列第7行下边距5pt 为了垂直居中显示
]
)
)
self.story.append(table)
self.story.append(Spacer(1, 12))
def _buildFooter(self):
# 创建带缩进的左对齐样式
styleWithIndent = ParagraphStyle(name="IndentedLeft", parent=self.styleLeft, leftIndent=-30) # 左缩进 20pt,可根据需要调整
styleWithIndent2 = ParagraphStyle(name="IndentedLeft", parent=self.styleLeft, leftIndent=-10) # 左缩进 20pt,可根据需要调整
self.story.append(Spacer(1, 90))
self.story.append(Paragraph("备注信息", styleWithIndent))
self.story.append(Paragraph("1、内单整机产品检验合格随机附带一份此报告。", styleWithIndent2))
self.story.append(Paragraph("2、检验"NG"时,必须在备注栏附带《不合格品处理表》文件编号。", styleWithIndent2))
self.story.append(Paragraph("3、本文件视为受控文件,请勿分享。", styleWithIndent2))
def generate(self, checkResults: dict[str, str]):
# doc = SimpleDocTemplate(self.outputPath, pagesize=A4)
doc = SimpleDocTemplate(self.outputPath, pagesize=A4, topMargin=36, bottomMargin=36, leftMargin=72, rightMargin=72)
self._buildHeader()
self._buildTable(checkResults)
self._buildFooter()
try:
self._kill_process_by_file(self.outputPath)
time.sleep(0.5)
doc.build(self.story)
self._openPdf(self.outputPath)
logger.info(f"✅ PDF 生成成功:{self.outputPath}")
except PermissionError:
logger.error("⚠️ PDF 写入失败:文件可能正在打开,请先关闭再重试")
def _openPdf(self, sPdfPath):
if platform.system() == "Windows":
os.startfile(sPdfPath)
elif platform.system() == "Darwin": # macOS
os.system(f"open {sPdfPath}")
else:
os.system(f"xdg-open {sPdfPath}")
@staticmethod
def _kill_process_by_file(filename):
"""
使用 handle.exe 查找并强制关闭打开 filename 的进程
"""
handle_path = r"C:\tools\handle\handle.exe" # 你自己的 handle.exe 路径
if not os.path.exists(handle_path):
logger.error(f"handle.exe 不存在,请确认路径:{handle_path}")
return
try:
result = subprocess.run([handle_path, filename], capture_output=True, text=True, timeout=5)
except subprocess.TimeoutExpired:
logger.error("handle.exe 执行超时")
return
except Exception as e:
logger.exception(f"运行 handle.exe 时发生异常:{e}")
return
if result.returncode != 0:
logger.warning("handle.exe 执行失败")
logger.warning(result.stderr.strip())
return
output = result.stdout
pids = set()
for line in output.splitlines():
if "pid:" in line:
parts = line.split()
for i, part in enumerate(parts):
if part == "pid:" and i + 1 < len(parts):
pid = parts[i + 1]
pids.add(pid)
if not pids:
logger.info("没有进程打开该文件")
return
for pid in pids:
logger.info(f"尝试强制终止进程 PID: {pid}")
try:
subprocess.run(["taskkill", "/PID", pid, "/F"], check=True)
logger.success(f"已终止 PID: {pid}")
except subprocess.CalledProcessError as e:
logger.warning(f"终止 PID {pid} 失败:{e}")
Loading...
举报
举报成功
我们将于2个工作日内通过站内信反馈结果给你!
请认真填写举报原因,尽可能描述详细。
请选择举报类型
取消
发送
误判申诉

此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。

如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。

取消
提交

简介

pythonCode
暂无标签
GPL-3.0
使用 GPL-3.0 开源许可协议
取消

发行版

暂无发行版

贡献者

全部

近期动态

不能加载更多了
编辑仓库简介
简介内容
主页
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Python
1
https://gitee.com/linght/python-code.git
git@gitee.com:linght/python-code.git
linght
python-code
pythonCode
master
点此查找更多帮助

搜索帮助

评论
仓库举报
回到顶部
登录提示
该操作需登录 Gitee 帐号,请先登录后再操作。
立即登录
没有帐号,去注册

AltStyle によって変換されたページ (->オリジナル) /