Repository navigation
Expand file tree
/
Copy path02_converter.py
More file actions
197 lines (167 loc) · 5.7 KB
/
Copy path02_converter.py
File metadata and controls
197 lines (167 loc) · 5.7 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
#!/usr/bin/env python3
"""
Windows-only Word/HTML → PDF converter with progress bar and cleanup.
Behavior
- Scans the current working directory and all subfolders.
- Targets .doc, .docx, .rtf, .htm, .html.
- Exports each to a same-name .pdf next to the source.
- Deletes the source file only after a successful conversion.
- Skips items whose target PDF already exists.
- Shows a running progress bar.
- --dry-run performs no conversion and no deletion.
Prereqs
- Windows with Microsoft Word installed.
- Python 3.8+ and pywin32: pip install pywin32
Usage
- Open PowerShell in the target folder, then:
python convert_to_pdf.py
- Dry run:
python convert_to_pdf.py --dry-run
"""
import os
import sys
import argparse
from pathlib import Path
from typing import Iterable, Tuple, List
DOC_EXTS = {".doc", ".docx", ".rtf"}
HTML_EXTS = {".htm", ".html"}
ALL_EXTS = DOC_EXTS | HTML_EXTS
TARGET_EXT = ".pdf"
# ---------- discovery ----------
def find_eligible(root: Path) -> List[Path]:
"""
Return a list of eligible files under root recursively.
"""
files: List[Path] = []
for p in root.rglob("*"):
if p.is_file() and p.suffix.lower() in ALL_EXTS:
files.append(p)
return files
def target_path(src: Path) -> Path:
return src.with_suffix(TARGET_EXT)
# ---------- progress bar ----------
def render_progress(done: int, total: int, width: int = 40, prefix: str = "Progress") -> None:
"""
Simple in-place progress bar: [#####.....] 12/100
"""
if total <= 0:
total = 1
ratio = min(max(done / total, 0.0), 1.0)
filled = int(ratio * width)
bar = "#" * filled + "." * (width - filled)
msg = f"\r{prefix} [{bar}] {done}/{total}"
sys.stdout.write(msg)
sys.stdout.flush()
if done == total:
sys.stdout.write("\n")
# ---------- conversion via Word COM ----------
def convert_one(word_app, src: Path, dst: Path, dry_run: bool) -> Tuple[bool, str]:
"""
Convert a single file using Word's ExportAsFixedFormat.
Returns (success, error_message_if_any).
"""
# Skip if PDF exists
if dst.exists():
return False, "pdf-exists"
if dry_run:
return True, ""
# Open and export
doc = None
try:
# ReadOnly avoids prompts. ConfirmConversions False, AddToRecentFiles False.
doc = word_app.Documents.Open(str(src), ReadOnly=True)
# 17 = wdExportFormatPDF; OptimizeFor=0 print quality; CreateBookmarks=1 headings
doc.ExportAsFixedFormat(
OutputFileName=str(dst),
ExportFormat=17,
OpenAfterExport=False,
OptimizeFor=0,
CreateBookmarks=1
)
doc.Close(False)
return True, ""
except Exception as e:
try:
if doc is not None:
doc.Close(False)
except Exception:
pass
return False, f"word-error: {e}"
# ---------- main ----------
def main():
if os.name != "nt":
print("ERROR: Windows only. Microsoft Word required.", file=sys.stderr)
sys.exit(1)
ap = argparse.ArgumentParser(description="Convert DOC/DOCX/RTF/HTML to PDF in current folder recursively, delete sources after success.")
ap.add_argument("--dry-run", action="store_true", help="List actions and show progress only. No PDFs written. No deletions.")
args = ap.parse_args()
root = Path.cwd()
print(f"Scanning: {root}")
# Build the full workload first
workload = find_eligible(root)
total = len(workload)
if total == 0:
print("No DOC/DOCX/RTF/HTML files found.")
return
print(f"Found {total} eligible files")
# Import pywin32 and start Word
try:
import win32com.client
except Exception:
print("ERROR: pywin32 not available. Install with: pip install pywin32", file=sys.stderr)
sys.exit(3)
try:
word = win32com.client.DispatchEx("Word.Application")
except Exception:
print("ERROR: Cannot start Word via COM. Is Microsoft Word installed?", file=sys.stderr)
sys.exit(4)
# Quiet Word
try:
word.Visible = False
word.DisplayAlerts = 0
except Exception:
pass
converted = 0
skipped_pdf_exists = 0
failed = 0
failures: List[Tuple[Path, str]] = []
# Process with progress bar
done = 0
render_progress(done, total)
for src in workload:
dst = target_path(src)
ok, info = convert_one(word, src, dst, args.dry_run)
if ok:
converted += 1
# Delete source only if we actually exported a new PDF, not when skipping due to existing PDF, and not in dry-run
if not args.dry_run:
try:
src.unlink()
except Exception as e:
# Non-fatal: record but continue
failures.append((src, f"delete-failed: {e}"))
failed += 1
else:
if info == "pdf-exists":
skipped_pdf_exists += 1
else:
failed += 1
failures.append((src, info))
done += 1
render_progress(done, total)
# Cleanup Word
try:
word.Quit()
except Exception:
pass
# Summary
print("Summary")
print(f" Converted and deleted sources: {converted}")
print(f" Skipped (PDF already exists): {skipped_pdf_exists}")
print(f" Failed: {failed}")
if failures:
print("Failures:")
for p, msg in failures:
print(f" {p} -> {msg}")
if __name__ == "__main__":
main()