tablepic 0.2.2__tar.gz → 0.3.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. tablepic-0.3.0/MANIFEST.in +5 -0
  2. {tablepic-0.2.2 → tablepic-0.3.0}/PKG-INFO +6 -3
  3. {tablepic-0.2.2 → tablepic-0.3.0}/README.md +290 -9
  4. tablepic-0.3.0/pyproject.toml +41 -0
  5. tablepic-0.3.0/src/tablepic/__init__.py +14 -0
  6. tablepic-0.3.0/src/tablepic/font.py +232 -0
  7. tablepic-0.3.0/src/tablepic/fonts/NotoSansSC-GBK.otf +0 -0
  8. tablepic-0.3.0/src/tablepic/fonts/OFL.txt +94 -0
  9. tablepic-0.3.0/src/tablepic/fonts/manifest.json +47 -0
  10. {tablepic-0.2.2 → tablepic-0.3.0}/src/tablepic/main.py +66 -39
  11. {tablepic-0.2.2 → tablepic-0.3.0}/src/tablepic.egg-info/PKG-INFO +6 -3
  12. {tablepic-0.2.2 → tablepic-0.3.0}/src/tablepic.egg-info/SOURCES.txt +8 -1
  13. tablepic-0.3.0/src/tablepic.egg-info/requires.txt +2 -0
  14. tablepic-0.3.0/tests/test_font.py +299 -0
  15. tablepic-0.3.0/tools/build_font.py +213 -0
  16. tablepic-0.2.2/MANIFEST.in +0 -3
  17. tablepic-0.2.2/pyproject.toml +0 -24
  18. tablepic-0.2.2/src/tablepic/__init__.py +0 -10
  19. {tablepic-0.2.2 → tablepic-0.3.0}/LICENSE +0 -0
  20. {tablepic-0.2.2 → tablepic-0.3.0}/readme_pypi.md +0 -0
  21. {tablepic-0.2.2 → tablepic-0.3.0}/setup.cfg +0 -0
  22. {tablepic-0.2.2 → tablepic-0.3.0}/src/tablepic/assets/arrow_down.png +0 -0
  23. {tablepic-0.2.2 → tablepic-0.3.0}/src/tablepic/assets/arrow_down2.png +0 -0
  24. {tablepic-0.2.2 → tablepic-0.3.0}/src/tablepic/assets/arrow_up.png +0 -0
  25. {tablepic-0.2.2 → tablepic-0.3.0}/src/tablepic/assets/arrow_up2.png +0 -0
  26. {tablepic-0.2.2 → tablepic-0.3.0}/src/tablepic/assets/cicle_neutral.png +0 -0
  27. {tablepic-0.2.2 → tablepic-0.3.0}/src/tablepic/assets/circle_down.png +0 -0
  28. {tablepic-0.2.2 → tablepic-0.3.0}/src/tablepic/assets/circle_up.png +0 -0
  29. {tablepic-0.2.2 → tablepic-0.3.0}/src/tablepic/assets/happy_face.png +0 -0
  30. {tablepic-0.2.2 → tablepic-0.3.0}/src/tablepic/assets/neutral.png +0 -0
  31. {tablepic-0.2.2 → tablepic-0.3.0}/src/tablepic/assets/neutral_face.png +0 -0
  32. {tablepic-0.2.2 → tablepic-0.3.0}/src/tablepic/assets/sad_face.png +0 -0
  33. {tablepic-0.2.2 → tablepic-0.3.0}/src/tablepic/assets/square_down.png +0 -0
  34. {tablepic-0.2.2 → tablepic-0.3.0}/src/tablepic/assets/square_neutral.png +0 -0
  35. {tablepic-0.2.2 → tablepic-0.3.0}/src/tablepic/assets/square_up.png +0 -0
  36. {tablepic-0.2.2 → tablepic-0.3.0}/src/tablepic/assets/triangle_down.png +0 -0
  37. {tablepic-0.2.2 → tablepic-0.3.0}/src/tablepic/assets/triangle_up.png +0 -0
  38. {tablepic-0.2.2 → tablepic-0.3.0}/src/tablepic.egg-info/dependency_links.txt +0 -0
  39. {tablepic-0.2.2 → tablepic-0.3.0}/src/tablepic.egg-info/top_level.txt +0 -0
@@ -0,0 +1,5 @@
1
+ include LICENSE
2
+ include README.md
3
+ recursive-include src/tablepic/assets *.png
4
+ recursive-include src/tablepic/fonts *.otf *.txt *.json
5
+ recursive-include tools *.py
@@ -1,6 +1,6 @@
1
- Metadata-Version: 2.1
1
+ Metadata-Version: 2.4
2
2
  Name: tablepic
3
- Version: 0.2.2
3
+ Version: 0.3.0
4
4
  Summary: A package can generate a picture which contains a table.
5
5
  Author-email: Xin Yan <slash.xin@gmail.com>
6
6
  Project-URL: Homepage, https://github.com/slash-xin/tablepic
@@ -8,9 +8,12 @@ Project-URL: Bug Tracker, https://github.com/slash-xin/tablepic/issues
8
8
  Classifier: Programming Language :: Python :: 3
9
9
  Classifier: License :: OSI Approved :: MIT License
10
10
  Classifier: Operating System :: OS Independent
11
- Requires-Python: >=3.5
11
+ Requires-Python: >=3.9
12
12
  Description-Content-Type: text/markdown
13
13
  License-File: LICENSE
14
+ Requires-Dist: pillow>=8.0.0
15
+ Requires-Dist: numpy>=1.19.3
16
+ Dynamic: license-file
14
17
 
15
18
  <!--
16
19
  * @Author: xinyan
@@ -2,7 +2,7 @@
2
2
  * @Author: xinyan
3
3
  * @Date: 2023-11-02 19:07:09
4
4
  * @LastEditors: xinyan
5
- * @LastEditTime: 2024-03-22 21:31:08
5
+ * @LastEditTime: 2024-03-24 19:45:54
6
6
  * @Description: file content
7
7
  -->
8
8
 
@@ -12,9 +12,18 @@
12
12
  - [1. 概述](#1-概述)
13
13
  - [2. 安装](#2-安装)
14
14
  - [3. 版本说明](#3-版本说明)
15
- - [v0.2.2](#v022)
15
+ - [v0.3.0](#v030)
16
16
  - [更新概览](#更新概览)
17
+ - [内置字体](#内置字体)
18
+ - [自定义字体](#自定义字体)
19
+ - [缺字检查](#缺字检查)
20
+ - [内置字体的许可与更新](#内置字体的许可与更新)
21
+ - [v0.2.2](#v022)
22
+ - [更新概览](#更新概览-1)
17
23
  - [索引支持详述](#索引支持详述)
24
+ - [表格内容支持二维列表](#表格内容支持二维列表)
25
+ - [图标支持](#图标支持)
26
+ - [完成示例代码](#完成示例代码)
18
27
  - [v0.2.1](#v021)
19
28
  - [v0.2.0](#v020)
20
29
  - [v0.1.0](#v010)
@@ -44,7 +53,7 @@
44
53
 
45
54
  ## 2. 安装
46
55
 
47
- 请使用pip来安装这个包。
56
+ 请使用pip来安装这个包(需要 Python 3.9 及以上版本)。
48
57
 
49
58
  ```shell
50
59
  pip install tablepic
@@ -52,17 +61,287 @@ pip install tablepic
52
61
 
53
62
  ## 3. 版本说明
54
63
 
64
+ ### v0.3.0
65
+
66
+ #### 更新概览
67
+ - 更新日期:2026.12.03
68
+ - 更新内容:字体不再依赖操作系统的系统字体,改为随包内置一个开源中文字体。
69
+ - 1、不传 `font_path` 时使用内置字体(Noto Sans SC,GBK 子集),在 Windows、macOS、Linux 以及没有任何字体的容器中输出一致。
70
+ - 2、`font_path` 改为可选参数(`complex_table_pic` 的参数顺序不变);指定时只接受字体文件路径。
71
+ - 3、渲染前检查字体是否覆盖全部字符,缺字时抛出 `MissingGlyphError`,不再出现文字被悄悄吞掉或显示为方框的情况。
72
+ - 4、版本要求 Python >= 3.9。
73
+ - 5、渲染时在进程内复用字体对象与图标,输出逐像素不变。带图标的表格从秒级降到百毫秒级:50×10 带图标从 4.5 s 降到 0.26 s,200×10 带图标从 18.8 s 降到 0.74 s;不带图标的表格快 2.5~3 倍(Python 3.9 / Pillow 11.3,可用 `python benchmarks/bench.py` 复现)。
74
+
75
+ #### 内置字体
76
+ 内置字体是 [Noto Sans SC](https://github.com/notofonts/noto-cjk) Regular(与思源黑体同源)的 GBK 子集。安装后即可渲染中文和英文,无需任何配置;各平台、各机器的输出完全一致(列宽由字体测量得到,字体相同,布局才相同)。覆盖范围:
77
+ - 中文:GBK 收录的全部汉字,含简体、繁体常用字和生僻姓名字(如 堃、喆、昇)
78
+ - 英文:基本拉丁字母、数字、拉丁补充与扩展-A(含拼音声调字母)
79
+ - 其他:日文假名、希腊与西里尔字母、常用标点、货币、数学符号、箭头、带圈数字、制表符、全角字符
80
+
81
+ ```python
82
+ import tablepic as tp
83
+
84
+ title_list = [{'content': '各区域数据统计'}]
85
+ cell_dict = {'content': [['区域', '指标'], ['华东', '1,200']]}
86
+ img = tp.complex_table_pic(2, 2, title_list, cell_dict) # 不需要 font_path
87
+ img = tp.generate_table_pic(2, 2, title_list, {'content': ['区域', '指标']}, {'content': [['华东', '1,200']]})
88
+ ```
89
+
90
+ #### 自定义字体
91
+ 传入字体文件路径(`str` 或 `pathlib.Path`),标题、脚注、单元格仍可单独指定 `font_path`。`.ttc` 文件默认使用第一个 face。文件不存在或无法加载时抛出 `FontNotFoundError`。
92
+
93
+ ```python
94
+ tp.complex_table_pic(2, 2, title_list, cell_dict, font_path='/path/to/your/font.ttf')
95
+ ```
96
+
97
+ #### 缺字检查
98
+ 内置字体只覆盖中英文及常用符号。渲染前,`tablepic` 会检查每个实际使用的字体(包括单独指定的标题、脚注、单元格字体)是否包含全部待渲染的字符;缺字时抛出 `MissingGlyphError` 并列出字符与码点,此时请通过 `font_path` 指定包含这些字符的字体文件:
99
+
100
+ ```python
101
+ import tablepic as tp
102
+
103
+ try:
104
+ tp.complex_table_pic(1, 1, [{'content': 't'}], {'content': ['서울']})
105
+ except tp.MissingGlyphError as e:
106
+ print(e)
107
+ # 内置字体(Noto Sans SC,GBK 子集)不支持以下 2 个字符:서(U+C11C) 울(U+C6B8)。内置字体覆盖中文(简体、繁体常用字)、英文及常用符号;其他文字(如韩文、emoji)请通过 font_path 参数指定包含这些字符的字体文件。
108
+ ```
109
+
110
+ `FontNotFoundError`、`MissingGlyphError` 都是 `FontError` 的子类,可统一捕获。
111
+
112
+ #### 内置字体的许可与更新
113
+ - 字体许可为 SIL Open Font License 1.1,全文随包分发(`tablepic/fonts/OFL.txt`),不改变 tablepic 本身的 MIT 许可。
114
+ - 字体由 `tools/build_font.py` 生成:从上游 tag `Sans2.004` 下载官方字体并校验 sha256,子集化为 GBK 字符集,并自检字符不丢失。来源、校验和、字符集规则记录在 `tablepic/fonts/manifest.json`。更换或更新字体时重新运行该脚本即可(仅维护时需要 fontTools)。
115
+
55
116
  ### v0.2.2
56
117
 
57
118
  #### 更新概览
58
119
  - 更新日期:2024.03.22
59
- - 更新内容:针对函数 `complex_table_pic` 进行了功能优化,以及数据图表的支持
120
+ - 更新内容:针对函数 `complex_table_pic` 进行了功能优化,以及数据图表的支持。具体包括:
60
121
  - 1、参数 `cell_dict` 在指定行、列、单元格时支持逆向索引;单元格的索引还支持行列坐标索引。
61
- - 2、参数 `content` 的值支持二维列表输入;要求每行的列数是相同的。
122
+ - 2、参数 `cell_dict` 的key `content` 的值支持二维列表输入;要求每行的列数是相同的。
62
123
  - 3、支持对单元格添加指示性的图标:箭头、表情、百分比。
63
124
 
64
125
  #### 索引支持详述
65
- 针对一个5x5的表格,除了用 `r0` 表示第一行,和 `r-5`表示相同的行;`c2` 和 `c-3` 表示相同的列。在此版本之前,单元格的索引与 `content` 参数内容的索引同步。在此表格没有合并的单元格的前提下,若要对第二行第一列的单元格设置属性,则必须通过索引`5` 表示。在此版本后,还可以通过 `1-0`、`1,0`、`1,-5` 、`-4,0`、`-4,-5` 表示。
126
+ 针对一个5x5,且没有单元格合并的表格,除了用 `r0` 表示第一行外,还可以用 `r-5`表示相同的行;可以用 `c2` 和 `c-3` 表示相同的列。
127
+
128
+ 在此版本之前,单元格的索引与 `content` 参数内容的索引同步。若要对第二行第一列的单元格设置属性,则必须通过索引`5` 表示。在此版本后,还可以通过 `1-0`、`1,0`、`1,-5` 、`-4,0`、`-4,-5` 表示。
129
+
130
+ > 注:在一开始设计此包时,单元格索引使用 `[行坐标]-[纵坐标]` 的方式,“-”作为分隔符使用。但是此次增加逆向索引的功能时发现,逆向索引的负号会和分隔符混在一起。所以,此次增加了“,”作为分隔符的支持。若要使用逆向索引,必须使用逗号分隔符。
131
+
132
+ 代码示例:
133
+
134
+ ```python
135
+ bold_font_path = '/xxx/xxx.ttf
136
+
137
+ cell_dict = {
138
+ 'content': [
139
+ 'xxx','xxx','xxx','xxx',
140
+ 'xxx','xxx','xxx','xxx',
141
+ 'xxx','xxx','xxx','xxx'
142
+ ],
143
+ 'font_path': {'r0': bold_font_path, 'r-1': bold_font_path}
144
+ 'back_color': {'r3': '#FF0000', 'c-1': '00FF00'}
145
+ 'font_size': {4: 20, '1-0': 25, '2,2': 30, '-1,-1': 40}
146
+ }
147
+ ```
148
+
149
+ #### 表格内容支持二维列表
150
+
151
+ 为了更加方便使用,增加二维列表的赋值方式。但需要注意
152
+ - 如果是一维列表赋值,被合并的单元格内容是不需要指定的。
153
+ - 如果是二维列表赋值,被合并的单元格的内容也需要指定(虽然不使用),也就意味着1维列表的大小必须相同。
154
+
155
+ 代码示例:
156
+
157
+ ```python
158
+
159
+ # 假设3*4的表格,有第三行的前个单元格被合并
160
+ merge_dict = {'2,0':[0,1]}
161
+ # 一维列表赋值
162
+ cell_dict = {
163
+ 'content': [
164
+ 'xxx','xxx','xxx','xxx',
165
+ 'xxx','xxx','xxx','xxx',
166
+ 'xxx','xxx','xxx'
167
+ ],
168
+ }
169
+
170
+ # 二维列表赋值
171
+ cell_dict = {
172
+ 'content': [
173
+ ['xxx','xxx','xxx','xxx'],
174
+ ['xxx','xxx','xxx','xxx'],
175
+ ['xxx','占位没用','xxx','xxx']
176
+ ],
177
+ }
178
+ ```
179
+ #### 图标支持
180
+
181
+ 此版本增加了单元格指示性图标的支持,目前可使用的图标类型包括以下几种:
182
+
183
+ ![IconCollect](./pic/IconDesc.png)
184
+
185
+ 图标的设定只支持单元格,也就是说需要为想要设定图标的单元格都分别指定。通过 `cell_dict` 参数中的 `icon_config` key来为每个单元格设定图标属性。目前可以指定:
186
+ - 图标的类型
187
+ - 图标的颜色
188
+
189
+ 图标的类型即为上图中每个图标下方的名字,颜色通过十六进制颜色代码指定,两部分信息通过“@”进行分割。其中百分比图标可以指定具体的百分比数。
190
+
191
+ 示例代码:
192
+
193
+ ```python
194
+ cell_dict = {
195
+ 'content': [
196
+ ['ID', '指标1', '指标2', '指标3'],
197
+ ['A001', '10', '-20', '36.76%'],
198
+ ['A002', '-5', '40', '85.33%'],
199
+ ],
200
+ 'icon_config': {
201
+ '1,1': 'triangle_up@#FF0000', '1,2': 'square_down@#00FF00', '1,3': 'percent_36@#FF0000',
202
+ '2,1': 'triangle_down@#00FF00', '2,2': 'square_up@#FF0000', '2,3': 'percent_85@#00FF00',
203
+ }
204
+ }
205
+ ```
206
+
207
+ 以上设置将会得到下面的结果:
208
+
209
+ ![icon_demo](./pic/icon_demo.png)
210
+
211
+
212
+ #### 完成示例代码
213
+
214
+ 以下是一段完整的代码,生成的结果如下所示:
215
+
216
+ ![demo_complex_table_with_icon](./pic/demo_complex_table_with_icon.png)
217
+
218
+ ```python
219
+
220
+ import pandas as pd
221
+ import tablepic as tp
222
+
223
+ data_list = [
224
+ ['华北', '北京', 800, 1200, 950, 1400],
225
+ ['华北', '天津', 950, 1210, 860, 1410],
226
+ ['东北', '辽宁', 1100, 1220, 1370, 1420],
227
+ ['东北', '吉林', 1120, 1230, 1380, 1430],
228
+ ['华东', '上海', 1200, 1240, 1090, 1440],
229
+ ['华东', '江苏', 1210, 1250, 950, 1450],
230
+ ['华中', '湖北', 1220, 1260, 560, 1460],
231
+ ['华中', '湖南', 1230, 1270, 1270, 1470],
232
+ ['华南', '广东', 1240, 1280, 1370, 1480],
233
+ ['华南', '广西', 1250, 1290, 1480, 1490],
234
+ ]
235
+
236
+ df = pd.DataFrame(data_list, columns=['区域', '省份', '指标1', '指标2', '指标3', '指标4'])
237
+ df_sum = df.groupby('区域').sum(numeric_only=True).reset_index()
238
+ df_sum['区域'] = df_sum['区域'].apply(lambda x: x+'合计')
239
+ df_sum['省份'] = ''
240
+
241
+ df_final = pd.concat([df, df_sum], axis=0).sort_values(by='区域').reset_index(drop=True)
242
+ df_final['指标5'] = df_final['指标1'] / df_final['指标2']
243
+ df_final['指标6'] = df_final['指标3'] / df_final['指标4']
244
+
245
+ # 类型处理
246
+ for col in ['指标1', '指标2', '指标3', '指标4']:
247
+ df_final[col] = df_final[col].apply(lambda x: f'{x:,}')
248
+ for col in ['指标5', '指标6']:
249
+ df_final[col] = df_final[col].apply(lambda x: f'{x:.2%}')
250
+
251
+
252
+
253
+ font_path = '/Users/xinyan/Library/Fonts/sarasa-mono-sc-regular.ttf'
254
+ font_bold_path = '/Users/xinyan/Library/Fonts/sarasa-mono-sc-bold.ttf'
255
+ title_list = [
256
+ {'content': 'XXX区域数据统计', 'padding_b': 0, 'font_path': font_bold_path},
257
+ {'content': '统计日期:2024.03.18', 'font_size': 20, 'align': 'right', 'padding_t':10, 'padding_b':0, 'x_offset': -30},
258
+ ]
259
+
260
+ footnote_list = [
261
+ {'content': '注:以上数据与实际图标只为演示,无实际意义!', 'padding_t': 0},
262
+ ]
263
+
264
+ # 单元格内容
265
+ content_list = [df_final.columns.tolist()] + df_final.values.tolist()
266
+ # 合并单元格计算:合计行的【区域】字段合并
267
+ merge_dict = {}
268
+ row_font_path = {}
269
+ for idx, val in enumerate(df_final['区域']):
270
+ if val.endswith('合计'):
271
+ merge_dict[f'{idx+1}-0'] = [0, 1]
272
+ row_font_path[f'r{idx+1}'] = font_bold_path
273
+ # 颜色定义
274
+ clr_good = '#2a6e3f'
275
+ clr_warn = '#f39c12'
276
+ clr_bad = '#c12c1f'
277
+ # 图标配置
278
+ icon_config = {}
279
+ for r_idx, row in df_final.iterrows():
280
+ c_idx = 0
281
+ for col, val in row.items():
282
+ # 指标1:箭头
283
+ if col == '指标1':
284
+ if float(val.replace(',', '')) > 1200:
285
+ icon_config[f'{r_idx+1}-{c_idx}'] = f'arrow_up@{clr_good}'
286
+ elif float(val.replace(',', '')) > 1100:
287
+ icon_config[f'{r_idx+1}-{c_idx}'] = f'neutral@{clr_warn}'
288
+ else:
289
+ icon_config[f'{r_idx+1}-{c_idx}'] = f'arrow_down@{clr_bad}'
290
+ # 指标2:圆圈箭头
291
+ elif col == '指标2':
292
+ if float(val.replace(',', '')) > 1280:
293
+ icon_config[f'{r_idx+1}-{c_idx}'] = f'circle_up@{clr_good}'
294
+ elif float(val.replace(',', '')) > 1250:
295
+ icon_config[f'{r_idx+1}-{c_idx}'] = f'neutral@{clr_warn}'
296
+ else:
297
+ icon_config[f'{r_idx+1}-{c_idx}'] = f'circle_down@{clr_bad}'
298
+ # 指标3:方块箭头
299
+ elif col == '指标3':
300
+ if float(val.replace(',', '')) > 1400:
301
+ icon_config[f'{r_idx+1}-{c_idx}'] = f'square_up@{clr_good}'
302
+ elif float(val.replace(',', '')) > 1380:
303
+ icon_config[f'{r_idx+1}-{c_idx}'] = f'neutral@{clr_warn}'
304
+ else:
305
+ icon_config[f'{r_idx+1}-{c_idx}'] = f'square_down@{clr_bad}'
306
+ # 指标4:三角箭头
307
+ elif col == '指标4':
308
+ if float(val.replace(',', '')) > 1450:
309
+ icon_config[f'{r_idx+1}-{c_idx}'] = f'triangle_up@{clr_good}'
310
+ elif float(val.replace(',', '')) > 1430:
311
+ icon_config[f'{r_idx+1}-{c_idx}'] = f'neutral@{clr_warn}'
312
+ else:
313
+ icon_config[f'{r_idx+1}-{c_idx}'] = f'triangle_down@{clr_bad}'
314
+ # 指标5:表情
315
+ elif col == '指标5':
316
+ if float(val.replace('%', '')) > 90:
317
+ icon_config[f'{r_idx+1}-{c_idx}'] = f'happy_face@{clr_good}'
318
+ elif float(val.replace('%', '')) > 70:
319
+ icon_config[f'{r_idx+1}-{c_idx}'] = f'neutral_face@{clr_warn}'
320
+ else:
321
+ icon_config[f'{r_idx+1}-{c_idx}'] = f'sad_face@{clr_bad}'
322
+ # 指标6:百分比
323
+ elif col == '指标6':
324
+ if float(val.replace('%', '')) > 90:
325
+ icon_config[f'{r_idx+1}-{c_idx}'] = f"percent_{float(val.replace('%', ''))}@{clr_good}"
326
+ elif float(val.replace('%', '')) > 70:
327
+ icon_config[f'{r_idx+1}-{c_idx}'] = f"percent_{float(val.replace('%', ''))}@{clr_warn}"
328
+ else:
329
+ icon_config[f'{r_idx+1}-{c_idx}'] = f"percent_{float(val.replace('%', ''))}@{clr_bad}"
330
+ c_idx += 1
331
+
332
+ cell_dict = {
333
+ 'content': content_list,
334
+ 'back_color': {'r0': '#2e59a7'},
335
+ 'fore_color': {'r0': '#FFFFFF'},
336
+ 'font_path': row_font_path,
337
+ 'icon_config': icon_config,
338
+ }
339
+ img_path = './pic/demo_complex_table_with_icon.png'
340
+ tp.complex_table_pic(df_final.shape[0]+1, df_final.shape[1], title_list, cell_dict, font_path, img_path,
341
+ footnote_list=footnote_list, cell_merge_dict=merge_dict)
342
+
343
+ ```
344
+
66
345
 
67
346
  ### v0.2.1
68
347
  - 更新日期:2024.03.17
@@ -232,7 +511,7 @@ v0.0.4版本的结果:
232
511
  - col_num:int, 必选参数,指定表格的总列数
233
512
  - title_list:list[dict], 必选参数,指定标题内容及设置
234
513
  - cell_dict:dict, 必选参数,指定表格的内容及设置
235
- - font_path:str, 必选参数,指定全局的字体文件路径
514
+ - font_path:str=None, 可选参数,指定全局的字体文件路径;默认使用内置字体(Noto Sans SC,GBK 子集),详见 [v0.3.0 版本说明](#v030)
236
515
  - img_path:str=None, 可选参数,指定图片的生成路径;若不指定,则返回Image对象,可用于 `combine_multiple_pic` 函数,将多个图片合并
237
516
  - footnote_list:list[dict], 可选参数,指定脚注内容及设置
238
517
  - col_width_dict:dict, 可选参数,自定义列的宽度;默认会根据内容及字体大小自动计算
@@ -662,7 +941,7 @@ tp.generate_table_pic(10, 8, title_list=title_list, header_dict=header_dict,
662
941
 
663
942
  ### 修改字体
664
943
 
665
- 目前,标题、表头、数据内容过的字体不能单独设置,当设定字体文件后,所有内容都会使用该字体呈现。
944
+ `font_path` 为可选参数:不指定时使用内置字体(Noto Sans SC,GBK 子集),v0.3.0 起不再按操作系统查找系统字体。目前,标题、表头、数据内容的字体不能单独设置,当设定字体文件后,所有内容都会使用该字体呈现。
666
945
 
667
946
  ```python
668
947
  import tablepic as tp
@@ -726,4 +1005,6 @@ tp.generate_table_pic(10, 8, title_list=title_list, header_dict=header_dict,
726
1005
 
727
1006
  # 许可
728
1007
 
729
- 请参见[许可文件](LICENSE)。
1008
+ 请参见[许可文件](LICENSE)。
1009
+
1010
+ 内置字体 Noto Sans SC 以 SIL Open Font License 1.1 授权,全文随包分发,见 [`src/tablepic/fonts/OFL.txt`](./src/tablepic/fonts/OFL.txt)。
@@ -0,0 +1,41 @@
1
+ [build-system]
2
+ requires = ["setuptools>=61.0"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+
6
+ [project]
7
+ name = "tablepic"
8
+ version = "0.3.0"
9
+ authors = [
10
+ { name="Xin Yan", email="slash.xin@gmail.com" },
11
+ ]
12
+ description = "A package can generate a picture which contains a table."
13
+ readme = "readme_pypi.md"
14
+ requires-python = ">=3.9"
15
+ # pillow: FreeTypeFont.getbbox() 从 8.0.0 起提供;numpy: 1.19.3 起提供 Python 3.9 的 wheel
16
+ dependencies = [
17
+ "pillow>=8.0.0",
18
+ "numpy>=1.19.3",
19
+ ]
20
+ classifiers = [
21
+ "Programming Language :: Python :: 3",
22
+ "License :: OSI Approved :: MIT License",
23
+ "Operating System :: OS Independent",
24
+ ]
25
+
26
+
27
+ [project.urls]
28
+ "Homepage" = "https://github.com/slash-xin/tablepic"
29
+ "Bug Tracker" = "https://github.com/slash-xin/tablepic/issues"
30
+
31
+
32
+ [tool.setuptools.packages.find]
33
+ where = ["src"]
34
+
35
+ # 内置字体随包分发(Noto Sans SC 的 GBK 子集,OFL 1.1),由 tools/build_font.py 生成
36
+ [tool.setuptools.package-data]
37
+ tablepic = ["assets/*.png", "fonts/NotoSansSC-GBK.otf", "fonts/OFL.txt", "fonts/manifest.json"]
38
+
39
+ [tool.pytest.ini_options]
40
+ testpaths = ["tests"]
41
+ pythonpath = ["src"]
@@ -0,0 +1,14 @@
1
+ '''
2
+ Author: xinyan
3
+ Date: 2023-06-13 17:12:19
4
+ LastEditors: xinyan
5
+ LastEditTime: 2024-03-07 16:50:45
6
+ Description: file content
7
+ '''
8
+
9
+
10
+ from .font import FontError, FontNotFoundError, MissingGlyphError
11
+ from .main import generate_table_pic, combine_multiple_pic, complex_table_pic
12
+
13
+ __all__ = ['generate_table_pic', 'combine_multiple_pic', 'complex_table_pic',
14
+ 'FontError', 'FontNotFoundError', 'MissingGlyphError']
@@ -0,0 +1,232 @@
1
+ '''
2
+ 字体的解析、校验与缺字检查。
3
+
4
+ 约定:
5
+ - 不传 font_path 时使用内置字体(Noto Sans SC 的 GBK 子集,覆盖中英文及常用符号),不再按操作系统猜测系统字体。
6
+ - 用户通过 font_path 指定字体文件,只支持文件路径(str 或 os.PathLike)。
7
+ - 渲染前检查字体是否覆盖全部待渲染的字符,缺字时抛出 MissingGlyphError,由用户更换字体文件。
8
+ '''
9
+ import atexit
10
+ import os
11
+ import struct
12
+ import tempfile
13
+ import unicodedata
14
+ from functools import lru_cache
15
+ from importlib import resources
16
+
17
+ from PIL import ImageFont
18
+
19
+ BUNDLED_FONT_NAME = 'NotoSansSC-GBK.otf'
20
+ BUNDLED_FONT_FAMILY = 'Noto Sans SC'
21
+ BUNDLED_FONT_COVERAGE = '中文(简体、繁体常用字)、英文及常用符号'
22
+ # 列出缺字时的上限,超出部分以“等共 N 个”概括
23
+ MAX_LISTED_CHARS = 20
24
+
25
+
26
+ class FontError(Exception):
27
+ '''字体相关错误的基类。'''
28
+
29
+
30
+ class FontNotFoundError(FontError):
31
+ '''字体文件不存在,或无法加载。'''
32
+
33
+
34
+ class MissingGlyphError(FontError):
35
+ '''字体不包含某些待渲染的字符。'''
36
+
37
+
38
+ @lru_cache(maxsize=1)
39
+ def bundled_font_path() -> str:
40
+ '''
41
+ 内置字体文件路径。常规安装下就是包目录里的文件;
42
+ 如果包被打进 zip 之类的归档,则释放到临时文件,进程退出时清理。
43
+ '''
44
+ resource = resources.files(__package__).joinpath('fonts').joinpath(BUNDLED_FONT_NAME)
45
+ try:
46
+ path = os.fspath(resource)
47
+ except TypeError:
48
+ path = str(resource)
49
+ if os.path.isfile(path):
50
+ return path
51
+ fd, path = tempfile.mkstemp(prefix='tablepic-', suffix=f'-{BUNDLED_FONT_NAME}')
52
+ try:
53
+ with os.fdopen(fd, 'wb') as f:
54
+ f.write(resource.read_bytes())
55
+ except BaseException:
56
+ _remove_quietly(path)
57
+ raise
58
+ atexit.register(_remove_quietly, path)
59
+ return path
60
+
61
+
62
+ def _remove_quietly(path: str) -> None:
63
+ try:
64
+ os.remove(path)
65
+ except OSError:
66
+ pass
67
+
68
+
69
+ def resolve_font_path(font_path=None) -> str:
70
+ '''
71
+ 把用户传入的 font_path 解析为可用的字体文件路径。
72
+ :param font_path: None 表示使用内置字体;否则为字体文件路径(str 或 os.PathLike)。
73
+ :return: 字体文件路径。
74
+ :raises FontError: font_path 的类型不受支持。
75
+ :raises FontNotFoundError: 字体文件不存在。
76
+ '''
77
+ if font_path is None:
78
+ return bundled_font_path()
79
+ if isinstance(font_path, (bytes, bytearray)) or hasattr(font_path, 'read'):
80
+ raise FontError(f'font_path 仅支持字体文件路径(str 或 os.PathLike),当前类型:{type(font_path).__name__}')
81
+ try:
82
+ path = os.fspath(font_path)
83
+ except TypeError as e:
84
+ raise FontError(f'font_path 仅支持字体文件路径(str 或 os.PathLike),当前类型:{type(font_path).__name__}') from e
85
+ if not isinstance(path, str):
86
+ raise FontError('font_path 仅支持字体文件路径(str 或 os.PathLike)')
87
+ if not os.path.isfile(path):
88
+ raise FontNotFoundError(f'字体文件不存在:{path}')
89
+ return path
90
+
91
+
92
+ def _truetype(path: str, font_size, index: int) -> ImageFont.FreeTypeFont:
93
+ try:
94
+ return ImageFont.truetype(path, font_size, index=index)
95
+ except OSError as e:
96
+ raise FontNotFoundError(f'无法加载字体文件 {path}:{e}') from e
97
+
98
+
99
+ def load_font(font_path, font_size, index: int = 0) -> ImageFont.FreeTypeFont:
100
+ '''
101
+ 加载字体,每次返回新的字体对象,不做缓存。
102
+ 公开接口使用它:调用方拿到字体对象后可能修改它(例如可变字体的字重轴),不应影响后续渲染。
103
+ :raises FontNotFoundError: 字体无法加载。
104
+ '''
105
+ return _truetype(font_path, font_size, index)
106
+
107
+
108
+ @lru_cache(maxsize=32)
109
+ def _font_object(path: str, mtime_ns: int, file_size: int, font_size, index: int) -> ImageFont.FreeTypeFont:
110
+ return _truetype(path, font_size, index)
111
+
112
+
113
+ def load_font_cached(font_path, font_size, index: int = 0) -> ImageFont.FreeTypeFont:
114
+ '''
115
+ 供渲染过程内部使用:同一个 (字体文件, 字号, face) 在进程内只加载一次,之后复用同一个字体对象。
116
+ font_path 应已经过 resolve_font_path 或 check_font_coverage 校验。
117
+ 缓存键包含文件的修改时间与大小,文件被替换后会重新加载。
118
+ :raises FontNotFoundError: 字体无法加载。
119
+ '''
120
+ path = os.fspath(font_path)
121
+ try:
122
+ stat = os.stat(path)
123
+ except OSError as e:
124
+ raise FontNotFoundError(f'无法加载字体文件 {path}:{e}') from e
125
+ return _font_object(path, stat.st_mtime_ns, stat.st_size, font_size, index)
126
+
127
+
128
+ def _u16(data: bytes, offset: int) -> int:
129
+ return struct.unpack_from('>H', data, offset)[0]
130
+
131
+
132
+ def _u32(data: bytes, offset: int) -> int:
133
+ return struct.unpack_from('>I', data, offset)[0]
134
+
135
+
136
+ def read_codepoints(font_data: bytes, index: int = 0):
137
+ '''
138
+ 解析字体文件的 cmap 表,返回有字形映射的全部 Unicode 码点集合。
139
+ 支持 .ttf / .otf / .ttc 以及 cmap format 4、12、13;无法解析的格式返回 None。
140
+ '''
141
+ try:
142
+ # .ttc:文件头给出各个 face 在文件中的偏移
143
+ if font_data[:4] == b'ttcf':
144
+ base = _u32(font_data, 12 + 4 * index)
145
+ else:
146
+ base = 0
147
+ tables = {}
148
+ for i in range(_u16(font_data, base + 4)):
149
+ tables[font_data[base + 12 + 16 * i: base + 16 + 16 * i]] = _u32(font_data, base + 20 + 16 * i)
150
+ cmap = tables[b'cmap']
151
+ # 优先使用覆盖面最大的子表:Windows 全 Unicode(3,10)、Unicode 全(0,4/0,6)、Windows BMP(3,1)
152
+ priority = {(3, 10): 4, (0, 4): 4, (0, 6): 4, (3, 1): 3, (0, 3): 3, (0, 2): 2, (0, 1): 1}
153
+ best_score, best_offset = -1, None
154
+ for i in range(_u16(font_data, cmap + 2)):
155
+ platform, encoding, offset = _u16(font_data, cmap + 4 + 8 * i), _u16(font_data, cmap + 6 + 8 * i), _u32(font_data, cmap + 8 + 8 * i)
156
+ score = priority.get((platform, encoding), -1)
157
+ if score > best_score and _u16(font_data, cmap + offset) in (4, 12, 13):
158
+ best_score, best_offset = score, cmap + offset
159
+ if best_offset is None:
160
+ return None
161
+ subtable, codepoints = best_offset, set()
162
+ if _u16(font_data, subtable) == 4:
163
+ segment_count = _u16(font_data, subtable + 6) // 2
164
+ ends, starts = subtable + 14, subtable + 16 + _u16(font_data, subtable + 6)
165
+ deltas, ranges = starts + 2 * segment_count, starts + 4 * segment_count
166
+ for i in range(segment_count):
167
+ end, start = _u16(font_data, ends + 2 * i), _u16(font_data, starts + 2 * i)
168
+ delta, range_offset = _u16(font_data, deltas + 2 * i), _u16(font_data, ranges + 2 * i)
169
+ if start == 0xFFFF:
170
+ continue
171
+ if range_offset == 0:
172
+ codepoints.update(c for c in range(start, end + 1) if (c + delta) & 0xFFFF)
173
+ else:
174
+ codepoints.update(c for c in range(start, end + 1)
175
+ if _u16(font_data, ranges + 2 * i + range_offset + 2 * (c - start)))
176
+ else: # format 12 / 13
177
+ for i in range(_u32(font_data, subtable + 12)):
178
+ start, end, glyph = struct.unpack_from('>III', font_data, subtable + 16 + 12 * i)
179
+ codepoints.update(range(start + (glyph == 0), end + 1))
180
+ return frozenset(codepoints)
181
+ except (struct.error, IndexError, KeyError):
182
+ return None
183
+
184
+
185
+ @lru_cache(maxsize=32)
186
+ def _codepoints(path: str, mtime_ns: int, size: int, index: int):
187
+ with open(path, 'rb') as f:
188
+ return read_codepoints(f.read(), index)
189
+
190
+
191
+ def codepoints(font_path: str, index: int = 0):
192
+ '''字体文件中有字形映射的 Unicode 码点集合;无法解析时返回 None。结果按文件缓存,文件变化后自动重新解析。'''
193
+ stat = os.stat(font_path)
194
+ return _codepoints(font_path, stat.st_mtime_ns, stat.st_size, index)
195
+
196
+
197
+ # 空白、控制、格式字符不对应字形,不做检查
198
+ _IGNORED_CATEGORIES = frozenset(('Cc', 'Cf', 'Zs', 'Zl', 'Zp'))
199
+
200
+
201
+ def _describe(chars) -> str:
202
+ shown = ' '.join(f'{ch}(U+{ord(ch):04X})' for ch in chars[:MAX_LISTED_CHARS])
203
+ return shown + (f' 等共 {len(chars)} 个' if len(chars) > MAX_LISTED_CHARS else '')
204
+
205
+
206
+ def check_font_coverage(texts_by_font: dict) -> None:
207
+ '''
208
+ 检查每个字体是否覆盖它要渲染的全部字符。
209
+ :param texts_by_font: {字体文件路径: [文本, ...]},非字符串的文本会被忽略。
210
+ :raises FontNotFoundError: 字体无法加载。
211
+ :raises MissingGlyphError: 字体缺少某些字符。
212
+ '''
213
+ bundled = bundled_font_path()
214
+ for font_path, texts in texts_by_font.items():
215
+ font_path = resolve_font_path(font_path)
216
+ load_font_cached(font_path, 20)
217
+ mapped = codepoints(font_path)
218
+ if mapped is None:
219
+ continue
220
+ chars = sorted({ch for text in texts if isinstance(text, str) for ch in text
221
+ if unicodedata.category(ch) not in _IGNORED_CATEGORIES}, key=ord)
222
+ missing = [ch for ch in chars if ord(ch) not in mapped]
223
+ if not missing:
224
+ continue
225
+ if font_path == bundled:
226
+ raise MissingGlyphError(
227
+ f'内置字体({BUNDLED_FONT_FAMILY},GBK 子集)不支持以下 {len(missing)} 个字符:{_describe(missing)}。'
228
+ f'内置字体覆盖{BUNDLED_FONT_COVERAGE};其他文字(如韩文、emoji)请通过 font_path 参数'
229
+ f'指定包含这些字符的字体文件。')
230
+ raise MissingGlyphError(
231
+ f'字体文件 {font_path} 不支持以下 {len(missing)} 个字符:{_describe(missing)}。'
232
+ f'请更换为包含这些字符的字体文件。')