You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
164 lines
6.0 KiB
164 lines
6.0 KiB
# -*- coding: utf-8 -*-
|
|
import os
|
|
import re
|
|
|
|
def clean_markdown_content(filename, content, link_mapping):
|
|
# 1. 목차/이전/다음 등 내비게이션 링크 제거 패턴
|
|
lines = content.split('\n')
|
|
cleaned_lines = []
|
|
|
|
for line in lines:
|
|
stripped = line.strip()
|
|
is_nav = False
|
|
if "메뉴얼 목차로 돌아가기" in stripped:
|
|
is_nav = True
|
|
elif "이전:" in stripped and "다음:" in stripped:
|
|
is_nav = True
|
|
elif stripped.startswith("[다음:") and stripped.endswith(")"):
|
|
is_nav = True
|
|
elif stripped.startswith("[← 이전:") and stripped.endswith(")"):
|
|
is_nav = True
|
|
|
|
if not is_nav:
|
|
cleaned_lines.append(line)
|
|
|
|
content = '\n'.join(cleaned_lines)
|
|
|
|
# 2. Obsidian 위키링크 이미지 문법 -> HTML img 태그로 치환 (크기 제한 및 중앙 정렬)
|
|
content = re.sub(r'!\[\[(.*?)\]\]', r'<img src="./\1" alt="\1" class="img-screenshot" />', content)
|
|
|
|
# 3. 마크다운 파일 참조 링크 -> 로컬 앵커로 치환
|
|
for md_file, anchor in link_mapping.items():
|
|
content = content.replace(f"({md_file})", f"({anchor})")
|
|
content = content.replace(f'"{md_file}"', f'"{anchor}"')
|
|
|
|
# 4. 각 파일 시작 전에 페이지 나누기 추가 (표지 파일은 제외)
|
|
is_cover = "사용자" in filename or "메뉴얼" in filename
|
|
if not is_cover:
|
|
content = '<div class="page-break"></div>\n\n' + content
|
|
|
|
# 5. 불필요하게 연속된 빈 라인 및 구분선 정리
|
|
content = re.sub(r'^\s*---\s*\n', '', content) # 문서 시작 부분의 --- 제거
|
|
content = re.sub(r'\n\s*---\s*$', '', content) # 문서 끝 부분의 --- 제거
|
|
|
|
return content
|
|
|
|
def main():
|
|
manual_dir = os.path.dirname(os.path.abspath(__file__))
|
|
merged_md_path = os.path.join(manual_dir, "Manual_Merged.md")
|
|
style_path = os.path.join(manual_dir, "pdf_style.css")
|
|
|
|
# CSS 파일 로드
|
|
css_content = ""
|
|
if os.path.exists(style_path):
|
|
with open(style_path, "r", encoding="utf-8") as f:
|
|
css_content = f.read()
|
|
else:
|
|
print(f"경고: 스타일시트 파일을 찾을 수 없습니다: {style_path}")
|
|
|
|
# 디렉토리 파일들을 UTF-8 유니코드로 스캔
|
|
all_files = os.listdir(manual_dir)
|
|
|
|
# 표지 파일 찾기
|
|
cover_file = None
|
|
for f in all_files:
|
|
if f.endswith(".md") and ("사용자" in f or "메뉴얼" in f) and "Merged" not in f:
|
|
cover_file = f
|
|
break
|
|
|
|
# "01_" ~ "09_"로 시작하는 검사 매뉴얼 파일 수집
|
|
numbered_files = []
|
|
for f in all_files:
|
|
if f.endswith(".md") and re.match(r'^\d+', f):
|
|
numbered_files.append(f)
|
|
|
|
# 순서 보장을 위해 정렬
|
|
numbered_files.sort()
|
|
|
|
# 최종 병합 리스트 빌드
|
|
final_file_list = []
|
|
if cover_file:
|
|
final_file_list.append(cover_file)
|
|
final_file_list.extend(numbered_files)
|
|
|
|
print("감지 및 병합할 파일 목록:")
|
|
for f in final_file_list:
|
|
print(f" - {f}")
|
|
|
|
# 링크 치환용 맵 작성 (인코딩 호환성을 위해 파일명 동적 파싱)
|
|
link_mapping = {}
|
|
for f in final_file_list:
|
|
if "사용자" in f or "메뉴얼" in f:
|
|
link_mapping[f] = "#메뉴얼-목차-table-of-contents"
|
|
elif f.startswith("01"):
|
|
link_mapping[f] = "#1-시스템-개요-및-요구사항"
|
|
elif f.startswith("02"):
|
|
link_mapping[f] = "#2-초기-설정-가이드"
|
|
elif f.startswith("03"):
|
|
link_mapping[f] = "#3-메인-화면-home-view"
|
|
elif f.startswith("04"):
|
|
link_mapping[f] = "#4-통신-설정-comm-settings"
|
|
elif f.startswith("05"):
|
|
link_mapping[f] = "#5-시험-설정-parameters"
|
|
elif f.startswith("06"):
|
|
link_mapping[f] = "#6-측정-데이터-조회-및-데이터베이스-연동"
|
|
elif f.startswith("07"):
|
|
link_mapping[f] = "#7-자동-시험-프로세스-및-14단계-시퀀스"
|
|
elif f.startswith("08"):
|
|
link_mapping[f] = "#8-로그-및-데이터-관리"
|
|
elif f.startswith("09"):
|
|
link_mapping[f] = "#9-오류-대응-및-프로그램-종료"
|
|
|
|
merged_markdown_only = ""
|
|
|
|
for file_name in final_file_list:
|
|
file_path = os.path.join(manual_dir, file_name)
|
|
print(f"병합 처리 중: {file_name}...")
|
|
with open(file_path, "r", encoding="utf-8") as f:
|
|
content = f.read()
|
|
|
|
cleaned = clean_markdown_content(file_name, content, link_mapping)
|
|
merged_markdown_only += cleaned + "\n\n"
|
|
|
|
# md 파일 저장용에는 style 포함
|
|
merged_content = ""
|
|
if css_content:
|
|
merged_content += f"<style>\n{css_content}\n</style>\n\n"
|
|
merged_content += merged_markdown_only
|
|
|
|
# 병합된 마크다운 저장
|
|
with open(merged_md_path, "w", encoding="utf-8") as f:
|
|
f.write(merged_content)
|
|
|
|
print(f"\n성공: 통합 마크다운 파일이 생성되었습니다 -> {merged_md_path}")
|
|
|
|
# HTML 생성 시도
|
|
try:
|
|
import markdown
|
|
merged_html_path = os.path.join(manual_dir, "Manual_for_pdf.html")
|
|
|
|
# HTML 뼈대 구성
|
|
html_output = f"""<!DOCTYPE html>
|
|
<html>
|
|
<head>
|
|
<meta charset="utf-8">
|
|
<title>Performance Inspect & Laser Marking System - 사용자 메뉴얼</title>
|
|
<style>
|
|
{css_content}
|
|
</style>
|
|
</head>
|
|
<body>
|
|
"""
|
|
html_body = markdown.markdown(merged_markdown_only, extensions=['tables', 'fenced_code'])
|
|
html_output += html_body
|
|
html_output += "\n</body>\n</html>"
|
|
|
|
with open(merged_html_path, "w", encoding="utf-8") as f:
|
|
f.write(html_output)
|
|
|
|
print(f"성공: 통합 HTML 파일이 생성되었습니다 -> {merged_html_path}")
|
|
except ImportError:
|
|
print("\n참고: 파이썬 'markdown' 패키지가 설치되지 않아 HTML 빌드를 건너뜁니다. (pip install markdown)")
|
|
|
|
if __name__ == "__main__":
|
|
main()
|
|
|