import osimport platformimport subprocessimport timefrom loguru import loggerfrom reportlab.lib import colorsfrom reportlab.lib.pagesizes import A4from reportlab.lib.styles import ParagraphStylefrom reportlab.lib.styles import getSampleStyleSheetfrom reportlab.pdfbase import pdfmetricsfrom reportlab.pdfbase.ttfonts import TTFontfrom reportlab.platypus import Paragraph, Spacerfrom reportlab.platypus import Table, TableStyle, SimpleDocTemplateclass PdfGenerator:def __init__(self, outputPath="通讯设备出厂检验报告.pdf"):self.outputPath = outputPathself.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=CENTERdef _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 = " " * 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": # macOSos.system(f"open {sPdfPath}")else:os.system(f"xdg-open {sPdfPath}")@staticmethoddef _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}")returntry:result = subprocess.run([handle_path, filename], capture_output=True, text=True, timeout=5)except subprocess.TimeoutExpired:logger.error("handle.exe 执行超时")returnexcept Exception as e:logger.exception(f"运行 handle.exe 时发生异常:{e}")returnif result.returncode != 0:logger.warning("handle.exe 执行失败")logger.warning(result.stderr.strip())returnoutput = result.stdoutpids = 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("没有进程打开该文件")returnfor 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}")
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。