-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfont_catalog_cross_platform.py
More file actions
248 lines (198 loc) · 7.95 KB
/
Copy pathfont_catalog_cross_platform.py
File metadata and controls
248 lines (198 loc) · 7.95 KB
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
236
237
238
239
240
241
242
243
244
245
246
247
248
#!/usr/bin/env python3
"""
Script to generate an ODT document listing all available system fonts
with their variants (bold, italic, etc.) and Lorem Ipsum sample text.
Cross-platform compatible: Works on Windows, Linux, and macOS.
"""
import os
import sys
import platform
from pathlib import Path
from odf.opendocument import OpenDocumentText
from odf.style import Style, TextProperties, ParagraphProperties
from odf.text import P, Span
import matplotlib.font_manager as fm
def get_output_path(filename="output.txt"):
"""
Bestimmt einen geeigneten Ausgabepfad basierend auf dem Betriebssystem.
Args:
filename (str): Name der Ausgabedatei (z.B. "font_catalog.odt", "report.pdf")
Returns:
str: Vollständiger Pfad zur Ausgabedatei
"""
system = platform.system()
# Versuche verschiedene Speicherorte in dieser Reihenfolge:
possible_locations = []
# 1. Desktop (am besten auffindbar)
desktop = Path.home() / "Desktop"
if desktop.exists():
possible_locations.append(desktop)
# 2. Dokumente-Ordner
documents = Path.home() / "Documents"
if documents.exists():
possible_locations.append(documents)
# 3. Home-Verzeichnis
possible_locations.append(Path.home())
# 4. Aktuelles Verzeichnis (Fallback)
possible_locations.append(Path.cwd())
# Ersten beschreibbaren Pfad verwenden
for location in possible_locations:
try:
# Test ob schreibbar
test_file = location / ".write_test"
test_file.touch()
test_file.unlink()
output_path = location / filename
print(f"Ausgabepfad: {output_path}")
print(f"Betriebssystem: {system}")
return str(output_path)
except (PermissionError, OSError):
continue
# Fallback: aktuelles Verzeichnis (sollte immer funktionieren)
return filename
def get_system_fonts():
"""
Sammelt alle verfügbaren System-Fonts mit ihren Eigenschaften.
Gibt eine Liste von Dictionaries zurück mit Font-Informationen.
"""
fonts = []
seen = set() # Um Duplikate zu vermeiden
# Alle verfügbaren Fonts über matplotlib.font_manager abrufen
font_list = fm.fontManager.ttflist
for font in font_list:
# Eindeutiger Schlüssel für diese Font-Variante
key = (font.name, font.weight, font.style)
if key not in seen:
seen.add(key)
fonts.append({
'name': font.name,
'weight': font.weight, # z.B. 400 (normal), 700 (bold)
'style': font.style, # z.B. 'normal', 'italic', 'oblique'
'fname': font.fname # Pfad zur Font-Datei
})
# Sortieren nach Font-Name und dann nach Eigenschaften
fonts.sort(key=lambda x: (x['name'].lower(), x['weight'], x['style']))
return fonts
def get_variant_description(weight, style):
"""
Erstellt eine lesbare Beschreibung der Font-Variante.
"""
variants = []
# Weight beschreiben
if weight >= 700:
variants.append("Bold")
elif weight <= 300:
variants.append("Light")
elif weight != 400:
variants.append(f"Weight-{weight}")
# Style beschreiben
if style == 'italic':
variants.append("Italic")
elif style == 'oblique':
variants.append("Oblique")
if not variants:
return "Regular"
return " ".join(variants)
def create_font_list_textfile(fonts, output_path):
"""
Erstellt eine einfache Textdatei mit allen Font-Namen.
"""
print(f"\nErzeuge Font-Liste als Textdatei...")
with open(output_path, 'w', encoding='utf-8') as f:
f.write(f"Font-Liste für {platform.system()}\n")
f.write(f"Anzahl Fonts: {len(fonts)}\n")
f.write(f"Generiert am: {__import__('datetime').datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n")
f.write("=" * 80 + "\n\n")
for font_info in fonts:
font_name = font_info['name']
weight = font_info['weight']
style_name = font_info['style']
variant = get_variant_description(weight, style_name)
f.write(f"{font_name} ({variant})\n")
print(f"✓ Font-Liste gespeichert!")
print(f" Speicherort: {os.path.abspath(output_path)}")
def create_odt_document(fonts, output_path):
"""
Erstellt ein ODT-Dokument mit allen Fonts und ihren Varianten.
"""
doc = OpenDocumentText()
# Lorem Ipsum Text (80 Zeichen)
lorem_ipsum = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempo"
print(f"\nErzeuge ODT-Dokument mit {len(fonts)} Font-Varianten...")
for idx, font_info in enumerate(fonts):
font_name = font_info['name']
weight = font_info['weight']
style_name = font_info['style']
variant = get_variant_description(weight, style_name)
# Style für diesen Font erstellen
style_id = f"font_style_{idx}"
font_style = Style(name=style_id, family="paragraph")
# Text-Eigenschaften setzen
text_props = TextProperties()
text_props.setAttribute('fontfamily', font_name)
text_props.setAttribute('fontfamilygeneric', 'swiss')
text_props.setAttribute('fontpitch', 'variable')
# Weight setzen
if weight >= 700:
text_props.setAttribute('fontweight', 'bold')
elif weight <= 300:
text_props.setAttribute('fontweight', '300')
# Style setzen
if style_name == 'italic' or style_name == 'oblique':
text_props.setAttribute('fontstyle', 'italic')
text_props.setAttribute('fontsize', '11pt')
font_style.addElement(text_props)
doc.automaticstyles.addElement(font_style)
# Absatz mit Font-Name und Variante
p = P(stylename=font_style)
p.addText(f"{font_name} ({variant}): {lorem_ipsum}")
doc.text.addElement(p)
# Fortschrittsanzeige
if (idx + 1) % 50 == 0:
print(f" {idx + 1}/{len(fonts)} Fonts verarbeitet...")
# Dokument speichern
doc.save(output_path)
print(f"\n✓ Dokument erfolgreich gespeichert!")
print(f" Speicherort: {os.path.abspath(output_path)}")
print(f" Anzahl Font-Varianten: {len(fonts)}")
def main():
print("=" * 60)
print("Font-Katalog Generator (systemunabhängig)")
print("=" * 60)
# Systemunabhängigen Ausgabepfad bestimmen
os_name = platform.system().lower() # z.B. 'windows', 'linux', 'darwin'
output_file_odt = get_output_path("font_catalog.odt")
output_file_txt = get_output_path(f"font_list_{os_name}.txt")
print("\nSammle verfügbare System-Fonts...")
fonts = get_system_fonts()
if not fonts:
print("FEHLER: Keine Fonts gefunden!")
return 1
print(f"Gefunden: {len(fonts)} Font-Varianten")
# Textdatei mit Font-Liste erstellen
create_font_list_textfile(fonts, output_file_txt)
# ODT-Dokument erstellen
create_odt_document(fonts, output_file_odt)
# Öffnungshinweis
print(f"\nDu kannst die Dateien jetzt öffnen mit:")
if platform.system() == "Windows":
print(f" start {os.path.abspath(output_file_odt)}")
print(f" start {os.path.abspath(output_file_txt)}")
elif platform.system() == "Darwin": # macOS
print(f" open {os.path.abspath(output_file_odt)}")
print(f" open {os.path.abspath(output_file_txt)}")
else: # Linux
print(f" xdg-open {os.path.abspath(output_file_odt)}")
print(f" xdg-open {os.path.abspath(output_file_txt)}")
return 0
if __name__ == "__main__":
try:
exit(main())
except KeyboardInterrupt:
print("\n\nAbgebrochen durch Benutzer.")
exit(1)
except Exception as e:
print(f"\nFEHLER: {e}")
import traceback
traceback.print_exc()
exit(1)