motorradig2027/tools/build_install_docx.py

769 lines
27 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#!/usr/bin/env python3
"""Baut die Installationsanleitung als Word-Dokument.
Erzeugt zuerst sechs schematische Screenshots (nachgezeichnet, keine echten
Screenshots, keine Markenlogos) und setzt daraus über HTML und LibreOffice ein
DOCX zusammen:
python3 tools/build_install_docx.py
Ergebnis: docs/App-Installation_MotorradIG.docx
Voraussetzungen: Pillow und LibreOffice (soffice).
"""
import os
import re
import shutil
import subprocess
import sys
import tempfile
import zipfile
REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
DOC_OUT = os.path.join(REPO, 'docs', 'App-Installation_MotorradIG.docx')
TITLE = 'Motorrad-IG als App auf dem Handy'
SUBTITLE = 'Installationsanleitung für iPhone, iPad und Android'
DATE = 'Stand: 12. November 2026'
IMG_WIDTH, IMG_HEIGHT = 360, 620 # 360 px ≈ 9,5 cm bei 96 dpi
# --------------------------------------------------------------------------
# Schematische Screenshots
# --------------------------------------------------------------------------
import math
from PIL import Image, ImageDraw, ImageFont
W, H = 900, 1560
FONT_R = '/usr/share/fonts/truetype/liberation/LiberationSans-Regular.ttf'
FONT_B = '/usr/share/fonts/truetype/liberation/LiberationSans-Bold.ttf'
BLACK = (17, 17, 17)
GRAY = (95, 99, 104)
LIGHT = (241, 243, 244)
LINE = (218, 220, 224)
WHITE = (255, 255, 255)
BLUE_IOS = (10, 132, 255)
BLUE_ANDROID = (26, 115, 232)
RED = (217, 48, 37)
DARK = (52, 58, 64)
SHEET_GRAY = (232, 234, 237)
_cache = {}
def font(size, bold=False):
key = (size, bold)
if key not in _cache:
_cache[key] = ImageFont.truetype(FONT_B if bold else FONT_R, size)
return _cache[key]
def text(d, xy, s, size=36, bold=False, fill=BLACK, anchor='la'):
d.text(xy, s, font=font(size, bold), fill=fill, anchor=anchor)
def screen():
img = Image.new('RGB', (W, H), WHITE)
return img, ImageDraw.Draw(img)
def status_bar(d, android=False):
text(d, (70, 50), '9:41', 36, True, BLACK, 'lm')
x = 640
for i in range(4):
h = 12 + i * 8
d.rounded_rectangle((x + i * 22, 60 - h, x + i * 22 + 14, 60), 3, fill=BLACK)
if android:
d.arc((720, 26, 800, 106), 205, 335, fill=BLACK, width=8)
d.arc((736, 42, 784, 90), 205, 335, fill=BLACK, width=8)
d.ellipse((754, 58, 766, 70), fill=BLACK)
else:
d.arc((730, 34, 800, 104), 215, 325, fill=BLACK, width=7)
d.arc((745, 49, 785, 89), 215, 325, fill=BLACK, width=7)
d.ellipse((758, 62, 772, 76), fill=BLACK)
d.rounded_rectangle((815, 38, 868, 74), 8, outline=BLACK, width=4)
d.rounded_rectangle((821, 44, 850, 68), 3, fill=BLACK)
d.line((872, 50, 872, 62), fill=BLACK, width=5)
def site_page(d, top, bottom=1400):
"""Abstrakter Seiteninhalt der Motorrad-IG."""
d.rectangle((0, top, W, top + 120), fill=DARK)
text(d, (56, top + 60), 'Motorrad-IG', 44, True, WHITE, 'lm')
d.ellipse((W - 130, top + 22, W - 66, top + 86), outline=(200, 205, 210), width=4)
d.line((W - 112, top + 100, W - 84, top + 100), fill=(200, 205, 210), width=4)
text(d, (56, top + 165), 'Tourenplan', 50, True, BLACK, 'la')
cards = [('Sauerland-Runde', 'Sa 12.06.2027 · 8 Plätze frei'),
('Eifel am Sonntag', 'So 20.06.2027 · 3 Plätze frei')]
y = top + 240
for title, meta in cards:
d.rounded_rectangle((56, y, W - 56, y + 170), 24, outline=LINE, width=3)
text(d, (96, y + 58), title, 38, True)
text(d, (96, y + 112), meta, 28, False, GRAY)
d.rounded_rectangle((W - 230, y + 52, W - 96, y + 122), 16, fill=LIGHT)
text(d, (W - 163, y + 87), 'Details', 28, False, BLUE_ANDROID, 'mm')
y += 200
text(d, (56, y + 26), 'Nächste Aktivitäten', 42, True, BLACK)
events = [('Mi 24.06.2027', 'Feierabendrunde ab 18 Uhr'),
('Sa 11.07.2027', 'Stammtisch im Vereinsheim')]
y += 90
for day, label in events:
d.line((56, y, W - 56, y), fill=LINE, width=3)
text(d, (56, y + 42), day, 28, False, GRAY, 'lm')
text(d, (330, y + 42), label, 30, False, BLACK, 'lm')
y += 84
def highlight(img, box, radius=24, width=7):
layer = Image.new('RGBA', img.size, (0, 0, 0, 0))
ImageDraw.Draw(layer).rounded_rectangle(box, radius, outline=RED + (255,), width=width)
img.paste(Image.alpha_composite(img.convert('RGBA'), layer).convert('RGB'), (0, 0))
def arrow(d, start, end, color=RED, width=10, head=30):
(x1, y1), (x2, y2) = start, end
ang = math.atan2(y2 - y1, x2 - x1)
sx = x2 - math.cos(ang) * head * 0.85
sy = y2 - math.sin(ang) * head * 0.85
d.line((x1, y1, sx, sy), fill=color, width=width)
d.polygon([
(x2, y2),
(x2 - math.cos(ang - 0.45) * head, y2 - math.sin(ang - 0.45) * head),
(x2 - math.cos(ang + 0.45) * head, y2 - math.sin(ang + 0.45) * head),
], fill=color)
def dim(img, y0=0, alpha=110):
layer = Image.new('RGBA', img.size, (0, 0, 0, 0))
ImageDraw.Draw(layer).rectangle((0, y0, W, H), fill=(0, 0, 0, alpha))
return Image.alpha_composite(img.convert('RGBA'), layer).convert('RGB')
def icon_share(d, cx, cy, color):
d.rounded_rectangle((cx - 26, cy - 12, cx + 26, cy + 34), 6, outline=color, width=5)
d.line((cx, cy - 46, cx, cy + 6), fill=color, width=5)
d.line((cx - 18, cy - 28, cx, cy - 46), fill=color, width=5)
d.line((cx + 18, cy - 28, cx, cy - 46), fill=color, width=5)
def icon_bookmark(d, cx, cy, color):
d.line((cx - 18, cy - 32, cx - 18, cy + 34), fill=color, width=5)
d.line((cx + 18, cy - 32, cx + 18, cy + 34), fill=color, width=5)
d.line((cx - 18, cy - 32, cx + 18, cy - 32), fill=color, width=5)
d.line((cx - 18, cy + 34, cx, cy + 10), fill=color, width=5)
d.line((cx + 18, cy + 34, cx, cy + 10), fill=color, width=5)
def icon_tabs(d, cx, cy, color):
d.rounded_rectangle((cx - 14, cy - 30, cx + 26, cy + 22), 6, outline=color, width=5)
d.rounded_rectangle((cx - 26, cy - 20, cx + 12, cy + 32), 6, outline=color, width=5)
def chevron(d, cx, cy, color, direction=1, size=26):
d.line((cx + size * direction, cy - size, cx - size * direction, cy), fill=color, width=6)
d.line((cx + size * direction, cy + size, cx - size * direction, cy), fill=color, width=6)
def ios_frame(d):
status_bar(d, android=False)
d.rounded_rectangle((56, 100, W - 56, 190), 45, fill=LIGHT)
d.rounded_rectangle((110, 130, 134, 162), 6, outline=GRAY, width=4)
text(d, (160, 145), 'motorrad-ig.de', 36, False, BLACK, 'lm')
# --------------------------------------------------------------------------
# iOS
# --------------------------------------------------------------------------
def ios_1():
img, d = screen()
ios_frame(d)
site_page(d, 210)
d.rectangle((0, H - 150, W, H), fill=(249, 249, 249))
d.line((0, H - 150, W, H - 150), fill=LINE, width=3)
y = H - 75
chevron(d, 110, y, GRAY, direction=1)
chevron(d, 280, y, GRAY, direction=-1)
icon_share(d, 450, y, BLUE_IOS)
icon_bookmark(d, 620, y, BLUE_IOS)
icon_tabs(d, 790, y, BLUE_IOS)
highlight(img, (382, H - 143, 518, H - 7), radius=30, width=7)
arrow(d, (690, H - 250), (520, H - 120))
return img
def ios_2():
img, d = screen()
ios_frame(d)
site_page(d, 210)
d.rectangle((0, H - 150, W, H), fill=(249, 249, 249))
d.line((0, H - 150, W, H - 150), fill=LINE, width=3)
img = dim(img, 0, 115)
d = ImageDraw.Draw(img)
top = 420
d.rounded_rectangle((0, top, W, H), 40, fill=WHITE)
d.rounded_rectangle((410, top + 26, 490, top + 36), 5, fill=LINE)
text(d, (56, top + 62), 'Teilen', 40, True)
x = 90
for name in ['Nachrichten', 'Mail', 'Notizen', 'Mehr']:
d.rounded_rectangle((x, top + 130, x + 120, top + 250), 28, fill=SHEET_GRAY)
d.ellipse((x + 45, top + 165, x + 75, top + 195), fill=(174, 180, 186))
text(d, (x + 60, top + 292), name, 28, False, GRAY, 'mm')
x += 200
d.line((56, top + 350, W - 56, top + 350), fill=LINE, width=3)
actions = ['Kopieren', 'Als Lesezeichen sichern', 'Zum Home-Bildschirm',
'Zum Schnellzugriff', 'In Dateien sichern', 'Drucken']
for i, label in enumerate(actions):
y = top + 390 + i * 118
d.rounded_rectangle((80, y, 146, y + 66), 16, fill=SHEET_GRAY)
d.ellipse((100, y + 20, 126, y + 46), fill=(174, 180, 186))
text(d, (176, y + 33), label, 34, False, BLACK, 'lm')
target_top = top + 390 + 2 * 118 - 16
highlight(img, (52, target_top, W - 52, target_top + 98), radius=18, width=7)
arrow(d, (878, target_top - 120), (795, target_top + 34))
return img
def ios_3():
img, d = screen()
ios_frame(d)
site_page(d, 210)
img = dim(img, 0, 115)
d = ImageDraw.Draw(img)
d.rounded_rectangle((56, 150, W - 56, 760), 40, fill=WHITE)
text(d, (450, 205), 'Zum Home-Bildschirm', 30, True, BLACK, 'mm')
text(d, (96, 262), 'Abbrechen', 30, False, BLUE_IOS, 'lm')
text(d, (W - 96, 262), 'Hinzufügen', 30, True, BLUE_IOS, 'rm')
d.line((56, 305, W - 56, 305), fill=LINE, width=3)
d.rounded_rectangle((90, 355, 320, 585), 42, fill=(13, 17, 23))
text(d, (205, 470), 'IG', 92, True, WHITE, 'mm')
text(d, (370, 405), 'Motorrad IG', 40, True)
d.rounded_rectangle((370, 450, W - 110, 515), 10, fill=LIGHT)
text(d, (394, 483), 'Motorrad IG', 32, False, BLACK, 'lm')
text(d, (370, 550), 'https://motorrad-ig.de', 30, False, GRAY)
highlight(img, (632, 226, W - 58, 296), radius=16, width=7)
arrow(d, (590, 400), (700, 306))
return img
# --------------------------------------------------------------------------
# Android
# --------------------------------------------------------------------------
def android_chrome_bar(d):
d.rectangle((0, 96, W, 210), fill=WHITE)
d.rounded_rectangle((36, 116, 630, 194), 39, fill=LIGHT)
d.rounded_rectangle((78, 140, 100, 170), 5, outline=GRAY, width=4)
text(d, (128, 155), 'motorrad-ig.de', 34, False, BLACK, 'lm')
d.rounded_rectangle((668, 138, 718, 174), 8, outline=GRAY, width=4)
text(d, (693, 156), '2', 28, False, GRAY, 'mm')
for i in range(3):
d.ellipse((806, 128 + i * 24, 820, 142 + i * 24), fill=(60, 64, 67))
def android_frame(d):
status_bar(d, android=True)
android_chrome_bar(d)
def android_1():
img, d = screen()
android_frame(d)
site_page(d, 220, bottom=H)
highlight(img, (788, 112, 838, 200), radius=14, width=7)
arrow(d, (640, 275), (782, 190))
return img
def android_2():
img, d = screen()
android_frame(d)
site_page(d, 220, bottom=H)
img = dim(img, 0, 120)
d = ImageDraw.Draw(img)
top = 610
d.rounded_rectangle((0, top, W, H), 36, fill=WHITE)
rows = ['Neuer Tab', 'Neuer Inkognito-Tab', 'Lesezeichen', 'Verlauf und Downloads',
None, 'Teilen …', 'App installieren', None, 'Einstellungen']
y = top + 40
target = None
for row in rows:
if row is None:
d.line((56, y + 12, W - 56, y + 12), fill=LINE, width=3)
y += 26
continue
text(d, (80, y + 42), row, 36, False, BLACK, 'lm')
if row == 'App installieren':
target = (44, y + 4, W - 44, y + 82)
y += 105
highlight(img, target, radius=18, width=7)
arrow(d, (872, target[1] - 120), (812, target[1] + 8))
return img
def android_3():
img, d = screen()
android_frame(d)
site_page(d, 220, bottom=H)
img = dim(img, 0, 120)
d = ImageDraw.Draw(img)
top = 1040
d.rounded_rectangle((0, top, W, H), 36, fill=WHITE)
d.rounded_rectangle((70, top + 60, 230, top + 220), 34, fill=(13, 17, 23))
text(d, (150, top + 140), 'IG', 64, True, WHITE, 'mm')
text(d, (270, top + 95), 'Motorrad IG', 42, True)
text(d, (270, top + 155), 'motorrad-ig.de', 30, False, GRAY)
text(d, (70, top + 280), 'Diese Website als App installieren?', 34, False, BLACK)
text(d, (560, top + 400), 'Abbrechen', 34, False, GRAY, 'rm')
text(d, (W - 80, top + 400), 'Installieren', 36, True, BLUE_ANDROID, 'rm')
highlight(img, (600, top + 362, W - 50, top + 438), radius=16, width=7)
arrow(d, (878, top + 190), (838, top + 350))
return img
# --------------------------------------------------------------------------
# Inhalt des Dokuments
# --------------------------------------------------------------------------
INTRO = """
<p>Die Website <b>motorrad-ig.de</b> lässt sich wie eine App auf dem
Startbildschirm des Handys installieren. Danach startet sie über ein eigenes
Symbol und ohne Adressleiste. Ein Besuch im App Store oder bei Google Play ist
nicht nötig, und es entstehen keine Kosten.</p>
<p>Die Bilder in dieser Anleitung sind <b>schematische Darstellungen</b>. Je
nach iOS- oder Chrome-Version können die Bezeichnungen leicht abweichen. Die
<b>rot markierten Stellen</b> zeigen jeweils, was angetippt werden muss.</p>
<p class="box"><b>Das Wichtigste in Kürze:</b> kein App Store, kein Google Play –
die Installation läuft im Browser. Auf dem iPhone ausschließlich mit
<b>Safari</b>, auf Android mit <b>Chrome</b>. Dauer: etwa eine Minute.</p>
"""
IOS_STEPS = [
dict(
title='Schritt 1 – Seite in Safari öffnen',
text='Öffne <b>Safari</b> und rufe <b>motorrad-ig.de</b> auf. Tippe dann '
'unten in der Leiste auf das <b>Teilen-Symbol</b> – das ist das '
'Kästchen mit dem Pfeil nach oben. Auf dem iPad sitzt dieses Symbol '
'oben neben der Adresszeile.',
img='ios-1-teilen-symbol.png',
cap='Bild 1: Teilen-Symbol in Safari antippen',
),
dict(
title='Schritt 2 – „Zum Home-Bildschirm“ wählen',
text='Es öffnet sich das Teilen-Menü von unten. Tippe darin auf '
'<b>„Zum Home-Bildschirm“</b>. Der Eintrag steht manchmal weiter '
'unten in der Liste – dann einfach etwas nach oben scrollen.',
img='ios-2-teilen-menue.png',
cap='Bild 2: Eintrag „Zum Home-Bildschirm“ im Teilen-Menü',
),
dict(
title='Schritt 3 – „Hinzufügen“ bestätigen',
text='Tippe oben rechts auf <b>„Hinzufügen“</b>. Der Name „Motorrad IG“ '
'ist schon eingetragen und muss nicht geändert werden. Danach liegt '
'das Symbol auf dem Startbildschirm.',
img='ios-3-hinzufuegen.png',
cap='Bild 3: Mit „Hinzufügen“ die Installation abschließen',
),
]
ANDROID_STEPS = [
dict(
title='Schritt 1 – Seite in Chrome öffnen',
text='Öffne <b>Chrome</b> und rufe <b>motorrad-ig.de</b> auf. Tippe dann '
'oben rechts auf die <b>drei Punkte</b>, um das Menü zu öffnen.',
img='android-1-menue.png',
cap='Bild 4: Drei-Punkte-Menü in Chrome öffnen',
),
dict(
title='Schritt 2 – „App installieren“ wählen',
text='Tippe im Menü auf <b>„App installieren“</b>. In älteren '
'Chrome-Versionen heißt der Eintrag <b>„Zum Startbildschirm '
'hinzufügen“</b> – beide führen zum selben Ergebnis.',
img='android-2-app-installieren.png',
cap='Bild 5: Eintrag „App installieren“ im Chrome-Menü',
),
dict(
title='Schritt 3 – Installation bestätigen',
text='Bestätige mit <b>„Installieren“</b>. Das Symbol „Motorrad IG“ '
'erscheint auf dem Startbildschirm und im App-Menü des Handys.',
img='android-3-bestaetigen.png',
cap='Bild 6: Installation mit „Installieren“ bestätigen',
),
]
AFTER = """
<ul>
<li><b>Symbol:</b> „Motorrad IG“ liegt auf dem Startbildschirm, bei Android
zusätzlich im App-Menü.</li>
<li><b>Start:</b> Die App öffnet sich ohne Adressleiste und merkt sich die
Anmeldung.</li>
<li><b>Benachrichtigungen:</b> Auf dem iPhone sind Push-Benachrichtigungen
ausschließlich in der installierten App möglich, nicht im Safari-Tab.
Beim ersten Start den Datenschutzdialog bestätigen und im eigenen Profil
die Benachrichtigungen einschalten.</li>
<li><b>Aktualisierungen:</b> Die App lädt neue Inhalte automatisch; ein
erneuter Download ist nicht nötig.</li>
<li><b>Entfernen:</b> Symbol lange drücken und „App entfernen“ (iPhone) bzw.
„Deinstallieren“ oder „Vom Startbildschirm entfernen“ (Android)
auswählen.</li>
</ul>
"""
PROBLEMS = """
<ul>
<li><b>„Zum Home-Bildschirm“ fehlt im Teilen-Menü:</b> Die Seite erst
vollständig laden lassen. Im privaten Modus (Inkognito) wird der Eintrag
nicht angeboten.</li>
<li><b>Kein „App installieren“ in Chrome:</b> Stattdessen „Zum Startbildschirm
hinzufügen“ wählen. Erscheint auch das nicht, ist die Seite noch nicht
vollständig geladen.</li>
<li><b>Das Symbol öffnet den Browser statt der App:</b> Die alte Verknüpfung
löschen und die Installation einmal neu durchführen.</li>
<li><b>Keine Benachrichtigungen:</b> In den iPhone-Einstellungen unter
„Mitteilungen“ → „Motorrad IG“ erlauben und anschließend im Profil der App
den Haken bei den Benachrichtigungen setzen.</li>
<li><b>iPad:</b> Das Teilen-Symbol sitzt oben neben der Adresszeile; der
Ablauf ist sonst identisch.</li>
</ul>
"""
CSS = """
@page { size: A4; margin: 2.4cm 2.2cm; }
body { font-family: "Calibri", "Carlito", sans-serif; font-size: 10.5pt;
line-height: 1.4; color: #111111; }
h1 { font-size: 22pt; margin: 0 0 4pt 0; color: #1f2933; }
h2 { font-size: 15pt; margin: 16pt 0 8pt 0; color: #1f2933;
border-bottom: 1px solid #c8ccd0; padding-bottom: 3pt; }
h3 { font-size: 11.5pt; margin: 12pt 0 4pt 0; color: #1f2933; }
p { margin: 0 0 7pt 0; }
ul { margin: 0 0 7pt 0; padding-left: 18pt; }
li { margin-bottom: 4pt; }
b { font-weight: bold; }
.subtitle { font-size: 12.5pt; color: #444444; margin: 0 0 2pt 0; }
.meta { font-size: 9.5pt; color: #666666; margin: 0 0 16pt 0;
border-bottom: 2px solid #1f2933; padding-bottom: 8pt; }
.fig { text-align: center; margin: 6pt 0 2pt 0; }
.cap { text-align: center; font-size: 9pt; font-style: italic; color: #555555;
margin: 0 0 6pt 0; }
.box { background-color: #f4f5f6; border-left: 3pt solid #1f2933;
padding: 7pt 9pt; margin: 12pt 0 0 0; }
.note { font-size: 9.5pt; color: #444444; background-color: #f4f5f6;
border-left: 3pt solid #9aa0a6; padding: 6pt 8pt; margin: 0 0 9pt 0; }
"""
def figure(step: dict) -> str:
return (
'<div class="step">\n'
'<h3>%s</h3>\n<p>%s</p>\n'
'<p class="fig"><img src="%s" width="%d" height="%d"></p>\n'
'<p class="cap">%s</p>\n'
'</div>\n'
% (step['title'], step['text'], step['img'], IMG_WIDTH, IMG_HEIGHT, step['cap'])
)
def build_html() -> str:
parts = [
'<h1>%s</h1>' % TITLE,
'<p class="subtitle">%s</p>' % SUBTITLE,
'<p class="meta">%s</p>' % DATE,
INTRO,
'<h2>iPhone und iPad (Safari)</h2>',
'<p class="note"><b>Wichtig:</b> Auf dem iPhone funktioniert die '
'Installation nur in <b>Safari</b>. Chrome oder Firefox bieten diesen '
'Menüpunkt auf iOS nicht an.</p>',
figure(IOS_STEPS[0]),
figure(IOS_STEPS[1]),
figure(IOS_STEPS[2]),
'<h2>Android (Chrome)</h2>',
'<p class="note"><b>Voraussetzung:</b> Chrome oder ein anderer '
'Chromium-Browser wie Edge oder Samsung Internet.</p>',
figure(ANDROID_STEPS[0]),
figure(ANDROID_STEPS[1]),
figure(ANDROID_STEPS[2]),
'<h2>Nach der Installation</h2>',
AFTER,
'<h2>Wenn etwas nicht klappt</h2>',
PROBLEMS,
'<p class="cap">Fragen zur Installation? Mail an ig@fischergruppe.de</p>',
]
body = '\n'.join(parts)
return ('<!DOCTYPE html>\n<html lang="de">\n<head>\n<meta charset="utf-8">\n'
'<title>%s</title>\n<style>%s</style>\n</head>\n<body>\n%s\n</body>\n</html>\n'
% (TITLE, CSS, body))
def keep_together(docx_path: str) -> int:
"""Setzt "Mit nächstem Absatz zusammenhalten" für Überschriften und Bilder.
Ohne das rutscht z. B. die Schritt-Überschrift an das Seitenende und das
Bild auf die nächste Seite. Word und LibreOffice halten den Block dann
geschlossen und schieben ihn gemeinsam weiter.
"""
with zipfile.ZipFile(docx_path) as zin:
items = {i.filename: zin.read(i.filename) for i in zin.infolist()}
name = 'word/document.xml'
xml = items[name].decode('utf-8')
spans = [(m.start(), m.end()) for m in re.finditer(r'<w:p(?:\s[^>]*)?>.*?</w:p>', xml, re.S)]
styles = []
for start, end in spans:
paragraph = xml[start:end]
found = re.search(r'<w:pStyle w:val="([^"]+)"', paragraph)
styles.append(found.group(1) if found else '')
inserts = []
count = 0
for idx, (start, end) in enumerate(spans):
paragraph = xml[start:end]
if '<w:keepNext/>' in paragraph:
continue
style = styles[idx]
previous = styles[idx - 1] if idx > 0 else ''
keep = (
style in ('Heading1', 'Heading2', 'Heading3')
or '<w:drawing>' in paragraph
or 'F4F5F6' in paragraph # Hinweis-Kasten
or previous == 'Heading3' # Fließtext direkt unter dem Schritt
)
if not keep:
continue
pos = paragraph.find('<w:pPr>')
if pos == -1:
continue
head = re.match(r'<w:pPr>(?:<w:pStyle [^>]*/>)?', paragraph[pos:])
if head is None:
continue
inserts.append(start + pos + head.end())
count += 1
# Jeder Hauptabschnitt beginnt auf einer neuen Seite.
breaks = []
for idx, (start, end) in enumerate(spans):
if styles[idx] == 'Heading2' and '<w:pageBreakBefore/>' not in xml[start:end]:
paragraph = xml[start:end]
pos = paragraph.find('<w:pPr>')
head = re.match(r'<w:pPr>(?:<w:pStyle [^>]*/>)?', paragraph[pos:])
if head is not None:
breaks.append(start + pos + head.end())
# Gleiche Einfügestelle kann beides verlangen (z. B. Heading2). Reihenfolge
# laut OOXML-Schema: keepNext vor pageBreakBefore.
combined = {}
for pos in inserts:
combined.setdefault(pos, []).append('<w:keepNext/>')
for pos in breaks:
combined.setdefault(pos, []).append('<w:pageBreakBefore/>')
for pos in sorted(combined, reverse=True):
xml = xml[:pos] + ''.join(combined[pos]) + xml[pos:]
items[name] = xml.encode('utf-8')
tmp = docx_path + '.tmp'
with zipfile.ZipFile(tmp, 'w', zipfile.ZIP_DEFLATED) as zout:
for key, data in items.items():
zout.writestr(key, data)
shutil.move(tmp, docx_path)
return count
def to_a4(docx_path: str) -> None:
"""Setzt A4 und die Ränder; der HTML-Import von LibreOffice nutzt Letter."""
tmp = docx_path + '.tmp'
with zipfile.ZipFile(docx_path) as zin, zipfile.ZipFile(tmp, 'w', zipfile.ZIP_DEFLATED) as zout:
for item in zin.infolist():
data = zin.read(item.filename)
if item.filename == 'word/document.xml':
xml = data.decode('utf-8')
xml = re.sub(r'<w:pgSz[^/]*/>',
'<w:pgSz w:w="11906" w:h="16838"/>', xml, count=1)
xml = re.sub(r'<w:pgMar[^/]*/>',
'<w:pgMar w:top="1361" w:right="1247" w:bottom="1361" '
'w:left="1247" w:header="709" w:footer="709" w:gutter="0"/>',
xml, count=1)
data = xml.encode('utf-8')
zout.writestr(item, data)
shutil.move(tmp, docx_path)
def embed_images(docx_path: str) -> int:
"""Bettet extern verlinkte Bilder fest ein.
Der HTML-Import von LibreOffice legt lokale Grafiken als externe Links ab
(TargetMode="External"). Für ein weitergegebenes Dokument müssen sie im
DOCX liegen, sonst sind sie auf anderen Rechnern nicht sichtbar.
"""
with zipfile.ZipFile(docx_path) as zin:
items = {i.filename: zin.read(i.filename) for i in zin.infolist()}
rels_name = 'word/_rels/document.xml.rels'
rels = items[rels_name].decode('utf-8')
media = 0
extensions = set()
linked_ids = []
def replace(match):
nonlocal media
rel = match.group(0)
if 'TargetMode="External"' not in rel or '/image"' not in rel:
return rel
target = re.search(r'Target="([^"]+)"', rel).group(1)
if not target.startswith('file://'):
return rel
path = target[len('file://'):]
if not os.path.isfile(path):
return rel
media += 1
ext = os.path.splitext(path)[1].lower().lstrip('.')
extensions.add(ext)
name = 'word/media/image%d.%s' % (media, ext)
with open(path, 'rb') as fh:
items[name] = fh.read()
linked_ids.append(re.search(r'Id="([^"]+)"', rel).group(1))
rel = rel.replace(target, 'media/image%d.%s' % (media, ext))
rel = re.sub(r'\s*TargetMode="External"', '', rel)
return rel
new_rels = re.sub(r'<Relationship [^>]*/>', replace, rels)
content_name = '[Content_Types].xml'
content = items[content_name].decode('utf-8')
for ext in extensions:
if 'Extension="%s"' % ext not in content:
content = content.replace(
'</Types>',
'<Default Extension="%s" ContentType="image/%s"/></Types>'
% (ext, 'jpeg' if ext in ('jpg', 'jpeg') else ext),
)
items[rels_name] = new_rels.encode('utf-8')
items[content_name] = content.encode('utf-8')
# Ein externes Bild wird über r:link referenziert; eingebettet braucht es
# r:embed, sonst sucht Word weiterhin eine Datei außerhalb des Dokuments.
doc_name = 'word/document.xml'
document = items[doc_name].decode('utf-8')
for rid in linked_ids:
document = document.replace('r:link="%s"' % rid, 'r:embed="%s"' % rid)
items[doc_name] = document.encode('utf-8')
tmp = docx_path + '.tmp'
with zipfile.ZipFile(tmp, 'w', zipfile.ZIP_DEFLATED) as zout:
for name, data in items.items():
zout.writestr(name, data)
shutil.move(tmp, docx_path)
return media
def main() -> int:
work = tempfile.mkdtemp(prefix='install-docx-', dir='/tmp/opencode')
shots = os.path.join(work, 'shots')
os.makedirs(shots, exist_ok=True)
images = {
'ios-1-teilen-symbol.png': ios_1,
'ios-2-teilen-menue.png': ios_2,
'ios-3-hinzufuegen.png': ios_3,
'android-1-menue.png': android_1,
'android-2-app-installieren.png': android_2,
'android-3-bestaetigen.png': android_3,
}
for name, fn in images.items():
fn().save(os.path.join(shots, name), optimize=True)
html_path = os.path.join(shots, 'anleitung.html')
open(html_path, 'w', encoding='utf-8').write(build_html())
profile = 'file://' + os.path.join(work, 'lo-profile')
result = subprocess.run([
'soffice', '--headless', '--norestore',
'-env:UserInstallation=' + profile,
'--convert-to', 'docx:MS Word 2007 XML',
'--outdir', work, html_path,
], capture_output=True, text=True, timeout=300)
produced = os.path.join(work, 'anleitung.docx')
if not os.path.isfile(produced):
print(result.stdout + result.stderr, file=sys.stderr)
return 1
to_a4(produced)
embedded = embed_images(produced)
kept = keep_together(produced)
os.makedirs(os.path.dirname(DOC_OUT), exist_ok=True)
shutil.move(produced, DOC_OUT)
print('geschrieben:', DOC_OUT, os.path.getsize(DOC_OUT), 'Bytes,',
embedded, 'Bilder eingebettet,', kept, 'Absätze zusammengehalten')
return 0
if __name__ == '__main__':
sys.exit(main())