printer.py 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735
  1. """
  2. 打印功能模块
  3. 使用PyQt5的QPrinter实现打印功能
  4. """
  5. from PyQt5.QtPrintSupport import QPrinter, QPrintDialog, QPrintPreviewDialog
  6. from PyQt5.QtWidgets import QApplication
  7. from PyQt5.QtGui import QPainter, QFont, QFontMetrics, QPen
  8. from PyQt5.QtCore import Qt, QRect, QSizeF, QSize
  9. from typing import Dict
  10. import platform
  11. class Printer:
  12. """打印类"""
  13. def __init__(self):
  14. # 纸张尺寸(单张地磅单)- 根据打印机可打印宽度设置为70mm
  15. self.page_width_mm = 70 # 打印机可打印宽度70mm
  16. self.page_height_mm = 150 # 150mm(单张地磅单)
  17. self.slip_height_mm = 150 # 每张地磅单的高度150mm
  18. # 边距(mm)- 左右上下都设为0
  19. self.margin_left_mm = 0
  20. self.margin_right_mm = 0
  21. self.margin_top_mm = 0
  22. self.margin_bottom_mm = 20
  23. # 内容向左偏移(mm)- 用于抵消打印机物理边距,负值向左移
  24. # 纸张宽度改为76mm后,暂时不需要额外偏移
  25. self.content_offset_x_mm = 0
  26. # 计算可用尺寸(基于单张地磅单的高度150mm)
  27. available_height_mm = self.slip_height_mm - self.margin_top_mm - self.margin_bottom_mm
  28. available_width_mm = self.page_width_mm - self.margin_left_mm - self.margin_right_mm
  29. # 12行数据行 + 1行标题行 = 13行
  30. # 标题行占用10mm,剩余134mm给12行数据行
  31. # 每行高度 = 134mm / 12 ≈ 11.17mm
  32. num_data_rows = 12 # 12行数据行
  33. title_height_mm = 10.0 # 标题行高度
  34. data_rows_height_mm = available_height_mm - title_height_mm # 134mm
  35. self.line_height_mm = data_rows_height_mm / num_data_rows # 约11.17mm每行
  36. self.title_line_height_mm = title_height_mm # 10mm标题行
  37. # 4列布局:左侧label + 左侧内容 + 右侧label + 右侧内容
  38. # 每列约 = 74mm / 4 ≈ 18.5mm
  39. # 但实际分配:左侧部分和右侧部分各占50%
  40. # 左侧:label(约25%) + 内容(约25%)
  41. # 右侧:label(约25%) + 内容(约25%)
  42. column_width_mm = available_width_mm / 4 # 约18.5mm每列
  43. # 字体大小(针对80mm宽度优化,稍微缩小以适配更窄的纸张)
  44. self.title_font_size_mm = 1.9 # 标题字体大小(mm),从2.1缩小到1.9
  45. self.content_font_size_mm = 1.5 # 内容字体大小(mm),从1.68缩小到1.5
  46. self.label_font_size_mm = 1.5 # 标签字体大小(mm),从1.68缩小到1.5(不加粗)
  47. self.small_content_font_size_mm = 1.3 # 小内容字体大小(mm),用于供货单位和收货单位
  48. # 单元格内边距和间距(稍微缩小以节省空间)
  49. self.cell_padding_mm = 1.8 # 单元格内边距(mm),从2.0缩小到1.8
  50. self.label_content_spacing_mm = 2.0 # label和内容之间的间距(mm),从2.5缩小到2.0
  51. # 这些值将在draw_weighing_slip中根据实际页面尺寸动态计算
  52. self.title_font_size = None
  53. self.content_font_size = None
  54. self.label_font_size = None
  55. self.small_content_font_size = None # 小内容字体大小(points)
  56. self.line_height = None
  57. self.title_line_height = None
  58. self.cell_padding = None
  59. self.label_content_spacing = None
  60. self.label_width_2col = None
  61. self.label_width_4col = None
  62. self.label_width_cargo_name = None
  63. self.label_width_business_type = None
  64. self.label_width_supplier_consignee = None
  65. self.label_width_time = None
  66. self.label_width_planned_executed = None
  67. def _calculate_dimensions_from_page(self, page_width, page_height, dpi, painter=None):
  68. """
  69. 根据实际页面尺寸计算所有尺寸
  70. :param page_width: 页面宽度(points)
  71. :param page_height: 页面高度(points)
  72. :param dpi: 打印机DPI
  73. :param painter: QPainter对象(可选,用于更准确地计算字体宽度)
  74. """
  75. # 将mm转换为points:1mm = (dpi / 25.4) points
  76. mm_to_point = dpi / 25.4
  77. # 计算实际页面尺寸(mm)
  78. actual_width_mm = page_width / mm_to_point
  79. actual_height_mm = page_height / mm_to_point
  80. # 基于实际尺寸计算缩放比例
  81. # 宽度相对于80mm,高度相对于单张地磅单高度(150mm)
  82. width_scale = actual_width_mm / self.page_width_mm
  83. height_scale = actual_height_mm / self.slip_height_mm
  84. scale = min(width_scale, height_scale) # 使用较小的缩放比例,确保内容不超出
  85. # 计算字体大小(points)
  86. self.title_font_size = int(self.title_font_size_mm * mm_to_point * scale)
  87. self.content_font_size = int(self.content_font_size_mm * mm_to_point * scale)
  88. self.label_font_size = int(self.label_font_size_mm * mm_to_point * scale)
  89. self.small_content_font_size = int(self.small_content_font_size_mm * mm_to_point * scale)
  90. # 计算行高和间距(points)
  91. self.line_height = int(self.line_height_mm * mm_to_point * scale)
  92. self.title_line_height = int(self.title_line_height_mm * mm_to_point * scale)
  93. self.cell_padding = int(self.cell_padding_mm * mm_to_point * scale)
  94. self.label_content_spacing = int(self.label_content_spacing_mm * mm_to_point * scale)
  95. # 创建临时字体来计算label宽度(不加粗)
  96. two_char_width = 0
  97. try:
  98. label_font = QFont("微软雅黑", self.label_font_size) # 不加粗
  99. if painter:
  100. # 使用painter的font metrics,更准确
  101. painter.setFont(label_font)
  102. label_metrics = painter.fontMetrics()
  103. else:
  104. # 如果没有painter,使用QFontMetrics
  105. label_metrics = QFontMetrics(label_font)
  106. two_char_width = label_metrics.boundingRect("测试").width()
  107. except:
  108. # 如果无法创建QFontMetrics,使用估算值
  109. # 基于字体大小估算两个字的宽度
  110. two_char_width = int(self.label_font_size * 2.2)
  111. # 计算label宽度(基于mm,然后转换为points)
  112. # 80mm纸张,减去边距6mm = 74mm可用宽度
  113. # 4列布局:每列约18.5mm
  114. # 两列布局:每列约37mm,label占用约20% = 14.8mm
  115. # 四列布局:每列约18.5mm,label占用约40% = 7.4mm
  116. available_width_mm = self.page_width_mm - self.margin_left_mm - self.margin_right_mm
  117. # 两列布局:label宽度约为可用宽度的20%(给内容更多空间)
  118. label_width_2col_mm = available_width_mm * 0.20 * scale # 约18.8mm
  119. # 四列布局:label宽度约为单列宽度的40%
  120. label_width_4col_mm = (available_width_mm / 4) * 0.40 * scale # 约9.4mm
  121. self.label_width_2col = int(label_width_2col_mm * mm_to_point) + two_char_width
  122. self.label_width_4col = int(label_width_4col_mm * mm_to_point) + two_char_width
  123. # 特定字段的label宽度(基于实际字符宽度)
  124. # 货物名称、供货单位、收货单位的label较长,需要更多宽度
  125. self.label_width_cargo_name = int(available_width_mm * 0.25 * scale * mm_to_point) + two_char_width
  126. self.label_width_business_type = int(label_width_4col_mm * 1.1 * mm_to_point) + two_char_width
  127. self.label_width_supplier_consignee = int(available_width_mm * 0.25 * scale * mm_to_point) + two_char_width
  128. self.label_width_time = int(label_width_4col_mm * 1.1 * mm_to_point) + two_char_width
  129. self.label_width_planned_executed = int(label_width_4col_mm * 1.1 * mm_to_point) + two_char_width
  130. def get_printer(self) -> QPrinter:
  131. """
  132. 获取配置好的打印机对象
  133. :return: QPrinter对象
  134. """
  135. # 使用高分辨率打印机
  136. printer = QPrinter(QPrinter.HighResolution)
  137. # 尝试全页打印,绕过软件边距限制
  138. printer.setFullPage(True)
  139. # 设置自定义页面大小:80mm x 150mm
  140. printer.setPageSize(QPrinter.Custom)
  141. # 设置页面尺寸(单位:毫米)
  142. # 使用setPaperSize设置自定义尺寸
  143. try:
  144. printer.setPaperSize(QSizeF(self.page_width_mm, self.page_height_mm), QPrinter.Millimeter)
  145. except (AttributeError, TypeError):
  146. # 如果setPaperSize不存在或参数错误,尝试使用物理尺寸
  147. try:
  148. # 计算points尺寸:80mm = 226.77 points (72 DPI), 150mm = 425.19 points
  149. # 但在高分辨率打印机上,需要使用实际DPI
  150. dpi = printer.resolution()
  151. width_points = self.page_width_mm * (dpi / 25.4)
  152. height_points = self.page_height_mm * (dpi / 25.4)
  153. printer.setPaperSize(QSizeF(width_points, height_points), QPrinter.Point)
  154. except:
  155. pass
  156. # 设置页边距(单位:毫米)左、上、右、下
  157. printer.setPageMargins(
  158. self.margin_left_mm, self.margin_top_mm,
  159. self.margin_right_mm, self.margin_bottom_mm,
  160. QPrinter.Millimeter
  161. )
  162. return printer
  163. def preview_weighing_slip(self, slip: Dict, copies: int = 1):
  164. """
  165. 预览地磅单
  166. :param slip: 地磅单数据字典
  167. :param copies: 预览份数
  168. """
  169. printer = self.get_printer()
  170. # 创建打印预览对话框
  171. preview_dialog = QPrintPreviewDialog(printer)
  172. preview_dialog.setWindowTitle("打印预览 - 地磅单")
  173. # 定义绘制函数
  174. def paint_page(printer_obj):
  175. painter = QPainter(printer_obj)
  176. try:
  177. for copy_index in range(copies):
  178. self.draw_weighing_slip(
  179. painter, printer_obj, slip,
  180. copy_index=copy_index + 1, total_copies=copies
  181. )
  182. if copy_index < copies - 1:
  183. printer_obj.newPage()
  184. finally:
  185. painter.end()
  186. # 连接预览绘制信号
  187. preview_dialog.paintRequested.connect(paint_page)
  188. # 显示预览对话框
  189. preview_dialog.exec_()
  190. def print_weighing_slip(self, slip: Dict, show_preview: bool = False, copies: int = 1):
  191. """
  192. 打印地磅单
  193. :param slip: 地磅单数据字典
  194. :param show_preview: 是否先显示预览(默认False,直接打印)
  195. :param copies: 打印份数
  196. """
  197. if show_preview:
  198. # 显示预览
  199. self.preview_weighing_slip(slip, copies=copies)
  200. return
  201. printer = self.get_printer()
  202. # 显示打印对话框
  203. print_dialog = QPrintDialog(printer)
  204. if print_dialog.exec_() != QPrintDialog.Accepted:
  205. return
  206. # 开始打印
  207. painter = QPainter()
  208. painter.begin(printer)
  209. try:
  210. for copy_index in range(copies):
  211. self.draw_weighing_slip(
  212. painter, printer, slip,
  213. copy_index=copy_index + 1, total_copies=copies
  214. )
  215. if copy_index < copies - 1:
  216. printer.newPage()
  217. finally:
  218. painter.end()
  219. def direct_print_weighing_slip(self, slip: Dict, copies: int = 1):
  220. """
  221. 直接打印地磅单,不显示打印对话框
  222. :param slip: 地磅单数据字典
  223. :param copies: 打印份数
  224. """
  225. printer = self.get_printer()
  226. # 开始打印
  227. painter = QPainter()
  228. painter.begin(printer)
  229. try:
  230. for copy_index in range(copies):
  231. self.draw_weighing_slip(
  232. painter, printer, slip,
  233. copy_index=copy_index + 1, total_copies=copies
  234. )
  235. if copy_index < copies - 1:
  236. printer.newPage()
  237. finally:
  238. painter.end()
  239. def draw_weighing_slip(
  240. self,
  241. painter: QPainter,
  242. printer: QPrinter,
  243. slip: Dict,
  244. copy_index: int = 1,
  245. total_copies: int = 1
  246. ):
  247. """
  248. 绘制地磅单内容(300mm高度,上下各一张150mm的地磅单)
  249. :param painter: QPainter对象
  250. :param printer: QPrinter对象
  251. :param slip: 地磅单数据字典
  252. """
  253. # 获取页面尺寸(已减去边距)
  254. page_rect = printer.pageRect()
  255. width = page_rect.width()
  256. height = page_rect.height()
  257. # 获取打印机DPI
  258. dpi = printer.resolution()
  259. # 计算单张地磅单的高度(points)
  260. # 单张地磅单高度150mm,转换为points
  261. mm_to_point = dpi / 25.4
  262. single_slip_height_points = self.slip_height_mm * mm_to_point
  263. # 根据单张地磅单的尺寸计算所有尺寸(使用150mm作为参考高度)
  264. # 创建一个临时的页面尺寸来计算尺寸
  265. temp_width_points = width
  266. temp_height_points = single_slip_height_points
  267. self._calculate_dimensions_from_page(temp_width_points, temp_height_points, dpi, painter)
  268. # 起始 x 坐标:从可打印区域左边缘开始,加上向左偏移抵消物理边距
  269. offset_x_points = self.content_offset_x_mm * mm_to_point
  270. x = offset_x_points
  271. # 绘制第一张地磅单(从y=0开始,但向上偏移抵消打印机物理边距)
  272. y1 = -15 # 向上偏移15pt来抵消打印机顶部物理边距
  273. self._draw_single_slip(painter, slip, x, y1, width, dpi)
  274. def _draw_single_slip(
  275. self,
  276. painter: QPainter,
  277. slip: Dict,
  278. x: float,
  279. start_y: float,
  280. width: float,
  281. dpi: int
  282. ):
  283. """
  284. 绘制单张地磅单
  285. :param painter: QPainter对象
  286. :param slip: 地磅单数据字典
  287. :param x: 起始x坐标
  288. :param start_y: 起始y坐标
  289. :param width: 宽度
  290. :param dpi: 打印机DPI
  291. """
  292. y = start_y
  293. # 设置字体(针式票据机字距偏紧,增加字间距便于阅读)
  294. letter_spacing_points = 3.5 # 字间距(points),可按打印机观感微调
  295. title_font = QFont("微软雅黑", self.title_font_size, QFont.Bold)
  296. title_font.setLetterSpacing(QFont.AbsoluteSpacing, letter_spacing_points)
  297. # label字体不加粗,与内容字体一样
  298. label_font = QFont("微软雅黑", self.label_font_size) # 不加粗
  299. label_font.setLetterSpacing(QFont.AbsoluteSpacing, letter_spacing_points)
  300. content_font = QFont("微软雅黑", self.content_font_size)
  301. content_font.setLetterSpacing(QFont.AbsoluteSpacing, letter_spacing_points)
  302. # 小内容字体(用于供货单位和收货单位),字号+2
  303. small_content_font_size_with_offset = self.small_content_font_size + 2
  304. small_content_font = QFont("微软雅黑", small_content_font_size_with_offset)
  305. small_content_font.setLetterSpacing(QFont.AbsoluteSpacing, letter_spacing_points)
  306. # 绘制标题 - 确保居中,带出入库单ID(若有)
  307. painter.setFont(title_font)
  308. inbound_id = slip.get("inbound_outbound_id")
  309. if inbound_id is not None and inbound_id != "":
  310. title = f"山峡化工地磅单 ID:{inbound_id}"
  311. else:
  312. title = "山峡化工地磅单"
  313. title_metrics = QFontMetrics(title_font)
  314. # 使用boundingRect获取更准确的文本宽度
  315. title_rect = title_metrics.boundingRect(title)
  316. title_width = title_rect.width()
  317. # 使用页面实际宽度计算居中位置(相对于pageRect,x从0开始)
  318. title_x = (width - title_width) / 2
  319. # 确保标题垂直居中在标题行内
  320. # 使用更精确的垂直居中:单元格中心 + 文本rect的top偏移
  321. title_baseline = y + self.title_line_height / 2 + title_rect.height() / 2 - title_rect.bottom()
  322. # 使用QRect和Qt.AlignCenter来确保完美居中
  323. title_draw_rect = QRect(0, int(y), int(width), int(self.title_line_height))
  324. painter.drawText(title_draw_rect, Qt.AlignCenter, title)
  325. # 标题后直接开始数据行,不增加额外间距(因为行高已经合理分配)
  326. y += self.title_line_height
  327. # 设置边框画笔(2px边框线)
  328. # 在Qt打印系统中,使用逻辑单位,设置为2点(points)即可
  329. # 这样在打印时会自动按比例缩放,保持2像素的视觉效果
  330. border_width_points = 2 # 2px边框宽度(逻辑单位)
  331. border_pen = QPen(Qt.black, border_width_points)
  332. border_pen.setStyle(Qt.SolidLine)
  333. painter.setPen(border_pen)
  334. # 绘制表格内容(带边框)
  335. painter.setFont(label_font)
  336. content_metrics = QFontMetrics(content_font)
  337. label_metrics = QFontMetrics(label_font)
  338. # 计算文本垂直居中位置(通用函数)
  339. def get_text_baseline(cell_y_pos):
  340. max_metrics = label_metrics if label_metrics.height() > content_metrics.height() else content_metrics
  341. return cell_y_pos + self.line_height / 2 + max_metrics.ascent() - max_metrics.height() / 2
  342. # 辅助函数:绘制两列单元格(label + 内容),支持自动换行
  343. def draw_2col_row(label_text, value_text, y_pos, custom_label_width=None,
  344. custom_content_font=None, custom_spacing=None,
  345. enable_wrap=False):
  346. cell_y = y_pos
  347. # 使用自定义label宽度或默认宽度
  348. label_width = custom_label_width if custom_label_width is not None else self.label_width_2col
  349. # 使用自定义字体或默认内容字体
  350. value_font = custom_content_font if custom_content_font is not None else content_font
  351. # 使用自定义间距或默认间距
  352. spacing = custom_spacing if custom_spacing is not None else self.label_content_spacing
  353. # 计算内容区域的最大宽度
  354. label_x = x + self.cell_padding
  355. content_x = label_x + label_width + spacing
  356. content_max_width = width - content_x - self.cell_padding
  357. # 如果启用自动换行
  358. if enable_wrap and value_text:
  359. painter.setFont(value_font)
  360. value_metrics = painter.fontMetrics()
  361. value_str = str(value_text)
  362. # 计算需要换几行
  363. text_width = value_metrics.boundingRect(value_str).width()
  364. if text_width > content_max_width:
  365. # 需要换行,计算每个字符的宽度来找到断点
  366. lines = []
  367. current_line = ""
  368. for char in value_str:
  369. test_line = current_line + char
  370. if value_metrics.boundingRect(test_line).width() <= content_max_width:
  371. current_line = test_line
  372. else:
  373. if current_line:
  374. lines.append(current_line)
  375. current_line = char
  376. if current_line:
  377. lines.append(current_line)
  378. # 换行行高(保证文字不压边框,约65%单行高)
  379. wrap_line_height = int(self.line_height * 0.65)
  380. actual_height = wrap_line_height * len(lines)
  381. painter.drawRect(int(x), int(cell_y), int(width), int(actual_height))
  382. text_baseline = get_text_baseline(cell_y)
  383. # 绘制标签
  384. painter.setFont(label_font)
  385. painter.drawText(int(label_x), int(text_baseline), label_text)
  386. # 绘制多行内容
  387. for i, line in enumerate(lines):
  388. line_baseline = text_baseline + i * wrap_line_height
  389. painter.drawText(int(content_x), int(line_baseline), line)
  390. return y_pos + actual_height
  391. # 不启用换行时的原有逻辑
  392. painter.drawRect(int(x), int(cell_y), int(width), int(self.line_height))
  393. text_baseline = get_text_baseline(cell_y)
  394. # 绘制标签
  395. painter.setFont(label_font)
  396. painter.drawText(int(label_x), int(text_baseline), label_text)
  397. # 绘制内容
  398. if value_text:
  399. painter.setFont(value_font)
  400. painter.drawText(int(content_x), int(text_baseline), str(value_text))
  401. return y_pos + self.line_height
  402. # 辅助函数:绘制四列单元格(label1 + 内容1 + label2 + 内容2)
  403. def draw_4col_row(label1_text, value1_text, label2_text, value2_text, y_pos,
  404. custom_label1_width=None, custom_label2_width=None,
  405. left_content_max_width=None, custom_line_height=None,
  406. draw_center_line=False, wrap_right_value=False,
  407. left_value_offset=0, right_value_offset=0, right_label_offset=0,
  408. right_label_content_spacing=None):
  409. cell_y = y_pos
  410. base_line_height = custom_line_height if custom_line_height is not None else self.line_height
  411. actual_line_height = base_line_height
  412. label1_width = custom_label1_width if custom_label1_width is not None else self.label_width_4col
  413. label2_width = custom_label2_width if custom_label2_width is not None else self.label_width_4col
  414. label1_x = x + self.cell_padding
  415. content1_x = label1_x + label1_width + self.label_content_spacing
  416. if left_content_max_width is not None:
  417. content1_max_width = left_content_max_width
  418. left_end_x = content1_x + content1_max_width
  419. right_start_x = left_end_x + self.cell_padding
  420. else:
  421. left_half_width = width / 2
  422. right_start_x = x + left_half_width
  423. content1_max_width = right_start_x - content1_x - self.cell_padding
  424. label2_x = right_start_x + self.cell_padding
  425. # 应用右侧label的偏移
  426. if right_label_offset:
  427. label2_x += right_label_offset
  428. # 使用自定义右侧间距或默认间距
  429. right_spacing = right_label_content_spacing if right_label_content_spacing is not None else self.label_content_spacing
  430. content2_x = label2_x + label2_width + right_spacing
  431. content2_max_width = width - content2_x - self.cell_padding
  432. if left_value_offset:
  433. content1_x += left_value_offset
  434. content1_max_width = max(content1_max_width - left_value_offset, 0)
  435. if right_value_offset:
  436. content2_x += right_value_offset
  437. content2_max_width = max(content2_max_width - right_value_offset, 0)
  438. value2_str = str(value2_text) if value2_text is not None else ""
  439. multiline_right = False
  440. right_text_font = content_font
  441. right_text_flags = None
  442. if value2_str:
  443. if wrap_right_value:
  444. multiline_right = True
  445. right_text_flags = Qt.AlignLeft | Qt.AlignTop | Qt.TextWordWrap | Qt.TextWrapAnywhere
  446. painter.setFont(content_font)
  447. bounding = painter.boundingRect(
  448. QRect(0, 0, int(content2_max_width), 10000),
  449. right_text_flags,
  450. value2_str
  451. )
  452. actual_line_height = max(actual_line_height, bounding.height() + 2 * self.cell_padding)
  453. elif "\n" in value2_str:
  454. multiline_right = True
  455. time_font_size = int(self.content_font_size * 0.9)
  456. right_text_font = QFont("微软雅黑", time_font_size)
  457. right_text_flags = Qt.AlignLeft | Qt.AlignTop | Qt.TextWordWrap
  458. painter.setFont(right_text_font)
  459. bounding = painter.boundingRect(
  460. QRect(0, 0, int(content2_max_width), 10000),
  461. right_text_flags,
  462. value2_str
  463. )
  464. actual_line_height = max(actual_line_height, bounding.height() + 2 * self.cell_padding)
  465. painter.drawRect(int(x), int(cell_y), int(width), int(actual_line_height))
  466. text_baseline = get_text_baseline(cell_y)
  467. painter.setFont(label_font)
  468. painter.drawText(int(label1_x), int(text_baseline), label1_text)
  469. if value1_text:
  470. painter.setFont(content_font)
  471. painter.drawText(int(content1_x), int(text_baseline), str(value1_text))
  472. painter.setFont(label_font)
  473. painter.drawText(int(label2_x), int(text_baseline), label2_text)
  474. if value2_str:
  475. if multiline_right:
  476. painter.setFont(right_text_font)
  477. content2_rect = QRect(
  478. int(content2_x),
  479. int(cell_y + self.cell_padding),
  480. int(content2_max_width),
  481. int(actual_line_height - 2 * self.cell_padding)
  482. )
  483. painter.drawText(content2_rect, right_text_flags, value2_str)
  484. else:
  485. painter.setFont(content_font)
  486. painter.drawText(int(content2_x), int(text_baseline), value2_str)
  487. if draw_center_line:
  488. offset_points = 30 * 72.0 / 96.0
  489. center_x = x + width / 2 - offset_points
  490. painter.drawLine(int(center_x), int(cell_y), int(center_x), int(cell_y + actual_line_height))
  491. return y_pos + actual_line_height
  492. # 表格第一行:车号(两列:label + 内容)
  493. y = draw_2col_row("车号:", slip['vehicle_no'], y)
  494. # 表格第二行:计划号(两列:label + 内容)
  495. y = draw_2col_row("计划号:", slip.get('plan_no', '') or '', y)
  496. # 表格第三行:货物名称(两列:label + 内容)
  497. # 计算计划号的内容起始位置,使货物名称的值与计划号的值左对齐
  498. plan_no_content_start = x + self.cell_padding + self.label_width_2col + self.label_content_spacing
  499. cargo_name_content_start = x + self.cell_padding + self.label_width_cargo_name
  500. # 计算需要的间距使得货物名称的内容起始位置与计划号对齐
  501. cargo_name_spacing = plan_no_content_start - cargo_name_content_start
  502. y = draw_2col_row("货物名称:", slip['cargo_name'], y, self.label_width_cargo_name,
  503. custom_spacing=cargo_name_spacing)
  504. # 表格第四行:业务类型、批号(四列:label1 + 内容1 + label2 + 内容2)
  505. # 业务类型的值向右移动14px(4px + 10px),批号的值向左移动4px
  506. business_type_offset = 14 * 72.0 / 96.0 # 向右移动14px(转换为points)
  507. batch_no_offset = -4 * 72.0 / 96.0 # 向左移动4px(转换为points)
  508. # 批号的label宽度缩小6px
  509. batch_no_label_width_offset = -6 * 72.0 / 96.0 # 缩小6px(转换为points)
  510. batch_no_label_width = self.label_width_4col + batch_no_label_width_offset
  511. # 批号的label和值之间的间距缩小(缩小约30%)
  512. batch_no_spacing = self.label_content_spacing * 0.7
  513. y = draw_4col_row(
  514. "业务类型:", slip['business_type'],
  515. "批号:", slip.get('batch_no', '') or '',
  516. y,
  517. custom_label1_width=self.label_width_business_type,
  518. custom_label2_width=batch_no_label_width,
  519. draw_center_line=True,
  520. wrap_right_value=True,
  521. left_value_offset=business_type_offset,
  522. right_value_offset=batch_no_offset,
  523. right_label_content_spacing=batch_no_spacing
  524. )
  525. # 表格第五行:供货单位(两列:label + 内容)
  526. # 字号+2,距离左边label的距离-76,label宽度缩小30
  527. # 启用自动换行(enable_wrap=True)
  528. supplier_spacing = max(0, int(self.label_content_spacing * 0.6) - 76) # 间距减少76 points
  529. supplier_label_width = max(0, self.label_width_supplier_consignee - 30) # label宽度缩小30 points
  530. y = draw_2col_row("供货单位:", slip['supplier'], y, supplier_label_width,
  531. custom_content_font=small_content_font, custom_spacing=supplier_spacing,
  532. enable_wrap=True)
  533. # 表格第六行:收货单位(两列:label + 内容)
  534. # 字号+2,距离左边label的距离-76,label宽度缩小30
  535. # 启用自动换行(enable_wrap=True)
  536. consignee_spacing = max(0, int(self.label_content_spacing * 0.6) - 76) # 间距减少76 points
  537. consignee_label_width = max(0, self.label_width_supplier_consignee - 30) # label宽度缩小30 points
  538. y = draw_2col_row("收货单位:", slip['consignee'], y, consignee_label_width,
  539. custom_content_font=small_content_font, custom_spacing=consignee_spacing,
  540. enable_wrap=True)
  541. # 格式化时间字符串,将日期和时间分两行显示
  542. def format_time_to_two_lines(time_str):
  543. """将时间字符串格式化为两行:日期和时间分开"""
  544. if not time_str:
  545. return ""
  546. # 将空格替换为换行符
  547. # 例如:"2025-11-20 09:08:01" -> "2025-11-20\n09:08:01"
  548. return str(time_str).replace(" ", "\n", 1)
  549. # 表格第七行:毛重(t)、毛重时间(四列:label1 + 内容1 + label2 + 内容2)
  550. # 将kg转换为t(除以1000)
  551. gross_weight_t = slip['gross_weight'] / 1000.0
  552. # 格式化毛重时间,分成两行显示
  553. gross_weight_time_formatted = format_time_to_two_lines(slip['gross_weight_time'])
  554. # 限制毛重内容区域宽度,让时间部分往左移
  555. # 4列布局:针对80mm纸张优化,限制毛重内容宽度为页面宽度的18%(从22%缩小)
  556. gross_weight_content_width = int(width * 0.18)
  557. # 毛重时间的label往右4px,值往右8px
  558. # 将px转换为points:1px = 72/96 points (在96 DPI下)
  559. label_offset_4px = 4 * 72.0 / 96.0
  560. value_offset_8px = 8 * 72.0 / 96.0
  561. y = draw_4col_row(
  562. "毛重(t):", f"{gross_weight_t:.2f}",
  563. "毛重时间:", gross_weight_time_formatted,
  564. y,
  565. custom_label2_width=self.label_width_time,
  566. left_content_max_width=gross_weight_content_width,
  567. draw_center_line=True,
  568. right_label_offset=label_offset_4px,
  569. right_value_offset=value_offset_8px
  570. )
  571. # 表格第八行:皮重(t)、皮重时间(四列:label1 + 内容1 + label2 + 内容2)
  572. # 将kg转换为t(除以1000)
  573. tare_weight_t = slip['tare_weight'] / 1000.0
  574. # 格式化皮重时间,分成两行显示
  575. tare_weight_time_formatted = format_time_to_two_lines(slip['tare_weight_time'])
  576. # 限制皮重内容区域宽度,让时间部分往左移
  577. # 4列布局:针对80mm纸张优化,与毛重相同,限制皮重内容宽度为页面宽度的18%
  578. tare_weight_content_width = int(width * 0.18)
  579. # 皮重时间的label往右4px,值往右8px
  580. y = draw_4col_row(
  581. "皮重(t):", f"{tare_weight_t:.2f}",
  582. "皮重时间:", tare_weight_time_formatted,
  583. y,
  584. custom_label2_width=self.label_width_time,
  585. left_content_max_width=tare_weight_content_width,
  586. draw_center_line=True,
  587. right_label_offset=label_offset_4px,
  588. right_value_offset=value_offset_8px
  589. )
  590. # 表格第九行:扣杂(t)、净重(t)(四列:label1 + 内容1 + label2 + 内容2)
  591. # 将kg转换为t(除以1000)
  592. deduction_t = slip.get('deduction', 0) / 1000.0
  593. net_weight_t = slip['net_weight'] / 1000.0
  594. # 使用与皮重时间相同的左侧内容宽度,确保右侧label对齐
  595. # 净重的label往右4px,值往右8px
  596. y = draw_4col_row(
  597. "扣杂(t):", f"{deduction_t:.2f}",
  598. "净重(t):", f"{net_weight_t:.2f}",
  599. y,
  600. left_content_max_width=tare_weight_content_width,
  601. draw_center_line=True,
  602. right_label_offset=label_offset_4px,
  603. right_value_offset=value_offset_8px
  604. )
  605. # 表格第十行:计划量(t)、已执行量(t)(四列:label1 + 内容1 + label2 + 内容2)
  606. # 将kg转换为t(除以1000)
  607. planned_qty = slip.get('planned_quantity')
  608. planned_qty_t = planned_qty / 1000.0 if planned_qty else None
  609. executed_qty = slip.get('executed_quantity')
  610. executed_qty_t = executed_qty / 1000.0 if executed_qty else None
  611. # 使用与皮重时间相同的左侧内容宽度,确保右侧label对齐
  612. value_shift_points = 30 * 72.0 / 96.0
  613. executed_value_extra_shift = 30 * 72.0 / 96.0
  614. # 计划量和已执行量的值都向右移动8px
  615. additional_right_shift = 8 * 72.0 / 96.0
  616. # 计划量的值向左移动20px
  617. planned_value_left_shift = 20 * 72.0 / 96.0
  618. # 计划量和已执行量的label宽度减少8px
  619. label_width_reduction = 8 * 72.0 / 96.0
  620. planned_executed_label_width = self.label_width_planned_executed - label_width_reduction
  621. y = draw_4col_row(
  622. "计划量(t):", f"{planned_qty_t:.2f}" if planned_qty_t else "",
  623. "已执行量(t):", f"{executed_qty_t:.2f}" if executed_qty_t else "",
  624. y,
  625. custom_label1_width=planned_executed_label_width,
  626. custom_label2_width=planned_executed_label_width,
  627. left_content_max_width=tare_weight_content_width,
  628. draw_center_line=True,
  629. left_value_offset=value_shift_points + additional_right_shift - planned_value_left_shift,
  630. right_value_offset=value_shift_points + executed_value_extra_shift + additional_right_shift
  631. )
  632. # 表格第十一行:磅点(两列:label + 内容)
  633. y = draw_2col_row("磅点:", slip.get('weighing_point', '山峡地磅'), y)
  634. # 表格第十二行:备注(两列:label + 内容)
  635. y = draw_2col_row("备注:", slip.get('remarks', '') or '', y)