|
import os |
|
import sys |
|
import aspose.html as ah |
|
import aspose.html.saving as ahs |
|
|
|
def convert_html_to_txt(input_path: str, output_path: str, encoding: str = "utf-8") -> None: |
|
""" |
|
Converts an HTML file to a plain text (TXT) file using Aspose.HTML for Python via .NET. |
|
""" |
|
if not os.path.isfile(input_path): |
|
raise FileNotFoundError(f"Input file does not exist: {input_path}") |
|
|
|
try: |
|
# Load the HTML document |
|
document = ah.HtmlDocument(input_path) |
|
|
|
# Configure TXT save options |
|
txt_options = ahs.TxtSaveOptions() |
|
txt_options.encoding = encoding # Ensure proper character encoding |
|
txt_options.remove_extra_whitespace = True # Reduce unnecessary spaces (if supported) |
|
|
|
# Perform the conversion |
|
document.save(output_path, txt_options) |
|
|
|
except Exception as exc: |
|
# Capture any Aspose or I/O related errors |
|
print(f"[Error] Conversion failed: {exc}", file=sys.stderr) |
|
raise |
|
|
|
finally: |
|
# Explicitly release resources held by the document |
|
if 'document' in locals(): |
|
document.dispose() |
|
|
|
|
|
def validate_txt_output(output_path: str, min_chars: int = 10) -> None: |
|
""" |
|
Simple validation to ensure the TXT file was created and contains readable content. |
|
""" |
|
if not os.path.isfile(output_path): |
|
raise FileNotFoundError(f"Output file was not created: {output_path}") |
|
|
|
with open(output_path, "r", encoding="utf-8") as txt_file: |
|
content = txt_file.read() |
|
|
|
if len(content) < min_chars: |
|
raise ValueError("Output text appears to be empty or truncated.") |
|
|
|
# Show a short preview for quick verification |
|
preview = content[:200].replace("\r", "").replace("\n", " | ") |
|
print(f"[Info] Conversion succeeded. Preview (first 200 chars):\n{preview}") |
|
|
|
|
|
if __name__ == "__main__": |
|
# Example file paths – replace with actual locations as needed |
|
INPUT_HTML = "sample.html" |
|
OUTPUT_TXT = "sample.txt" |
|
|
|
try: |
|
convert_html_to_txt(INPUT_HTML, OUTPUT_TXT) |
|
validate_txt_output(OUTPUT_TXT) |
|
except Exception as e: |
|
print(f"[Fatal] HTML to TXT conversion failed: {e}", file=sys.stderr) |
|
sys.exit(1) |