rhwp 0.9.0

HWP/HWPX document engine for Rust applications, WebAssembly, and CLI automation
Documentation
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
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
use crate::wmf::{
    converter::svg::node::{Data, Node},
    imports::*,
    parser::*,
};

pub fn css_color_from_color_ref(c: &ColorRef) -> String {
    format!("#{:02X}{:02X}{:02X}", c.red, c.green, c.blue)
}

pub fn url_string(link: &str) -> String {
    format!("url({link})")
}

pub fn as_point_string(point: &PointS) -> String {
    format!("{},{}", point.x, point.y)
}

impl crate::wmf::converter::Bitmap {
    pub fn as_data_url(&self) -> String {
        use base64::{engine::general_purpose::STANDARD, Engine};
        // [Task #860] SVG renderer (rsvg-convert, 브라우저) 가 `data:image/bmp` URI 미지원.
        // BMP → PNG 재인코딩 후 data:image/png URI 로 embed.
        // BMP decode 실패 시 fallback 으로 BMP URI 유지 (graceful degradation).
        if let Some(png) = crate::renderer::svg::bmp_bytes_to_png_bytes(self.as_slice()) {
            format!("data:image/png;base64,{}", STANDARD.encode(&png))
        } else {
            format!("data:image/bmp;base64,{}", STANDARD.encode(self.as_slice()))
        }
    }
}

impl Brush {
    pub fn as_filter(&self) -> Node {
        match self {
            Brush::DIBPatternPT { brush_hatch, .. } => {
                let data = crate::wmf::converter::Bitmap::from(brush_hatch.clone()).as_data_url();
                Node::new("filter").add(Node::new("feImage").set("href", data))
            }
            Brush::Hatched {
                color_ref,
                brush_hatch,
            } => {
                let data = crate::wmf::converter::Bitmap::from((color_ref.clone(), *brush_hatch))
                    .as_data_url();
                Node::new("filter").add(Node::new("feImage").set("href", data))
            }
            Brush::Pattern { brush_hatch } => {
                let bitmap = crate::wmf::parser::DeviceIndependentBitmap::from(brush_hatch.clone());
                let data = crate::wmf::converter::Bitmap::from(bitmap).as_data_url();

                Node::new("filter").add(Node::new("feImage").set("href", data))
            }
            Brush::Solid { color_ref } => Node::new("filter")
                .set("x", "0")
                .set("y", "0")
                .set("width", "1")
                .set("height", "1")
                .add(
                    Node::new("feFlood")
                        .set("flood-color", css_color_from_color_ref(color_ref))
                        .set("result", "bg"),
                )
                .add(
                    Node::new("feMerge")
                        .add(Node::new("feMergeNode").set("in", "bg"))
                        .add(Node::new("feMergeNode").set("in", "SourceGraphic")),
                ),
            Brush::Null => Node::new("filter")
                .set("x", "0")
                .set("y", "0")
                .set("width", "0")
                .set("height", "0")
                .add(
                    Node::new("feFlood")
                        .set("flood-color", "#000")
                        .set("flood-opacity", "0"),
                ),
        }
    }
}

#[derive(Clone, Debug)]
pub enum Fill {
    Pattern { pattern: Node },
    Value { value: String },
}

impl From<Brush> for Fill {
    fn from(v: Brush) -> Self {
        match v {
            Brush::DIBPatternPT { brush_hatch, .. } => {
                let data = crate::wmf::converter::Bitmap::from(brush_hatch.clone()).as_data_url();
                let image = Node::new("image")
                    .set("x", "0")
                    .set("y", "0")
                    .set("width", brush_hatch.dib_header_info.width())
                    .set("height", brush_hatch.dib_header_info.height())
                    .set("href", data);
                let pattern = Node::new("pattern")
                    .set("patternUnits", "userSpaceOnUse")
                    .set("patternContentUnits", "userSpaceOnUse")
                    .set("x", "0")
                    .set("y", "0")
                    .set("width", brush_hatch.dib_header_info.width())
                    .set("height", brush_hatch.dib_header_info.height())
                    .add(image);

                Fill::Pattern { pattern }
            }
            Brush::Hatched {
                color_ref,
                brush_hatch,
            } => {
                let path = match brush_hatch {
                    HatchStyle::HS_HORIZONTAL => {
                        let data = Data::new().move_to("0 0").line_to("10 0");

                        Node::new("path")
                            .set("stroke", css_color_from_color_ref(&color_ref))
                            .set("d", data)
                    }
                    HatchStyle::HS_VERTICAL => {
                        let data = Data::new().move_to("0 0").line_to("0 10");

                        Node::new("path")
                            .set("stroke", css_color_from_color_ref(&color_ref))
                            .set("d", data)
                    }
                    HatchStyle::HS_FDIAGONAL => {
                        let data = Data::new().move_to("0 10").line_to("10 0");

                        Node::new("path")
                            .set("stroke", css_color_from_color_ref(&color_ref))
                            .set("d", data)
                    }
                    HatchStyle::HS_BDIAGONAL => {
                        let data = Data::new().move_to("0 0").line_to("10 10");

                        Node::new("path")
                            .set("stroke", css_color_from_color_ref(&color_ref))
                            .set("d", data)
                    }
                    HatchStyle::HS_CROSS => {
                        let data = Data::new()
                            .move_to("0 0")
                            .line_to("10 0")
                            .move_to("0 0")
                            .line_to("0 10");

                        Node::new("path")
                            .set("stroke", css_color_from_color_ref(&color_ref))
                            .set("d", data)
                    }
                    HatchStyle::HS_DIAGCROSS => {
                        let data = Data::new()
                            .move_to("0 0")
                            .line_to("10 10")
                            .move_to("10 0")
                            .line_to("0 10");

                        Node::new("path")
                            .set("stroke", css_color_from_color_ref(&color_ref))
                            .set("d", data)
                    }
                };

                let pattern = Node::new("pattern")
                    .set("patternUnits", "userSpaceOnUse")
                    .set("patternContentUnits", "userSpaceOnUse")
                    .set("x", "0")
                    .set("y", "0")
                    .set("width", "10")
                    .set("height", "10")
                    .add(path);

                Fill::Pattern { pattern }
            }
            Brush::Pattern { brush_hatch } => {
                let bitmap = crate::wmf::parser::DeviceIndependentBitmap::from(brush_hatch.clone());
                let data = crate::wmf::converter::Bitmap::from(bitmap).as_data_url();
                let image = Node::new("image")
                    .set("x", "0")
                    .set("y", "0")
                    .set("width", brush_hatch.width)
                    .set("height", brush_hatch.height)
                    .set("href", data);
                let pattern = Node::new("pattern")
                    .set("patternUnits", "userSpaceOnUse")
                    .set("patternContentUnits", "userSpaceOnUse")
                    .set("x", "0")
                    .set("y", "0")
                    .set("width", brush_hatch.width)
                    .set("height", brush_hatch.height)
                    .add(image);

                Fill::Pattern { pattern }
            }
            Brush::Solid { color_ref } => Fill::Value {
                value: css_color_from_color_ref(&color_ref),
            },
            Brush::Null => Fill::Value {
                value: "none".to_owned(),
            },
        }
    }
}

#[derive(Clone, Debug)]
pub struct Stroke {
    /// set true if stroke should not be rendered
    none: bool,
    /// sets the color of the line around an element
    color: ColorRef,
    /// sets the width of the line around an element
    width: i16,
    /// sets the opacity of the line around an element
    opacity: f32,
    /// sets the shape of the end-lines for a line or open path
    line_cap: String,
    /// sets the line to show as a dashed line
    dash_array: String,
    /// sets the shape of the corners where two lines meet
    line_join: String,
}

impl Default for Stroke {
    fn default() -> Self {
        Self {
            none: false,
            color: ColorRef::black(),
            width: 1,
            opacity: 1_f32,
            line_cap: "butt".to_owned(),
            dash_array: "none".to_owned(),
            line_join: "miter".to_owned(),
        }
    }
}

impl From<Pen> for Stroke {
    fn from(v: Pen) -> Self {
        if v.style.style == PenStyle::PS_NULL {
            return Self {
                none: true,
                ..Default::default()
            };
        }

        let mut stroke = Self::default();

        match v.style.end_cap {
            PenStyle::PS_SOLID => {
                "round".clone_into(&mut stroke.line_cap);
            }
            PenStyle::PS_ENDCAP_SQUARE => {
                "square".clone_into(&mut stroke.line_cap);
            }
            _ => {
                "butt".clone_into(&mut stroke.line_cap);
            }
        }

        match v.style.line_join {
            PenStyle::PS_SOLID => {
                "round".clone_into(&mut stroke.line_join);
            }
            PenStyle::PS_JOIN_BEVEL => {
                "bevel".clone_into(&mut stroke.line_join);
            }
            _ => {
                "miter".clone_into(&mut stroke.line_join);
            }
        }

        // [fuzz] 펜 두께는 파일의 i16 이라 `* 10` 이 넘친다 — i32 로 올려 계산한다.
        match v.style.style {
            PenStyle::PS_DASH => {
                stroke.dash_array = format!("{v} {v}", v = i32::from(v.width.x) * 10);
            }
            PenStyle::PS_ALTERNATE | PenStyle::PS_DOT => {
                stroke.dash_array = format!("{} {}", v.width.x, i32::from(v.width.x) * 10);
            }
            PenStyle::PS_DASHDOT => {
                stroke.dash_array = format!(
                    "{} {} {} {}",
                    i32::from(v.width.x) * 10,
                    i32::from(v.width.x) * 2,
                    v.width.x,
                    i32::from(v.width.x) * 2,
                );
            }
            PenStyle::PS_DASHDOTDOT => {
                stroke.dash_array = format!(
                    "{} {} {} {} {} {}",
                    i32::from(v.width.x) * 10,
                    i32::from(v.width.x) * 2,
                    v.width.x,
                    i32::from(v.width.x) * 2,
                    v.width.x,
                    i32::from(v.width.x) * 2,
                );
            }
            _ => {}
        }

        stroke.color = v.color_ref;
        stroke.width = if v.width.x == 0 { 1 } else { v.width.x };
        stroke
    }
}

impl From<Brush> for Stroke {
    fn from(v: Brush) -> Self {
        match v {
            Brush::DIBPatternPT { .. } => Self {
                none: true,
                ..Default::default()
            },
            Brush::Hatched { color_ref, .. } | Brush::Solid { color_ref } => Self {
                color: color_ref,
                ..Default::default()
            },
            Brush::Pattern { .. } => Self {
                ..Default::default()
            },
            Brush::Null => Self {
                none: true,
                width: 0,
                ..Default::default()
            },
        }
    }
}

impl Stroke {
    pub fn color(&self) -> String {
        css_color_from_color_ref(&self.color)
    }

    pub fn dash_array(&self) -> String {
        self.dash_array.clone()
    }

    pub fn line_cap(&self) -> String {
        self.line_cap.clone()
    }

    pub fn line_join(&self) -> String {
        self.line_join.clone()
    }

    pub fn opacity(&self) -> String {
        format!("{:.02}", self.opacity)
    }

    pub fn width(&self) -> i16 {
        self.width
    }

    pub fn set_props(&self, elem: Node) -> Node {
        if self.none {
            return elem.set("stroke", "none");
        }

        elem.set("stroke", self.color())
            .set("stroke-dasharray", self.dash_array())
            .set("stroke-linecap", self.line_cap())
            .set("stroke-linejoin", self.line_join())
            .set("stroke-opacity", self.opacity())
            .set("stroke-width", self.width())
    }
}

impl Font {
    pub fn set_props(&self, mut elem: Node, point: &PointS) -> (Node, Vec<String>) {
        let mut styles = Vec::with_capacity(2);

        if self.italic {
            styles.push("font-style: italic;".to_owned());
        }

        {
            let mut v = Vec::with_capacity(2);

            if self.underline {
                v.push("underline");
            }

            if self.strike_out {
                v.push("line-through");
            }

            if !v.is_empty() {
                styles.push(format!("text-decoration: {};", v.join(" ")));
            }
        };

        if self.orientation != 0 {
            // [fuzz] 파일의 i16 끝값에서 뺄셈·부호 반전이 넘치지 않게 i32 로 계산한다.
            let ori = i32::from(self.orientation) - i32::from(self.escapement);

            if ori != 0 {
                elem = elem.set("rotate", -ori / 10);
            }
        }

        if self.escapement != 0 {
            elem = elem.set(
                "transform",
                format!(
                    "rotate({}, {} {})",
                    -i32::from(self.escapement) / 10,
                    point.x,
                    point.y
                ),
            );
        }

        let mut font_family: Vec<String> = vec![];

        // 본문과 같은 설치 별칭을 사용해 한국어 face가 영문 family로 설치된 경우도 찾는다.
        for face in std::iter::once(&self.facename).chain(&self.fallback_facename) {
            for name in std::iter::once(face.as_str()).chain(
                crate::renderer::installed_render_font_aliases(face)
                    .iter()
                    .copied(),
            ) {
                if !font_family.iter().any(|existing| existing == name) {
                    font_family.push(name.to_owned());
                }
            }
        }

        // 한컴 WMF 의 한국어 폰트 (예: "굴림체") 가 시스템에 미설치된 환경에서
        // SVG renderer 가 fallback 못 찾으면 글자가 깨져 보임. facename/fallback
        // 에 한글 char (U+AC00~U+D7A3) 있으면 시스템 한국어 폰트 chain 추가.
        let has_korean = font_family
            .iter()
            .any(|f| f.chars().any(|c| ('\u{AC00}'..='\u{D7A3}').contains(&c)));
        if has_korean {
            for fallback in [
                "Apple SD Gothic Neo",
                "Malgun Gothic",
                "Nanum Gothic",
                "Noto Sans CJK KR",
                "sans-serif",
            ] {
                font_family.push(fallback.to_string());
            }
        } else {
            // 영문 face(예: "Calibri")만 지정된 글자도 미설치 환경에서 renderer 기본 글꼴(명조)로
            // 떨어지지 않게 LOGFONT 계열로 대체 사슬을 단다. 한글은 Windows 글꼴 연결처럼
            // 맑은 고딕 계열로 간다(1790387 35쪽 차트: "Calibri" 의 "2018년" — 한/글 PDF 는 고딕).
            let chain: &[&str] = match self.pitch_and_family.family {
                FamilyFont::FF_ROMAN => &[
                    "Times New Roman",
                    "Batang",
                    "바탕",
                    "Noto Serif CJK KR",
                    "serif",
                ],
                FamilyFont::FF_MODERN => &["Courier New", "monospace"],
                _ => &[
                    "Arial",
                    "Malgun Gothic",
                    "맑은 고딕",
                    "Apple SD Gothic Neo",
                    "Noto Sans CJK KR",
                    "sans-serif",
                ],
            };
            for fallback in chain {
                if !font_family.iter().any(|existing| existing == fallback) {
                    font_family.push((*fallback).to_string());
                }
            }
        }

        elem = elem
            .set("font-family", format!("'{}'", font_family.join("','")))
            .set("font-size", self.height.saturating_abs())
            .set("font-weight", self.weight);

        (elem, styles)
    }
}