helper-hwp 0.5.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,214 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as original works of authorship. For the purposes of this
44
+ License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work
179
+
180
+ Copyright 2025 helper_hwp contributors
181
+
182
+ Licensed under the Apache License, Version 2.0 (the "License");
183
+ you may not use this file except in compliance with the License.
184
+ You may obtain a copy of the License at
185
+
186
+ http://www.apache.org/licenses/LICENSE-2.0
187
+
188
+ Unless required by applicable law or agreed to in writing, software
189
+ distributed under the License is distributed on an "AS IS" BASIS,
190
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
191
+ See the License for the specific language governing permissions and
192
+ limitations under the License.
193
+
194
+ ---
195
+
196
+ This project is based on and distributed under the Apache License 2.0.
197
+ You are free to use, modify, and distribute this software.
198
+
199
+ When using or distributing this software, please include attribution:
200
+ Source: https://github.com/c0z0c/helper_hwp
201
+
202
+ ---
203
+
204
+ 본 프로젝트는 Apache License 2.0 하에 배포됩니다.
205
+
206
+ - 누구나 자유롭게 사용할 수 있습니다
207
+ - 누구나 자유롭게 수정할 수 있습니다
208
+ - 상업적 이용이 가능합니다
209
+ - 재배포가 가능합니다
210
+
211
+ 사용 시 출처를 표기해 주세요:
212
+ 출처: https://github.com/c0z0c/helper_hwp
213
+
214
+ 라이센스 전문은 위의 영문 내용을 참조하시기 바랍니다.
@@ -0,0 +1,134 @@
1
+ Metadata-Version: 2.4
2
+ Name: helper-hwp
3
+ Version: 0.5.0
4
+ Summary: Python HWP 파일 파서 및 텍스트 추출 라이브러리
5
+ Author-email: c0z0c <c0z0c.dev@gmail.com>
6
+ License: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/c0z0c/helper_hwp
8
+ Project-URL: Repository, https://github.com/c0z0c/helper_hwp
9
+ Project-URL: Issues, https://github.com/c0z0c/helper_hwp/issues
10
+ Keywords: hwp,hancom,hangul,parser,text-extraction
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: License :: OSI Approved :: Apache Software License
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.8
16
+ Classifier: Programming Language :: Python :: 3.9
17
+ Classifier: Programming Language :: Python :: 3.10
18
+ Classifier: Programming Language :: Python :: 3.11
19
+ Classifier: Programming Language :: Python :: 3.12
20
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
21
+ Classifier: Topic :: Text Processing
22
+ Requires-Python: >=3.8
23
+ Description-Content-Type: text/markdown
24
+ License-File: LICENSE
25
+ Requires-Dist: olefile>=0.46
26
+ Requires-Dist: pycryptodome>=3.15.0
27
+ Provides-Extra: dev
28
+ Requires-Dist: pytest>=7.0.0; extra == "dev"
29
+ Requires-Dist: pytest-cov>=4.0.0; extra == "dev"
30
+ Requires-Dist: black>=23.0.0; extra == "dev"
31
+ Requires-Dist: ruff>=0.1.0; extra == "dev"
32
+ Requires-Dist: mypy>=1.0.0; extra == "dev"
33
+ Dynamic: license-file
34
+
35
+ # helper_hwp
36
+
37
+ Python으로 작성된 HWP (한글 문서) 파일 파서 및 텍스트 추출 라이브러리입니다.
38
+
39
+ ## 특징
40
+
41
+ - HWP 5.x 포맷 지원 (CFB 기반)
42
+ - 텍스트 추출 및 마크다운 변환
43
+ - 표, 페이지 단위 파싱 지원
44
+ - 단위 변환 유틸리티 제공 (HWPUNIT ↔ cm/inch/px)
45
+
46
+ ## 설치
47
+
48
+ ```bash
49
+ pip install helper-hwp
50
+ ```
51
+
52
+ 또는 소스에서 설치:
53
+
54
+ ```bash
55
+ git clone https://github.com/c0z0c/helper_hwp.git
56
+ cd helper_hwp
57
+ pip install -e .
58
+ ```
59
+
60
+ ## 빠른 시작
61
+
62
+ ### 텍스트 추출
63
+
64
+ ```python
65
+ from helper_hwp import hwp_to_txt
66
+
67
+ # HWP 파일에서 텍스트 추출
68
+ text = hwp_to_txt('example.hwp')
69
+ print(text)
70
+ ```
71
+
72
+ ### 마크다운 변환
73
+
74
+ ```python
75
+ from helper_hwp import hwp_to_markdown
76
+
77
+ # HWP 파일을 마크다운으로 변환
78
+ markdown = hwp_to_markdown('example.hwp')
79
+ print(markdown)
80
+ ```
81
+
82
+ ### 문서 객체 사용
83
+
84
+ ```python
85
+ from helper_hwp import open_hwp
86
+
87
+ # HWP 문서 열기
88
+ doc = open_hwp('example.hwp')
89
+
90
+ # 문단 단위 순회
91
+ for paragraph in doc.iter_paragraphs():
92
+ print(paragraph.text)
93
+
94
+ # 표 단위 순회
95
+ for table in doc.iter_tables():
96
+ print(table.rows)
97
+ ```
98
+
99
+ ## 사용 예제
100
+
101
+ 더 많은 예제는 [examples](examples/) 디렉토리를 참조하세요:
102
+
103
+ - [텍스트 추출 예제](examples/example_hwp_to_txt.py)
104
+ - [마크다운 변환 예제](examples/example_hwp_to_markdown.py)
105
+ - [태그 순회 예제](examples/example_iter_tags.py)
106
+
107
+ ## 문서
108
+
109
+ - [사용자 가이드](docs/USER_GUIDE.md) - 기본 사용법 및 예제
110
+ - [개발자 문서](docs/DEVELOPER.md) - 프로젝트 구조 및 개발 가이드
111
+
112
+ ## 요구사항
113
+
114
+ - Python 3.8 이상
115
+ - olefile >= 0.46
116
+ - pycryptodome >= 3.15.0
117
+
118
+ ## 라이센스
119
+
120
+ 이 프로젝트는 Apache License 2.0 라이센스 하에 배포됩니다.
121
+
122
+ 누구나 자유롭게 사용하고 수정할 수 있으며, 사용 시 출처를 표기해 주세요.
123
+
124
+ 출처: https://github.com/c0z0c/helper_hwp
125
+
126
+ 자세한 내용은 [LICENSE](LICENSE) 파일을 참조하세요.
127
+
128
+ ## 기여
129
+
130
+ 프로젝트에 대한 기여를 환영합니다! 기여 방법은 [개발자 문서](docs/DEVELOPER.md)를 참조하세요.
131
+
132
+ ## 변경 이력
133
+
134
+ 변경 이력은 [CHANGELOG.md](CHANGELOG.md)를 참조하세요.
@@ -0,0 +1,100 @@
1
+ # helper_hwp
2
+
3
+ Python으로 작성된 HWP (한글 문서) 파일 파서 및 텍스트 추출 라이브러리입니다.
4
+
5
+ ## 특징
6
+
7
+ - HWP 5.x 포맷 지원 (CFB 기반)
8
+ - 텍스트 추출 및 마크다운 변환
9
+ - 표, 페이지 단위 파싱 지원
10
+ - 단위 변환 유틸리티 제공 (HWPUNIT ↔ cm/inch/px)
11
+
12
+ ## 설치
13
+
14
+ ```bash
15
+ pip install helper-hwp
16
+ ```
17
+
18
+ 또는 소스에서 설치:
19
+
20
+ ```bash
21
+ git clone https://github.com/c0z0c/helper_hwp.git
22
+ cd helper_hwp
23
+ pip install -e .
24
+ ```
25
+
26
+ ## 빠른 시작
27
+
28
+ ### 텍스트 추출
29
+
30
+ ```python
31
+ from helper_hwp import hwp_to_txt
32
+
33
+ # HWP 파일에서 텍스트 추출
34
+ text = hwp_to_txt('example.hwp')
35
+ print(text)
36
+ ```
37
+
38
+ ### 마크다운 변환
39
+
40
+ ```python
41
+ from helper_hwp import hwp_to_markdown
42
+
43
+ # HWP 파일을 마크다운으로 변환
44
+ markdown = hwp_to_markdown('example.hwp')
45
+ print(markdown)
46
+ ```
47
+
48
+ ### 문서 객체 사용
49
+
50
+ ```python
51
+ from helper_hwp import open_hwp
52
+
53
+ # HWP 문서 열기
54
+ doc = open_hwp('example.hwp')
55
+
56
+ # 문단 단위 순회
57
+ for paragraph in doc.iter_paragraphs():
58
+ print(paragraph.text)
59
+
60
+ # 표 단위 순회
61
+ for table in doc.iter_tables():
62
+ print(table.rows)
63
+ ```
64
+
65
+ ## 사용 예제
66
+
67
+ 더 많은 예제는 [examples](examples/) 디렉토리를 참조하세요:
68
+
69
+ - [텍스트 추출 예제](examples/example_hwp_to_txt.py)
70
+ - [마크다운 변환 예제](examples/example_hwp_to_markdown.py)
71
+ - [태그 순회 예제](examples/example_iter_tags.py)
72
+
73
+ ## 문서
74
+
75
+ - [사용자 가이드](docs/USER_GUIDE.md) - 기본 사용법 및 예제
76
+ - [개발자 문서](docs/DEVELOPER.md) - 프로젝트 구조 및 개발 가이드
77
+
78
+ ## 요구사항
79
+
80
+ - Python 3.8 이상
81
+ - olefile >= 0.46
82
+ - pycryptodome >= 3.15.0
83
+
84
+ ## 라이센스
85
+
86
+ 이 프로젝트는 Apache License 2.0 라이센스 하에 배포됩니다.
87
+
88
+ 누구나 자유롭게 사용하고 수정할 수 있으며, 사용 시 출처를 표기해 주세요.
89
+
90
+ 출처: https://github.com/c0z0c/helper_hwp
91
+
92
+ 자세한 내용은 [LICENSE](LICENSE) 파일을 참조하세요.
93
+
94
+ ## 기여
95
+
96
+ 프로젝트에 대한 기여를 환영합니다! 기여 방법은 [개발자 문서](docs/DEVELOPER.md)를 참조하세요.
97
+
98
+ ## 변경 이력
99
+
100
+ 변경 이력은 [CHANGELOG.md](CHANGELOG.md)를 참조하세요.
@@ -0,0 +1,134 @@
1
+ Metadata-Version: 2.4
2
+ Name: helper-hwp
3
+ Version: 0.5.0
4
+ Summary: Python HWP 파일 파서 및 텍스트 추출 라이브러리
5
+ Author-email: c0z0c <c0z0c.dev@gmail.com>
6
+ License: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/c0z0c/helper_hwp
8
+ Project-URL: Repository, https://github.com/c0z0c/helper_hwp
9
+ Project-URL: Issues, https://github.com/c0z0c/helper_hwp/issues
10
+ Keywords: hwp,hancom,hangul,parser,text-extraction
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: License :: OSI Approved :: Apache Software License
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.8
16
+ Classifier: Programming Language :: Python :: 3.9
17
+ Classifier: Programming Language :: Python :: 3.10
18
+ Classifier: Programming Language :: Python :: 3.11
19
+ Classifier: Programming Language :: Python :: 3.12
20
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
21
+ Classifier: Topic :: Text Processing
22
+ Requires-Python: >=3.8
23
+ Description-Content-Type: text/markdown
24
+ License-File: LICENSE
25
+ Requires-Dist: olefile>=0.46
26
+ Requires-Dist: pycryptodome>=3.15.0
27
+ Provides-Extra: dev
28
+ Requires-Dist: pytest>=7.0.0; extra == "dev"
29
+ Requires-Dist: pytest-cov>=4.0.0; extra == "dev"
30
+ Requires-Dist: black>=23.0.0; extra == "dev"
31
+ Requires-Dist: ruff>=0.1.0; extra == "dev"
32
+ Requires-Dist: mypy>=1.0.0; extra == "dev"
33
+ Dynamic: license-file
34
+
35
+ # helper_hwp
36
+
37
+ Python으로 작성된 HWP (한글 문서) 파일 파서 및 텍스트 추출 라이브러리입니다.
38
+
39
+ ## 특징
40
+
41
+ - HWP 5.x 포맷 지원 (CFB 기반)
42
+ - 텍스트 추출 및 마크다운 변환
43
+ - 표, 페이지 단위 파싱 지원
44
+ - 단위 변환 유틸리티 제공 (HWPUNIT ↔ cm/inch/px)
45
+
46
+ ## 설치
47
+
48
+ ```bash
49
+ pip install helper-hwp
50
+ ```
51
+
52
+ 또는 소스에서 설치:
53
+
54
+ ```bash
55
+ git clone https://github.com/c0z0c/helper_hwp.git
56
+ cd helper_hwp
57
+ pip install -e .
58
+ ```
59
+
60
+ ## 빠른 시작
61
+
62
+ ### 텍스트 추출
63
+
64
+ ```python
65
+ from helper_hwp import hwp_to_txt
66
+
67
+ # HWP 파일에서 텍스트 추출
68
+ text = hwp_to_txt('example.hwp')
69
+ print(text)
70
+ ```
71
+
72
+ ### 마크다운 변환
73
+
74
+ ```python
75
+ from helper_hwp import hwp_to_markdown
76
+
77
+ # HWP 파일을 마크다운으로 변환
78
+ markdown = hwp_to_markdown('example.hwp')
79
+ print(markdown)
80
+ ```
81
+
82
+ ### 문서 객체 사용
83
+
84
+ ```python
85
+ from helper_hwp import open_hwp
86
+
87
+ # HWP 문서 열기
88
+ doc = open_hwp('example.hwp')
89
+
90
+ # 문단 단위 순회
91
+ for paragraph in doc.iter_paragraphs():
92
+ print(paragraph.text)
93
+
94
+ # 표 단위 순회
95
+ for table in doc.iter_tables():
96
+ print(table.rows)
97
+ ```
98
+
99
+ ## 사용 예제
100
+
101
+ 더 많은 예제는 [examples](examples/) 디렉토리를 참조하세요:
102
+
103
+ - [텍스트 추출 예제](examples/example_hwp_to_txt.py)
104
+ - [마크다운 변환 예제](examples/example_hwp_to_markdown.py)
105
+ - [태그 순회 예제](examples/example_iter_tags.py)
106
+
107
+ ## 문서
108
+
109
+ - [사용자 가이드](docs/USER_GUIDE.md) - 기본 사용법 및 예제
110
+ - [개발자 문서](docs/DEVELOPER.md) - 프로젝트 구조 및 개발 가이드
111
+
112
+ ## 요구사항
113
+
114
+ - Python 3.8 이상
115
+ - olefile >= 0.46
116
+ - pycryptodome >= 3.15.0
117
+
118
+ ## 라이센스
119
+
120
+ 이 프로젝트는 Apache License 2.0 라이센스 하에 배포됩니다.
121
+
122
+ 누구나 자유롭게 사용하고 수정할 수 있으며, 사용 시 출처를 표기해 주세요.
123
+
124
+ 출처: https://github.com/c0z0c/helper_hwp
125
+
126
+ 자세한 내용은 [LICENSE](LICENSE) 파일을 참조하세요.
127
+
128
+ ## 기여
129
+
130
+ 프로젝트에 대한 기여를 환영합니다! 기여 방법은 [개발자 문서](docs/DEVELOPER.md)를 참조하세요.
131
+
132
+ ## 변경 이력
133
+
134
+ 변경 이력은 [CHANGELOG.md](CHANGELOG.md)를 참조하세요.
@@ -0,0 +1,12 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ helper_hwp.egg-info/PKG-INFO
5
+ helper_hwp.egg-info/SOURCES.txt
6
+ helper_hwp.egg-info/dependency_links.txt
7
+ helper_hwp.egg-info/requires.txt
8
+ helper_hwp.egg-info/top_level.txt
9
+ tests/test_hwp_iter_tags.py
10
+ tests/test_hwp_to_markdown.py
11
+ tests/test_hwp_to_markdown_pdf.py
12
+ tests/test_hwp_to_txt.py
@@ -0,0 +1,9 @@
1
+ olefile>=0.46
2
+ pycryptodome>=3.15.0
3
+
4
+ [dev]
5
+ pytest>=7.0.0
6
+ pytest-cov>=4.0.0
7
+ black>=23.0.0
8
+ ruff>=0.1.0
9
+ mypy>=1.0.0
@@ -0,0 +1 @@
1
+ helper_hwp
@@ -0,0 +1,71 @@
1
+ [build-system]
2
+ requires = ["setuptools>=61.0", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "helper-hwp"
7
+ version = "0.5.0"
8
+ description = "Python HWP 파일 파서 및 텍스트 추출 라이브러리"
9
+ readme = "README.md"
10
+ requires-python = ">=3.8"
11
+ license = {text = "Apache-2.0"}
12
+ authors = [
13
+ {name = "c0z0c", email = "c0z0c.dev@gmail.com"}
14
+ ]
15
+ keywords = ["hwp", "hancom", "hangul", "parser", "text-extraction"]
16
+ classifiers = [
17
+ "Development Status :: 3 - Alpha",
18
+ "Intended Audience :: Developers",
19
+ "License :: OSI Approved :: Apache Software License",
20
+ "Programming Language :: Python :: 3",
21
+ "Programming Language :: Python :: 3.8",
22
+ "Programming Language :: Python :: 3.9",
23
+ "Programming Language :: Python :: 3.10",
24
+ "Programming Language :: Python :: 3.11",
25
+ "Programming Language :: Python :: 3.12",
26
+ "Topic :: Software Development :: Libraries :: Python Modules",
27
+ "Topic :: Text Processing",
28
+ ]
29
+
30
+ dependencies = [
31
+ "olefile>=0.46", # CFB (Compound File Binary) 파싱
32
+ "pycryptodome>=3.15.0", # AES 암호화 해제
33
+ ]
34
+
35
+ [project.optional-dependencies]
36
+ dev = [
37
+ "pytest>=7.0.0",
38
+ "pytest-cov>=4.0.0",
39
+ "black>=23.0.0",
40
+ "ruff>=0.1.0",
41
+ "mypy>=1.0.0",
42
+ ]
43
+
44
+ [project.urls]
45
+ Homepage = "https://github.com/c0z0c/helper_hwp"
46
+ Repository = "https://github.com/c0z0c/helper_hwp"
47
+ Issues = "https://github.com/c0z0c/helper_hwp/issues"
48
+
49
+ [tool.setuptools]
50
+ py-modules = ["helper_hwp"]
51
+
52
+ [tool.black]
53
+ line-length = 100
54
+ target-version = ['py38']
55
+
56
+ [tool.ruff]
57
+ line-length = 100
58
+ target-version = "py38"
59
+
60
+ [tool.mypy]
61
+ python_version = "3.8"
62
+ warn_return_any = true
63
+ warn_unused_configs = true
64
+ disallow_untyped_defs = false
65
+
66
+ [tool.pytest.ini_options]
67
+ testpaths = ["tests"]
68
+ python_files = ["test_*.py"]
69
+ python_classes = ["Test*"]
70
+ python_functions = ["test_*"]
71
+ addopts = "--cov=helper_hwp --cov-report=html --cov-report=term-missing"
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,350 @@
1
+ """
2
+ test.hwp를 open_hwp()로 문단 단위로 텍스트 추출하는 데모
3
+
4
+ 사용법:
5
+ python test_helper_hwp.py
6
+ """
7
+
8
+ import sys
9
+ import os
10
+ import struct
11
+ sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
12
+
13
+ # UTF-8 출력 설정 (Windows 콘솔 대응)
14
+ if sys.platform == 'win32':
15
+ import io
16
+ sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8', errors='replace')
17
+ sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding='utf-8', errors='replace')
18
+
19
+ from helper_hwp import open_hwp, ElementType, IterMode
20
+
21
+
22
+ def estimate_table_size(table) -> tuple:
23
+ """일반 텍스트 테이블 크기 추정"""
24
+ if table.rows and table.cols:
25
+ # 기본 셀 크기 가정
26
+ default_cell_width = 3.0 # cm
27
+ default_cell_height = 0.8 # cm
28
+
29
+ estimated_width = table.cols * default_cell_width
30
+ estimated_height = table.rows * default_cell_height
31
+
32
+ return (estimated_width, estimated_height)
33
+ return (None, None)
34
+
35
+
36
+ def main():
37
+ # test.hwp 파일 경로
38
+ test_file = "test.hwp"
39
+
40
+ # 파일 존재 확인
41
+ if not os.path.exists(test_file):
42
+ print(f"오류: {test_file} 파일을 찾을 수 없습니다.")
43
+ print(f"현재 디렉토리: {os.getcwd()}")
44
+ print(f"\n사용 가능한 HWP 파일:")
45
+ for file in os.listdir('.'):
46
+ if file.endswith('.hwp'):
47
+ print(f" - {file}")
48
+ return
49
+
50
+ print("=" * 80)
51
+ print("open_hwp() 데모 - test.hwp 태그 기반 순회")
52
+ print("=" * 80)
53
+
54
+ output_file = "test_helper_hwp.txt"
55
+ with open(output_file, 'w', encoding='utf-8') as f:
56
+
57
+ # Context Manager로 파일 로드
58
+ f.write(f"\n[1] 파일 로딩: {test_file}")
59
+ with open_hwp(test_file) as hwp:
60
+ # 파일 정보 출력
61
+ f.write(f"\n[2] 파일 정보")
62
+ f.write(f" - 버전: {hwp.version}")
63
+ f.write(f" - 압축: {hwp.compressed}")
64
+ f.write(f" - 암호화: {hwp.encrypted}")
65
+ f.write(f" - 섹션 수: {len(hwp.sections)}")
66
+ f.write(f" - 순회 모드: {hwp.iter_mode.value}")
67
+ f.write(f" - 글자 모양 수: {len(hwp._hwp.char_shapes)}개")
68
+
69
+ # iter_tags()로 문서 요소 순회
70
+ f.write(f"\n[3] 태그 기반 순회 - iter_tags()")
71
+ element_counts = {}
72
+ paragraphs = []
73
+ tables = []
74
+ page_breaks = []
75
+ footers = []
76
+ headers = []
77
+ page_defs = []
78
+
79
+ for element_type, element in hwp.iter_tags():
80
+ element_counts[element_type] = element_counts.get(element_type, 0) + 1
81
+
82
+ if element_type == ElementType.PARAGRAPH:
83
+ paragraphs.append(element)
84
+ elif element_type == ElementType.TABLE:
85
+ tables.append(element)
86
+ elif element_type == ElementType.PAGE_BREAK:
87
+ page_breaks.append(element)
88
+ elif element_type == ElementType.FOOTER:
89
+ footers.append(element)
90
+ elif element_type == ElementType.HEADER:
91
+ headers.append(element)
92
+ elif element_type == ElementType.PAGE_DEF:
93
+ page_defs.append(element)
94
+
95
+ f.write(f" > 요소 통계:")
96
+ for elem_type, count in element_counts.items():
97
+ f.write(f" - {elem_type.value}: {count}개")
98
+
99
+ # 문단 통계
100
+ f.write(f"\n[4] 문단 통계")
101
+ total_chars = sum(len(p.text) for p in paragraphs)
102
+ avg_chars = total_chars / len(paragraphs) if paragraphs else 0
103
+ max_chars = max(len(p.text) for p in paragraphs) if paragraphs else 0
104
+ min_chars = min(len(p.text) for p in paragraphs) if paragraphs else 0
105
+
106
+ # 서식 정보 통계
107
+ font_sizes = [p.char_shape.font_size for p in paragraphs if p.char_shape]
108
+ bold_count = sum(1 for p in paragraphs if p.char_shape and p.char_shape.bold)
109
+ italic_count = sum(1 for p in paragraphs if p.char_shape and p.char_shape.italic)
110
+
111
+ f.write(f" - 총 문자 수: {total_chars:,}자")
112
+ f.write(f" - 평균 문단 길이: {avg_chars:.1f}자")
113
+ f.write(f" - 최대 문단 길이: {max_chars}자")
114
+ f.write(f" - 최소 문단 길이: {min_chars}자")
115
+ if font_sizes:
116
+ f.write(f" - 평균 글꼴 크기: {sum(font_sizes)/len(font_sizes):.1f}pt")
117
+ f.write(f" - 굵게 문단: {bold_count}개")
118
+ f.write(f" - 기울임 문단: {italic_count}개")
119
+
120
+ # 문단별 텍스트 출력 (처음 5개만)
121
+ f.write(f"\n[5] 문단별 텍스트 출력 (처음 5개)")
122
+ f.write("=" * 80)
123
+
124
+ for i, para in enumerate(paragraphs[:5], 1):
125
+ f.write(f"\n문단 {i} ({len(para.text)}자):")
126
+ if para.char_shape:
127
+ f.write(f" [글꼴: {para.char_shape.font_size}pt, 굵게: {para.char_shape.bold}, 기울임: {para.char_shape.italic}]")
128
+ # 확장 속성: 글자별 서식 정보
129
+ if para.char_shapes:
130
+ f.write(f" [확장] 글자별 서식 ({len(para.char_shapes)}개):")
131
+ for pos, shape in para.char_shapes:
132
+ f.write(f" 위치 {pos}: {shape.font_size}pt, 굵게 {shape.bold}, 기울임 {shape.italic}")
133
+ f.write(f"{para.text}")
134
+ f.write("-" * 80)
135
+
136
+ if len(paragraphs) > 5:
137
+ f.write(f"\n... ({len(paragraphs) - 5}개 문단 생략)")
138
+
139
+ # 테이블 정보
140
+ if tables:
141
+ f.write(f"\n[6] 테이블 정보")
142
+ f.write(f" > 총 {len(tables)}개 테이블 발견")
143
+ for i, table in enumerate(tables, 1):
144
+ f.write(f" 테이블 {i}: code={table.code}")
145
+
146
+ # 페이지 구분
147
+ if page_breaks:
148
+ f.write(f"\n[7] 페이지 구분")
149
+ f.write(f" > 총 {len(page_breaks)}개 페이지 구분 발견")
150
+
151
+ # 머리말 정보
152
+ if headers:
153
+ f.write(f"\n[8] 머리말 정보")
154
+ f.write(f" > 총 {len(headers)}개 머리말 발견")
155
+ for i, header in enumerate(headers, 1):
156
+ f.write(f" 머리말 {i}: code={header.code}")
157
+ if hasattr(header, 'control_id'):
158
+ f.write(f", control_id=0x{header.control_id:08X}")
159
+
160
+ # 꼬리말 정보
161
+ if footers:
162
+ f.write(f"\n[9] 꼬리말 정보")
163
+ f.write(f" > 총 {len(footers)}개 꼬리말 발견")
164
+ for i, footer in enumerate(footers, 1):
165
+ f.write(f" 꼬리말 {i}: code={footer.code}")
166
+ if hasattr(footer, 'control_id'):
167
+ f.write(f", control_id=0x{footer.control_id:08X}")
168
+
169
+ # 페이지 정의 정보
170
+ if page_defs:
171
+ f.write(f"\n[10] 페이지 정의 (PAGE_DEF)")
172
+ f.write(f" > 총 {len(page_defs)}개 페이지 정의 발견")
173
+ for i, page_def in enumerate(page_defs, 1):
174
+ f.write(f" 페이지 정의 {i}: code={page_def.code}")
175
+
176
+ # 전체 텍스트 추출
177
+ f.write(f"\n[11] 전체 텍스트 추출 - to_text()")
178
+ full_text = hwp.to_text()
179
+ f.write(f" > 총 {len(full_text):,}자 추출")
180
+
181
+ index = 1
182
+ for element_type, element in hwp.iter_tags():
183
+ # 확장 제어 디버깅 정보 출력
184
+ # if element_type in [ElementType.TABLE, ElementType.EQUATION, ElementType.PICTURE]:
185
+ # control_id = element.control_id if hasattr(element, 'control_id') else None
186
+ # control_id_str = f"0x{control_id:08X}" if control_id else "None"
187
+ # f.write(f"*** 타입: {element_type.value}, 코드: {element.code}, Control ID: {control_id_str}, 데이터: {element.data[:20] if element.data else None}\n")
188
+
189
+ if element_type == ElementType.PARAGRAPH:
190
+ f.write(f"[문단 {index}]\n")
191
+ if hasattr(element, 'char_shape') and element.char_shape:
192
+ f.write(f"[서식(max): {element.char_shape.font_size}pt, 굵게: {element.char_shape.bold}]\n")
193
+ # 확장 속성: 글자별 상세 서식
194
+ if hasattr(element, 'char_shapes') and element.char_shapes and len(element.char_shapes) > 1:
195
+ f.write(f"[상세] 글자별 서식 변경 지점:\n")
196
+ for pos, shape in element.char_shapes:
197
+ f.write(f" 위치 {pos}: {shape.font_size}pt, 굵게 {shape.bold}\n")
198
+ f.write(f"{element.text}\n\n")
199
+ elif element_type == ElementType.TABLE:
200
+ # tables.append(element)
201
+ f.write(f"[표 {index}]\n")
202
+ f.write(f" - Table Index: {element.table_index}\n")
203
+ f.write(f" - Control ID: {element.control_id or element.get_control_id()}\n")
204
+ f.write(f" - code: {element.code}\n")
205
+ if element.rows is not None:
206
+ f.write(f" - 행/열: {element.rows} x {element.cols} (cell_count={element.cell_count})\n")
207
+
208
+ # 크기 출력 (실제 크기 또는 추정 크기)
209
+ if element.width is not None:
210
+ # 실제 크기 (도형 개체 테이블)
211
+ width_px = element.to_px(element.width, dpi=96)
212
+ height_px = element.to_px(element.height, dpi=96)
213
+ f.write(f" - 크기(cm): {element.width_cm:.2f}cm x {element.height_cm:.2f}cm\n")
214
+ f.write(f" - 크기(px): {width_px}px x {height_px}px (96 DPI)\n")
215
+ else:
216
+ # 추정 크기 (일반 텍스트 테이블)
217
+ est_width, est_height = estimate_table_size(element)
218
+ if est_width:
219
+ # cm를 픽셀로 변환 (1 inch = 2.54 cm, 96 DPI)
220
+ est_width_px = int(est_width / 2.54 * 96)
221
+ est_height_px = int(est_height / 2.54 * 96)
222
+ f.write(f" - 크기(추정cm): ~{est_width:.2f}cm x ~{est_height:.2f}cm\n")
223
+ f.write(f" - 크기(추정px): ~{est_width_px}px x ~{est_height_px}px (96 DPI)\n")
224
+
225
+ # 위치 출력 (cm와 픽셀 둘 다)
226
+ if element.x is not None:
227
+ x_px = element.to_px(element.x, dpi=96)
228
+ y_px = element.to_px(element.y, dpi=96)
229
+ f.write(f" - 위치(cm): X={element.to_cm(element.x):.2f}cm, Y={element.to_cm(element.y):.2f}cm\n")
230
+ f.write(f" - 위치(px): X={x_px}px, Y={y_px}px (96 DPI)\n")
231
+ else:
232
+ f.write(f" - 위치: 텍스트 흐름 (자동 배치)\n")
233
+
234
+ f.write(f"\n")
235
+ elif element_type == ElementType.PAGE_BREAK:
236
+ f.write(f"[페이지구분 {index}]\n")
237
+ elif element_type == ElementType.SECTION:
238
+ f.write(f"[섹션 {index}]\n")
239
+ elif element_type == ElementType.HEADER:
240
+ f.write(f"[머리말 {index}]\n")
241
+ elif element_type == ElementType.FOOTER:
242
+ f.write(f"[꼬리말 {index}]\n")
243
+ if hasattr(element, 'control_id'):
244
+ f.write(f" - Control ID: 0x{element.control_id:08X}\n")
245
+ f.write(f" - code: {element.code}\n")
246
+ # 꼬리말 내용이 있는지 확인
247
+ if hasattr(element, 'data') and element.data:
248
+ f.write(f" - 데이터 길이: {len(element.data)} bytes\n")
249
+ elif element_type == ElementType.FOOTNOTE:
250
+ f.write(f"[각주 {index}]\n")
251
+ elif element_type == ElementType.ENDNOTE:
252
+ f.write(f"[미주 {index}]\n")
253
+ elif element_type == ElementType.COMMENT:
254
+ f.write(f"[메모 {index}]\n")
255
+ elif element_type == ElementType.SHAPE:
256
+ f.write(f"[도형 {index}]\n")
257
+ elif element_type == ElementType.PICTURE:
258
+ f.write(f"[그림 {index}]\n")
259
+ elif element_type == ElementType.OLE:
260
+ f.write(f"[OLE {index}]\n")
261
+ elif element_type == ElementType.EQUATION:
262
+ f.write(f"[수식 {index}]\n")
263
+ elif element_type == ElementType.HYPERLINK:
264
+ f.write(f"[하이퍼링크 {index}]\n")
265
+ elif element_type == ElementType.SHAPE_COMPONENT:
266
+ f.write(f"[도형요소 {index}]\n")
267
+ elif element_type == ElementType.LIST_HEADER:
268
+ f.write(f"[리스트헤더 {index}]\n")
269
+ elif element_type == ElementType.PAGE_DEF:
270
+ f.write(f"[페이지정의 {index}]\n")
271
+ f.write(f" - code: {element.code}\n")
272
+ if hasattr(element, 'data') and element.data:
273
+ f.write(f" - 데이터 길이: {len(element.data)} bytes\n")
274
+ # 꼬리말 여백 정보 (offset 16-19, HWPUNIT 4 bytes)
275
+ if len(element.data) >= 20:
276
+ footer_margin = struct.unpack('<I', element.data[16:20])[0]
277
+ f.write(f" - 꼬리말 여백: {footer_margin} HWPUNIT\n")
278
+ elif element_type == ElementType.CTRL_HEADER:
279
+ f.write(f"[컨트롤헤더 {index}]\n")
280
+ elif element_type == ElementType.CTRL_DATA:
281
+ f.write(f"[컨트롤데이터 {index}]\n")
282
+ elif element_type == ElementType.CAPTION:
283
+ f.write(f"[캡션 {index}]\n")
284
+ elif element_type == ElementType.BOOKMARK:
285
+ f.write(f"[책갈피 {index}]\n")
286
+ elif element_type == ElementType.FIELD:
287
+ f.write(f"[필드 {index}]\n")
288
+ elif element_type == ElementType.AUTO_NUMBER:
289
+ f.write(f"[자동번호/쪽번호 {index}]\n")
290
+ if hasattr(element, 'control_id') and element.control_id:
291
+ f.write(f" - Control ID: 0x{element.control_id:08X}\n")
292
+ f.write(f" - code: {element.code}\n")
293
+ if hasattr(element, 'data') and element.data:
294
+ # 자동 번호 데이터 파싱 (12 bytes: 속성 4 + 번호 2 + 기호들 6)
295
+ if len(element.data) >= 12:
296
+ attrs = struct.unpack('<I', element.data[0:4])[0]
297
+ number = struct.unpack('<H', element.data[4:6])[0]
298
+ number_type = attrs & 0xF # bit 0~3: 번호 종류
299
+ number_format = (attrs >> 4) & 0xFF # bit 4~11: 번호 모양
300
+
301
+ type_names = {0: "쪽 번호", 1: "각주 번호", 2: "미주 번호",
302
+ 3: "그림 번호", 4: "표 번호", 5: "수식 번호"}
303
+ f.write(f" - 번호 종류: {type_names.get(number_type, f'알수없음({number_type})')}\n")
304
+ f.write(f" - 번호: {number}\n")
305
+ f.write(f" - 번호 모양: {number_format}\n")
306
+ elif element_type == ElementType.NEW_NUMBER:
307
+ f.write(f"[새번호지정 {index}]\n")
308
+ if hasattr(element, 'control_id') and element.control_id:
309
+ f.write(f" - Control ID: 0x{element.control_id:08X}\n")
310
+ f.write(f" - code: {element.code}\n")
311
+ if hasattr(element, 'data') and element.data:
312
+ # 새 번호 지정 데이터 파싱 (8 bytes: 속성 4 + 번호 2)
313
+ if len(element.data) >= 6:
314
+ attrs = struct.unpack('<I', element.data[0:4])[0]
315
+ number = struct.unpack('<H', element.data[4:6])[0]
316
+ number_type = attrs & 0xF # bit 0~3: 번호 종류
317
+
318
+ type_names = {0: "쪽 번호", 1: "각주 번호", 2: "미주 번호",
319
+ 3: "그림 번호", 4: "표 번호", 5: "수식 번호"}
320
+ f.write(f" - 번호 종류: {type_names.get(number_type, f'알수없음({number_type})')}\n")
321
+ f.write(f" - 새 시작 번호: {number}\n")
322
+ elif element_type == ElementType.PAGE_NUM_POS:
323
+ f.write(f"[쪽번호위치 {index}]\n")
324
+ if hasattr(element, 'control_id') and element.control_id:
325
+ f.write(f" - Control ID: 0x{element.control_id:08X}\n")
326
+ f.write(f" - code: {element.code}\n")
327
+ if hasattr(element, 'data') and element.data:
328
+ # 쪽 번호 위치 데이터 파싱 (12 bytes)
329
+ if len(element.data) >= 12:
330
+ attrs = struct.unpack('<I', element.data[0:4])[0]
331
+ position = (attrs >> 8) & 0xF # bit 8~11: 위치
332
+ positions = {0: "없음", 1: "왼쪽 위", 2: "가운데 위", 3: "오른쪽 위",
333
+ 4: "왼쪽 아래", 5: "가운데 아래", 6: "오른쪽 아래",
334
+ 7: "바깥쪽 위", 8: "바깥쪽 아래", 9: "안쪽 위", 10: "안쪽 아래"}
335
+ f.write(f" - 표시 위치: {positions.get(position, f'알수없음({position})')}\n")
336
+ else:
337
+ f.write(f"[알수없음 {element_type.value} {index}]\n")
338
+
339
+ index += 1
340
+
341
+ f.write(f"\n[12] 파일 저장")
342
+ f.write(f" > 저장 완료: {output_file}")
343
+
344
+ print("\n" + "=" * 80)
345
+ print("완료!")
346
+ print("=" * 80)
347
+
348
+
349
+ if __name__ == "__main__":
350
+ main()
@@ -0,0 +1,26 @@
1
+ """hwp_to_markdown 함수 테스트"""
2
+
3
+ import sys
4
+ from pathlib import Path
5
+
6
+ sys.path.insert(0, str(Path(__file__).parent.parent))
7
+
8
+ from helper_hwp import hwp_to_markdown
9
+
10
+ def test_hwp_to_markdown():
11
+ hwp_path = Path(__file__).parent / "test.hwp"
12
+ md_path = Path(__file__).parent / "test_hwp_to_markdown.md"
13
+
14
+ # HWP에서 마크다운 추출
15
+ markdown = hwp_to_markdown(str(hwp_path))
16
+
17
+ # 파일로 저장
18
+ with open(md_path, 'w', encoding='utf-8') as f:
19
+ f.write(markdown)
20
+
21
+ print(f"변환 완료: {md_path}")
22
+ print(f"\n=== 출력 내용 ({len(markdown)} 글자) ===")
23
+ print(markdown[:1000])
24
+
25
+ if __name__ == "__main__":
26
+ test_hwp_to_markdown()
@@ -0,0 +1,112 @@
1
+ import sys
2
+ import platform
3
+ import shutil
4
+ from pathlib import Path
5
+ import pypandoc
6
+ from matplotlib import font_manager
7
+
8
+ sys.path.insert(0, str(Path(__file__).parent.parent))
9
+
10
+ from helper_hwp import hwp_to_markdown
11
+
12
+ def get_available_korean_font() -> str:
13
+ """시스템에서 사용 가능한 한글 폰트 반환
14
+
15
+ Returns:
16
+ str: 사용 가능한 폰트명
17
+
18
+ Raises:
19
+ SystemExit: 한글 폰트가 없을 경우
20
+ """
21
+ system = platform.system()
22
+
23
+ # 우선순위별 폰트 목록 (유니코드 포괄 범위 우선)
24
+ if system == "Windows":
25
+ font_candidates = ["Arial Unicode MS", "NotoSans CJK KR", "Malgun Gothic", "맑은 고딕"]
26
+ install_url = "https://github.com/notofonts/noto-cjk/releases (Noto Sans CJK)"
27
+ else: # Linux/macOS
28
+ font_candidates = ["Noto Sans CJK KR", "NanumGothic"]
29
+ install_url = "sudo apt install fonts-noto-cjk (Ubuntu/Debian)"
30
+
31
+ # 시스템 폰트 목록 조회
32
+ available_fonts = {f.name for f in font_manager.fontManager.ttflist}
33
+
34
+ # 우선순위대로 확인
35
+ for font in font_candidates:
36
+ if font in available_fonts:
37
+ return font
38
+
39
+ # 폰트 없음
40
+ print(f"\n[오류] 한글 폰트를 찾을 수 없습니다.")
41
+ print(f"설치 필요: {', '.join(font_candidates[:2])}")
42
+ print(f"설치 방법: {install_url}")
43
+ sys.exit(1)
44
+
45
+ def test_hwp_to_markdown_pdf() -> None:
46
+ """HWP → Markdown → PDF 변환 테스트 (한글 지원)"""
47
+ # XeLaTeX 경로 확인 및 설정
48
+ xelatex_path = shutil.which("xelatex")
49
+
50
+ if not xelatex_path:
51
+ # Windows MiKTeX 기본 경로 확인
52
+ miktex_paths = [
53
+ r"C:\Program Files\MiKTeX\miktex\bin\x64",
54
+ r"C:\Program Files (x86)\MiKTeX\miktex\bin\x64",
55
+ r"C:\Users\{}\AppData\Local\Programs\MiKTeX\miktex\bin\x64".format(Path.home().name),
56
+ ]
57
+
58
+ for miktex_bin in miktex_paths:
59
+ if Path(miktex_bin).exists():
60
+ import os
61
+ os.environ["PATH"] = f"{miktex_bin};{os.environ['PATH']}"
62
+ xelatex_path = shutil.which("xelatex")
63
+ if xelatex_path:
64
+ print(f"XeLaTeX 경로 설정: {miktex_bin}")
65
+ break
66
+
67
+ if not xelatex_path:
68
+ print("\n[오류] XeLaTeX을 찾을 수 없습니다.")
69
+ print("MiKTeX 설치: https://miktex.org/download")
70
+ print("\n수동 PATH 추가:")
71
+ print(' setx PATH "%PATH%;C:\\Program Files\\MiKTeX\\miktex\\bin\\x64"')
72
+ sys.exit(1)
73
+
74
+ hwp_path = Path(__file__).parent / "test.hwp"
75
+ pdf_path = Path(__file__).parent / "test_hwp_to_markdown_pdf.pdf"
76
+ md_path = Path(__file__).parent / "test_hwp_to_markdown_pdf.md"
77
+ header_path = Path(__file__).parent / "test_hwp_to_markdown_pdf.tex"
78
+
79
+ md_content = hwp_to_markdown(str(hwp_path))
80
+ md_path.write_text(md_content, encoding="utf-8")
81
+
82
+ mainfont = get_available_korean_font()
83
+ bold_font = f"{mainfont} Bold" if "Malgun Gothic" in mainfont else mainfont
84
+ print(f"사용 폰트: {mainfont}")
85
+
86
+ # LaTeX 헤더 파일 생성
87
+ header_content = (
88
+ r"\usepackage{fontspec}" "\n"
89
+ rf"\setmainfont{{{mainfont}}}[BoldFont={{{bold_font}}}]" "\n"
90
+ rf"\setsansfont{{{mainfont}}}" "\n"
91
+ rf"\setmonofont{{{mainfont}}}" "\n"
92
+ r"\usepackage{xeCJK}" "\n"
93
+ rf"\setCJKmainfont{{{mainfont}}}[BoldFont={{{bold_font}}}]" "\n"
94
+ r"\usepackage[margin=1cm]{geometry}"
95
+ )
96
+ header_path.write_text(header_content, encoding="utf-8")
97
+
98
+ pypandoc.convert_file(
99
+ str(md_path),
100
+ "pdf",
101
+ outputfile=str(pdf_path),
102
+ extra_args=[
103
+ "--pdf-engine=xelatex",
104
+ f"--include-in-header={header_path}",
105
+ ],
106
+ )
107
+
108
+ print(f"변환 완료: {md_path}")
109
+ print(f"변환 완료: {pdf_path}")
110
+
111
+ if __name__ == "__main__":
112
+ test_hwp_to_markdown_pdf()
@@ -0,0 +1,26 @@
1
+ """hwp_to_txt 함수 테스트"""
2
+
3
+ import sys
4
+ from pathlib import Path
5
+
6
+ sys.path.insert(0, str(Path(__file__).parent.parent))
7
+
8
+ from helper_hwp import hwp_to_txt
9
+
10
+ def test_hwp_to_txt():
11
+ hwp_path = Path(__file__).parent / "test.hwp"
12
+ txt_path = Path(__file__).parent / "test_hwp_to_txt.txt"
13
+
14
+ # HWP에서 텍스트 추출
15
+ text = hwp_to_txt(str(hwp_path))
16
+
17
+ # 파일로 저장
18
+ with open(txt_path, 'w', encoding='utf-8') as f:
19
+ f.write(text)
20
+
21
+ print(f"변환 완료: {txt_path}")
22
+ print(f"\n=== 출력 내용 ({len(text)} 글자) ===")
23
+ print(text[:500])
24
+
25
+ if __name__ == "__main__":
26
+ test_hwp_to_txt()