use super::image_resolver::{
bmp_bytes_to_png_bytes, detect_image_mime_type, pcx_bytes_to_png_bytes, tiff_bytes_to_png_bytes,
};
use super::render_tree::{PageRenderTree, RenderNode, RenderNodeType};
use super::svg::convert_wmf_to_svg;
use super::{LineStyle, PathCommand, Renderer, ShapeStyle, TextStyle};
use crate::model::style::UnderlineType;
use base64::Engine;
pub struct HtmlRenderer {
output: String,
width: f64,
height: f64,
pub show_paragraph_marks: bool,
pub show_control_codes: bool,
}
impl HtmlRenderer {
pub fn new() -> Self {
Self {
output: String::new(),
width: 0.0,
height: 0.0,
show_paragraph_marks: false,
show_control_codes: false,
}
}
pub fn output(&self) -> &str {
&self.output
}
pub fn render_tree(&mut self, tree: &PageRenderTree) {
self.render_node(&tree.root);
}
fn render_node(&mut self, node: &RenderNode) {
if !node.visible {
return;
}
match &node.node_type {
RenderNodeType::Page(page) => {
self.begin_page(page.width, page.height);
}
RenderNodeType::PageBackground(bg) => {
let bg_color = bg
.background_color
.map(|c| color_to_css(c))
.unwrap_or_else(|| "#ffffff".to_string());
self.output.push_str(&format!(
"<div class=\"page-bg\" style=\"position:absolute;left:{}px;top:{}px;width:{}px;height:{}px;background:{};\"></div>\n",
node.bbox.x, node.bbox.y,
node.bbox.width, node.bbox.height,
bg_color,
));
}
RenderNodeType::Header => {
self.output.push_str(&format!(
"<header class=\"page-header\" style=\"position:absolute;left:{}px;top:{}px;width:{}px;height:{}px;\">\n",
node.bbox.x, node.bbox.y, node.bbox.width, node.bbox.height,
));
for child in &node.children {
self.render_node(child);
}
self.output.push_str("</header>\n");
return; }
RenderNodeType::Footer => {
self.output.push_str(&format!(
"<footer class=\"page-footer\" style=\"position:absolute;left:{}px;top:{}px;width:{}px;height:{}px;\">\n",
node.bbox.x, node.bbox.y, node.bbox.width, node.bbox.height,
));
for child in &node.children {
self.render_node(child);
}
self.output.push_str("</footer>\n");
return;
}
RenderNodeType::Body { .. } => {
self.output.push_str(&format!(
"<div class=\"page-body\" style=\"position:absolute;left:{}px;top:{}px;width:{}px;height:{}px;\">\n",
node.bbox.x, node.bbox.y, node.bbox.width, node.bbox.height,
));
for child in &node.children {
self.render_node(child);
}
self.output.push_str("</div>\n");
return;
}
RenderNodeType::Column(col_idx) => {
self.output.push_str(&format!(
"<div class=\"column column-{}\" style=\"position:absolute;left:{}px;top:{}px;width:{}px;height:{}px;\">\n",
col_idx, node.bbox.x, node.bbox.y, node.bbox.width, node.bbox.height,
));
for child in &node.children {
self.render_node(child);
}
self.output.push_str("</div>\n");
return;
}
RenderNodeType::TextLine(line) => {
self.output.push_str(&format!(
"<div class=\"text-line\" style=\"position:absolute;left:{}px;top:{}px;width:{}px;height:{}px;line-height:{}px;\">\n",
node.bbox.x, node.bbox.y, node.bbox.width, node.bbox.height, line.line_height,
));
for child in &node.children {
self.render_node(child);
}
self.output.push_str("</div>\n");
return;
}
RenderNodeType::TextRun(run) => {
self.draw_text_positioned(
run.display_or_text(),
node.bbox.x,
node.bbox.y,
&run.style,
run.validated_layout_positions_for(run.display_or_text()),
);
if self.show_paragraph_marks || self.show_control_codes {
let font_size = run.style.effective_font_size();
if !run.text.is_empty() {
let char_positions = run.replay_positions_for(&run.text);
let mark_font_size = font_size * 0.5;
for (i, c) in run.text.chars().enumerate() {
if c == ' ' {
let cx = node.bbox.x + char_positions[i];
let next_x = if i + 1 < char_positions.len() {
node.bbox.x + char_positions[i + 1]
} else {
node.bbox.x + node.bbox.width
};
let mid_x = (cx + next_x) / 2.0 - mark_font_size * 0.25;
self.output.push_str(&format!(
"<span class=\"para-mark\" style=\"position:absolute;left:{}px;top:{}px;font-size:{}px;color:#0066FF;\">\u{2228}</span>\n",
mid_x, node.bbox.y, mark_font_size,
));
} else if c == '\t' {
let cx = node.bbox.x + char_positions[i];
self.output.push_str(&format!(
"<span class=\"para-mark\" style=\"position:absolute;left:{}px;top:{}px;font-size:{}px;color:#0066FF;\">\u{2192}</span>\n",
cx, node.bbox.y, mark_font_size,
));
}
}
}
if run.is_para_end || run.is_line_break_end {
let mark_x = if run.text.is_empty() {
node.bbox.x
} else {
node.bbox.x + node.bbox.width
};
let mark = if run.is_line_break_end {
"\u{2193}"
} else {
"\u{21B5}"
};
self.output.push_str(&format!(
"<span class=\"para-mark\" style=\"position:absolute;left:{}px;top:{}px;font-size:{}px;color:#0066FF;\">{}</span>\n",
mark_x, node.bbox.y, font_size, mark,
));
}
}
}
RenderNodeType::Table(_table) => {
self.output.push_str(&format!(
"<table class=\"hwp-table\" style=\"position:absolute;left:{}px;top:{}px;width:{}px;height:{}px;border-collapse:collapse;\">\n",
node.bbox.x, node.bbox.y, node.bbox.width, node.bbox.height,
));
for child in &node.children {
self.render_node(child);
}
self.output.push_str("</table>\n");
return;
}
RenderNodeType::TableCell(cell) => {
self.output.push_str(&format!(
"<td colspan=\"{}\" rowspan=\"{}\" style=\"width:{}px;height:{}px;\">\n",
cell.col_span, cell.row_span, node.bbox.width, node.bbox.height,
));
for child in &node.children {
self.render_node(child);
}
self.output.push_str("</td>\n");
return;
}
RenderNodeType::Rectangle(rect) => {
self.draw_rect(
node.bbox.x,
node.bbox.y,
node.bbox.width,
node.bbox.height,
rect.corner_radius,
&rect.style,
);
}
RenderNodeType::Image(img) => {
if img.crop.is_some_and(|(l, t, r, b)| r <= l || b <= t) {
return;
}
if let Some(ref data) = img.data {
let paint = img.paint_bbox(&node.bbox);
self.draw_image(data, paint.x, paint.y, paint.width, paint.height);
} else {
self.output.push_str(&format!(
"<div class=\"hwp-image\" style=\"position:absolute;left:{}px;top:{}px;width:{}px;height:{}px;background:#eee;\"></div>\n",
node.bbox.x, node.bbox.y, node.bbox.width, node.bbox.height,
));
}
}
_ => {}
}
for child in &node.children {
self.render_node(child);
}
if self.show_control_codes {
let label = match &node.node_type {
RenderNodeType::FormObject(_) => Some("[양식]"),
_ => node.control_code_label(),
};
if let Some(label) = label {
let fs = 10.0;
self.output.push_str(&format!(
"<span class=\"control-mark\" style=\"position:absolute;left:{}px;top:{}px;font-size:{}px;color:#CC3333;\">{}</span>\n",
node.bbox.x, node.bbox.y, fs, label,
));
}
}
if matches!(node.node_type, RenderNodeType::Page(_)) {
self.end_page();
}
}
}
impl Renderer for HtmlRenderer {
fn begin_page(&mut self, width: f64, height: f64) {
self.width = width;
self.height = height;
self.output.clear();
self.output.push_str(&format!(
"<div class=\"hwp-page\" style=\"position:relative;width:{}px;height:{}px;overflow:hidden;\">\n",
width, height,
));
}
fn end_page(&mut self) {
self.output.push_str("</div>\n");
}
fn draw_text(&mut self, text: &str, x: f64, y: f64, style: &TextStyle) {
self.draw_text_positioned(text, x, y, style, None);
}
fn draw_text_positioned(
&mut self,
text: &str,
x: f64,
y: f64,
style: &TextStyle,
layout_positions: Option<&[f64]>,
) {
let text = &crate::renderer::composer::expand_pua_render_text_in_style(text, style);
let font_size = style.effective_font_size();
let color = color_to_css(style.color);
let font_family = if style.font_family.is_empty() {
"sans-serif".to_string()
} else {
let fallback = super::generic_fallback(&style.font_family);
match super::base_family_without_weight_suffix(&style.font_family) {
Some(base) => format!(
"'{}', '{}', {}",
escape_html(&style.font_family),
escape_html(&base),
fallback
),
None => format!("'{}', {}", escape_html(&style.font_family), fallback),
}
};
let (draw_size, draw_y) = style.script_draw_metrics(font_size, y);
let mut css = format!(
"position:absolute;left:{}px;top:{}px;font-family:{};font-size:{}px;color:{};",
x, draw_y, font_family, draw_size, color,
);
if let Some(weight) = style.css_font_weight() {
css.push_str(&format!("font-weight:{};", weight));
}
if style.italic {
css.push_str("font-style:italic;");
}
if !matches!(style.underline, UnderlineType::None) {
let ul_style = match style.underline_shape {
1 | 5 => "dashed",
2 | 6 => "dotted",
3 | 4 => "dashed",
7..=9 => "double",
11 => "wavy",
_ => "solid",
};
let ul_pos = if matches!(style.underline, UnderlineType::Top) {
"text-underline-position:above;"
} else {
""
};
css.push_str(&format!(
"text-decoration:underline;text-decoration-style:{};{}",
ul_style, ul_pos
));
}
if style.strikethrough {
let st_style = match style.strike_shape {
1 | 5 => "dashed",
2 | 6 => "dotted",
3 | 4 => "dashed",
7..=9 => "double",
11 => "wavy",
_ => "solid",
};
css.push_str(&format!(
"text-decoration:line-through;text-decoration-style:{};",
st_style
));
}
if style.outline_type > 0 {
css.push_str(&format!(
"-webkit-text-stroke:1px {};color:transparent;",
color
));
}
if let Some(p) = style.text_paint {
let rgba = |color: u32, alpha: u8| {
format!(
"rgba({},{},{},{})",
color & 255,
(color >> 8) & 255,
(color >> 16) & 255,
f64::from(alpha) / 255.0
)
};
css.push_str(&format!(
"-webkit-text-stroke:{}px {};-webkit-text-fill-color:{};paint-order:fill stroke;",
if p.width == 0.0 { 1.0 } else { p.width },
rgba(p.paint.stroke_color, p.paint.stroke_alpha),
rgba(
style.color,
if p.paint.fill { p.paint.fill_alpha } else { 0 }
)
));
}
if style.emboss {
css.push_str("text-shadow:-1px -1px 0 #999,1px 1px 0 #fff;");
}
if style.engrave {
css.push_str("text-shadow:1px 1px 0 #999,-1px -1px 0 #fff;");
}
if crate::model::color::char_shade(style.shade_color).is_some() {
css.push_str(&format!(
"background-color:{};",
color_to_css(style.shade_color)
));
}
let (_, ratio) = style.ratio_draw_params(1.0);
if style.has_horizontal_ratio() {
css.push_str(&format!(
"transform:scaleX({:.4});transform-origin:left;",
ratio
));
}
if let Some(positions) = super::validated_replay_positions(text, layout_positions) {
let left_token = format!("left:{}px;", x);
for (index, character) in text.chars().enumerate() {
let positioned_left = format!("left:{}px;", x + positions[index]);
let positioned_css = css.replacen(&left_token, &positioned_left, 1);
self.output.push_str(&format!(
"<span class=\"text-run text-run-positioned\" style=\"{}\">{}</span>\n",
positioned_css,
escape_html(&character.to_string()),
));
}
} else {
self.output.push_str(&format!(
"<span class=\"text-run\" style=\"{}\">{}</span>\n",
css,
escape_html(text),
));
}
}
fn draw_rect(
&mut self,
x: f64,
y: f64,
w: f64,
h: f64,
corner_radius: f64,
style: &ShapeStyle,
) {
let mut css = format!(
"position:absolute;left:{}px;top:{}px;width:{}px;height:{}px;",
x, y, w, h,
);
if corner_radius > 0.0 {
css.push_str(&format!("border-radius:{}px;", corner_radius));
}
if let Some(fill) = style.fill_color {
css.push_str(&format!("background:{};", color_to_css(fill)));
}
if let Some(stroke) = style.stroke_color {
css.push_str(&format!(
"border:{}px solid {};",
style.stroke_width,
color_to_css(stroke)
));
}
self.output.push_str(&format!(
"<div class=\"hwp-rect\" style=\"{}\"></div>\n",
css,
));
}
fn draw_line(&mut self, x1: f64, y1: f64, x2: f64, y2: f64, _style: &LineStyle) {
let min_x = x1.min(x2);
let min_y = y1.min(y2);
let w = (x2 - x1).abs().max(1.0);
let h = (y2 - y1).abs().max(1.0);
self.output.push_str(&format!(
"<svg class=\"hwp-line\" style=\"position:absolute;left:{}px;top:{}px;width:{}px;height:{}px;\"><line x1=\"{}\" y1=\"{}\" x2=\"{}\" y2=\"{}\" stroke=\"black\" stroke-width=\"1\"/></svg>\n",
min_x, min_y, w, h, x1 - min_x, y1 - min_y, x2 - min_x, y2 - min_y,
));
}
fn draw_ellipse(&mut self, cx: f64, cy: f64, rx: f64, ry: f64, style: &ShapeStyle) {
let mut css = format!(
"position:absolute;left:{}px;top:{}px;width:{}px;height:{}px;border-radius:50%;",
cx - rx,
cy - ry,
rx * 2.0,
ry * 2.0,
);
if let Some(fill) = style.fill_color {
css.push_str(&format!("background:{};", color_to_css(fill)));
}
self.output.push_str(&format!(
"<div class=\"hwp-ellipse\" style=\"{}\"></div>\n",
css,
));
}
fn draw_image(&mut self, data: &[u8], x: f64, y: f64, w: f64, h: f64) {
let mime_type = detect_image_mime_type(data);
let (render_data, render_mime): (std::borrow::Cow<[u8]>, &str) =
if mime_type == "image/x-wmf" {
match convert_wmf_to_svg(data) {
Some(svg_bytes) => (std::borrow::Cow::Owned(svg_bytes), "image/svg+xml"),
None => (std::borrow::Cow::Borrowed(data), mime_type),
}
} else if mime_type == "image/x-emf" {
match crate::emf::convert_to_standalone_svg(data) {
Some(svg_bytes) => (std::borrow::Cow::Owned(svg_bytes), "image/svg+xml"),
None => (std::borrow::Cow::Borrowed(data), mime_type),
}
} else if mime_type == "image/bmp" {
match bmp_bytes_to_png_bytes(data) {
Some(png_bytes) => (std::borrow::Cow::Owned(png_bytes), "image/png"),
None => (std::borrow::Cow::Borrowed(data), mime_type),
}
} else if mime_type == "image/x-pcx" {
match pcx_bytes_to_png_bytes(data) {
Some(png_bytes) => (std::borrow::Cow::Owned(png_bytes), "image/png"),
None => (std::borrow::Cow::Borrowed(data), mime_type),
}
} else if mime_type == "image/tiff" {
match tiff_bytes_to_png_bytes(data) {
Some(png_bytes) => (std::borrow::Cow::Owned(png_bytes), "image/png"),
None => (std::borrow::Cow::Borrowed(data), mime_type),
}
} else if mime_type == "application/postscript" {
match crate::renderer::image_resolver::eps_renderable_bytes(data) {
Some((mime, bytes)) => (std::borrow::Cow::Owned(bytes), mime),
None => (std::borrow::Cow::Borrowed(data), mime_type),
}
} else {
(std::borrow::Cow::Borrowed(data), mime_type)
};
let base64_data = base64::engine::general_purpose::STANDARD.encode(&*render_data);
let data_uri = format!("data:{};base64,{}", render_mime, base64_data);
self.output.push_str(&format!(
"<img class=\"hwp-image\" src=\"{}\" style=\"position:absolute;left:{}px;top:{}px;width:{}px;height:{}px;\" />\n",
data_uri, x, y, w, h,
));
}
fn draw_path(&mut self, commands: &[PathCommand], style: &ShapeStyle) {
let mut d = String::new();
for cmd in commands {
match cmd {
PathCommand::MoveTo(x, y) => d.push_str(&format!("M{} {} ", x, y)),
PathCommand::LineTo(x, y) => d.push_str(&format!("L{} {} ", x, y)),
PathCommand::CurveTo(x1, y1, x2, y2, x, y) => {
d.push_str(&format!("C{} {} {} {} {} {} ", x1, y1, x2, y2, x, y));
}
PathCommand::ArcTo(rx, ry, x_rot, large_arc, sweep, x, y) => {
d.push_str(&format!(
"A{} {} {} {} {} {} {} ",
rx,
ry,
x_rot,
if *large_arc { 1 } else { 0 },
if *sweep { 1 } else { 0 },
x,
y
));
}
PathCommand::ClosePath => d.push_str("Z "),
}
}
let fill = style
.fill_color
.map(|c| color_to_css(c))
.unwrap_or_else(|| "none".to_string());
self.output.push_str(&format!(
"<svg class=\"hwp-path\" style=\"position:absolute;\"><path d=\"{}\" fill=\"{}\"/></svg>\n",
d.trim(), fill,
));
}
}
fn color_to_css(color: u32) -> String {
let b = (color >> 16) & 0xFF;
let g = (color >> 8) & 0xFF;
let r = color & 0xFF;
format!("#{:02x}{:02x}{:02x}", r, g, b)
}
fn escape_html(s: &str) -> String {
let mut result = String::with_capacity(s.len());
for c in s.chars() {
match c {
'&' => result.push_str("&"),
'<' => result.push_str("<"),
'>' => result.push_str(">"),
'"' => result.push_str("""),
'\u{09}' | '\u{0A}' | '\u{0D}' => result.push(c),
c if c < '\u{0020}' => {} _ => result.push(c),
}
}
result
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_html_begin_end_page() {
let mut renderer = HtmlRenderer::new();
renderer.begin_page(800.0, 600.0);
renderer.end_page();
let output = renderer.output();
assert!(output.contains("hwp-page"));
assert!(output.contains("width:800px"));
assert!(output.ends_with("</div>\n"));
}
#[test]
fn test_html_draw_text() {
let mut renderer = HtmlRenderer::new();
renderer.begin_page(800.0, 600.0);
renderer.draw_text(
"테스트",
10.0,
20.0,
&TextStyle {
font_size: 14.0,
bold: true,
italic: true,
..Default::default()
},
);
let output = renderer.output();
assert!(output.contains("font-weight:bold"));
assert!(output.contains("font-style:italic"));
}
#[test]
fn test_html_draw_text_medium_weight() {
let mut renderer = HtmlRenderer::new();
renderer.begin_page(800.0, 600.0);
renderer.draw_text(
"중고딕",
10.0,
20.0,
&TextStyle {
font_size: 14.0,
font_family: "HY중고딕".to_string(),
bold: false,
..Default::default()
},
);
let output = renderer.output();
assert!(
output.contains("font-weight:500"),
"중고딕 계열은 font-weight:500이어야 함"
);
assert!(!output.contains("font-weight:bold"));
}
#[test]
fn test_html_draw_rect() {
let mut renderer = HtmlRenderer::new();
renderer.begin_page(800.0, 600.0);
renderer.draw_rect(
0.0,
0.0,
100.0,
50.0,
0.0,
&ShapeStyle {
fill_color: Some(0x00FF0000),
..Default::default()
},
);
let output = renderer.output();
assert!(output.contains("hwp-rect"));
assert!(output.contains("background:#0000ff")); }
#[test]
fn test_html_escape() {
assert_eq!(
escape_html("<script>alert('xss')</script>"),
"<script>alert('xss')</script>"
);
}
#[test]
fn test_html_render_tree() {
use super::super::render_tree::*;
let tree = PageRenderTree::new(0, 800.0, 600.0);
let mut renderer = HtmlRenderer::new();
renderer.render_tree(&tree);
let output = renderer.output();
assert!(output.contains("hwp-page"));
}
#[test]
fn test_draw_image_png() {
let mut renderer = HtmlRenderer::new();
renderer.begin_page(800.0, 600.0);
let png_data = [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0x00];
renderer.draw_image(&png_data, 10.0, 20.0, 100.0, 50.0);
let output = renderer.output();
assert!(output.contains("<img"));
assert!(output.contains("data:image/png;base64,"));
assert!(output.contains("hwp-image"));
}
#[test]
fn test_draw_image_jpeg() {
let mut renderer = HtmlRenderer::new();
renderer.begin_page(800.0, 600.0);
let jpeg_data = [0xFF, 0xD8, 0xFF, 0xE0, 0x00, 0x10, 0x4A, 0x46];
renderer.draw_image(&jpeg_data, 0.0, 0.0, 200.0, 150.0);
let output = renderer.output();
assert!(output.contains("data:image/jpeg;base64,"));
}
#[test]
fn test_draw_image_unknown_format() {
let mut renderer = HtmlRenderer::new();
renderer.begin_page(800.0, 600.0);
let unknown_data = [0x00, 0x01, 0x02, 0x03];
renderer.draw_image(&unknown_data, 5.0, 5.0, 50.0, 50.0);
let output = renderer.output();
assert!(output.contains("data:application/octet-stream;base64,"));
}
}