Pack a directory into an Office file (.docx/.pptx/.xlsx). Args: input_dir: Path to unpacked Office document directory output_file: Path to output Office file validate: If True, validates with soffice (default: False) Returns: bool: True if successful, False
(input_dir, output_file, validate=False)
| 43 | |
| 44 | |
| 45 | def pack_document(input_dir, output_file, validate=False): |
| 46 | """Pack a directory into an Office file (.docx/.pptx/.xlsx). |
| 47 | |
| 48 | Args: |
| 49 | input_dir: Path to unpacked Office document directory |
| 50 | output_file: Path to output Office file |
| 51 | validate: If True, validates with soffice (default: False) |
| 52 | |
| 53 | Returns: |
| 54 | bool: True if successful, False if validation failed |
| 55 | """ |
| 56 | input_dir = Path(input_dir) |
| 57 | output_file = Path(output_file) |
| 58 | |
| 59 | if not input_dir.is_dir(): |
| 60 | raise ValueError(f"{input_dir} is not a directory") |
| 61 | if output_file.suffix.lower() not in {".docx", ".pptx", ".xlsx"}: |
| 62 | raise ValueError(f"{output_file} must be a .docx, .pptx, or .xlsx file") |
| 63 | |
| 64 | # Work in temporary directory to avoid modifying original |
| 65 | with tempfile.TemporaryDirectory() as temp_dir: |
| 66 | temp_content_dir = Path(temp_dir) / "content" |
| 67 | shutil.copytree(input_dir, temp_content_dir) |
| 68 | |
| 69 | # Process XML files to remove pretty-printing whitespace |
| 70 | for pattern in ["*.xml", "*.rels"]: |
| 71 | for xml_file in temp_content_dir.rglob(pattern): |
| 72 | condense_xml(xml_file) |
| 73 | |
| 74 | # Create final Office file as zip archive |
| 75 | output_file.parent.mkdir(parents=True, exist_ok=True) |
| 76 | with zipfile.ZipFile(output_file, "w", zipfile.ZIP_DEFLATED) as zf: |
| 77 | for f in temp_content_dir.rglob("*"): |
| 78 | if f.is_file(): |
| 79 | zf.write(f, f.relative_to(temp_content_dir)) |
| 80 | |
| 81 | # Validate if requested |
| 82 | if validate: |
| 83 | if not validate_document(output_file): |
| 84 | output_file.unlink() # Delete the corrupt file |
| 85 | return False |
| 86 | |
| 87 | return True |
| 88 | |
| 89 | |
| 90 | def validate_document(doc_path): |
no test coverage detected