liepress 0.1.4

A Markdown to PDF/SVG/PNG converter with CSS styling support
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
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
//! PDF 渲染器 - 使用 krilla

use std::collections::HashMap;

use krilla::action::{Action, LinkAction};
use krilla::annotation::{Annotation, LinkAnnotation, Target};
use krilla::color::Color as KrillaColor;
use krilla::color::rgb::Color as RgbColor;
use krilla::destination::XyzDestination;
use krilla::document::Document;
use krilla::geom::{
    PathBuilder, Point as KrillaPoint, Rect as KrillaRect, Size, Transform as KrillaTransform,
};
use krilla::num::NormalizedF32;
use krilla::outline::{Outline, OutlineNode};
use krilla::page::PageSettings;
use krilla::paint::{
    Fill, FillRule, LineCap, LineJoin, LinearGradient, Paint, SpreadMethod, Stop,
    Stroke as KrillaStroke,
};
use krilla::surface::Surface;
use krilla::text::Font;
use vello_cpu::kurbo::{BezPath, PathEl, Point, Rect, Shape};

use crate::error::Result;
use crate::generator::Page;
use crate::generator::context::OutlineEntry;
use crate::render::PageRenderer;
use crate::visual::{Color, FillStrokeStyle, GradientDef, Stroke, StrokeStyle, Transform};

#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
struct FontCacheKey {
    data_ptr: *const u8,
    data_len: usize,
    index: u32,
}

impl FontCacheKey {
    fn from_font_data(font_data: &parley::FontData) -> Self {
        let data = font_data.data.as_ref();
        Self {
            data_ptr: data.as_ptr(),
            data_len: data.len(),
            index: font_data.index,
        }
    }
}

pub struct PdfDocumentGenerator {
    pages: Vec<Page>,
    outline: Vec<OutlineEntry>,
}

impl PdfDocumentGenerator {
    /// 从应用层的 Document 构造 PDF 生成器,不执行实际渲染。
    pub fn new(doc: &crate::generator::types::Document) -> Self {
        Self {
            pages: doc.pages.clone(),
            outline: doc.outline.clone(),
        }
    }

    /// 生成 PDF 字节数据。
    ///
    /// 内部创建 krilla Document,渲染所有页面、添加超链接、设置大纲(书签)。
    pub fn generate(&self) -> Result<Vec<u8>> {
        let mut krilla_doc = Document::new();
        for page in &self.pages {
            let size = Size::from_wh(page.width, page.height).ok_or_else(|| {
                crate::error::Error::VisualElementError("invalid page size".into())
            })?;
            let mut krilla_page = krilla_doc.start_page_with(PageSettings::new(size));
            let mut surface = krilla_page.surface();

            // 绘制白色背景
            Self::draw_white_background(&mut surface, page.width, page.height);

            let links = {
                let mut renderer = PdfRenderer::new(&mut surface);
                renderer.render_elements(&page.elements);
                renderer.take_links()
            };

            surface.finish();

            // 添加超链接注释
            for (x, y, w, h, url) in links {
                if let Some(rect) = KrillaRect::from_xywh(x, y, w, h) {
                    let action = Action::from(LinkAction::new(url.clone()));
                    let link_annotation = LinkAnnotation::new(rect, Target::Action(action));
                    krilla_page.add_annotation(Annotation::new_link(link_annotation, None));
                }
            }

            krilla_page.finish();
        }

        if !self.outline.is_empty() {
            let outline = build_krilla_outline(&self.outline);
            krilla_doc.set_outline(outline);
        }

        krilla_doc
            .finish()
            .map_err(|e| crate::error::Error::VisualElementError(format!("{:?}", e)))
    }

    fn draw_white_background(surface: &mut Surface, width: f32, height: f32) {
        let mut pb = PathBuilder::new();
        pb.move_to(0.0, 0.0);
        pb.line_to(width, 0.0);
        pb.line_to(width, height);
        pb.line_to(0.0, height);
        pb.close();
        if let Some(path) = pb.finish() {
            let fill = Fill {
                paint: Paint::from(RgbColor::new(255, 255, 255)),
                opacity: NormalizedF32::ONE,
                rule: FillRule::NonZero,
            };
            surface.set_fill(Some(fill));
            surface.draw_path(&path);
        }
    }
}

/// 将树形结构的 OutlineEntry 列表构建为 krilla 的层级 Outline。
///
/// entries 是根级别的条目列表,每个条目可能含有 children(子标题)。
/// XyzDestination 内部会自动将坐标从"顶部原点"转换为 PDF 的"底部原点",所以
/// 直接传入 y_position(从页面顶部算起)即可。
fn build_krilla_outline(entries: &[OutlineEntry]) -> Outline {
    let mut outline = Outline::new();
    for entry in entries {
        let node = entry_to_outline_node(entry);
        outline.push_child(node);
    }
    outline
}

/// 递归地将一个 OutlineEntry 及其子节点转换为 krilla OutlineNode
fn entry_to_outline_node(entry: &OutlineEntry) -> OutlineNode {
    let dest = XyzDestination::new(
        entry.page_number - 1,
        KrillaPoint::from_xy(entry.x_position, entry.y_position),
    );
    let mut node = OutlineNode::new(entry.title.clone(), dest);

    for child in &entry.children {
        let child_node = entry_to_outline_node(child);
        node.push_child(child_node);
    }

    node
}

pub struct PdfRenderer<'a, 's> {
    surface: &'s mut Surface<'a>,
    font_cache: HashMap<FontCacheKey, Font>,
    push_count: usize,
    links: Vec<(f32, f32, f32, f32, String)>,
}

impl<'a, 's> PdfRenderer<'a, 's> {
    fn new(surface: &'s mut Surface<'a>) -> Self {
        Self {
            surface,
            font_cache: HashMap::new(),
            push_count: 0,
            links: Vec::new(),
        }
    }

    fn take_links(&mut self) -> Vec<(f32, f32, f32, f32, String)> {
        std::mem::take(&mut self.links)
    }

    fn color_to_krilla(color: &Color) -> RgbColor {
        RgbColor::new(color.r, color.g, color.b)
    }

    fn opacity_from_alpha(alpha: u8) -> NormalizedF32 {
        NormalizedF32::new(alpha as f32 / 255.0).unwrap_or(NormalizedF32::ONE)
    }

    fn set_fill_color(&mut self, color: &Color) {
        let krilla_color = Self::color_to_krilla(color);
        let fill = Fill {
            paint: Paint::from(krilla_color),
            opacity: Self::opacity_from_alpha(color.a),
            rule: FillRule::NonZero,
        };
        self.surface.set_fill(Some(fill));
    }

    fn set_stroke_color(&mut self, color: &Color, width: f64) {
        let krilla_color = Self::color_to_krilla(color);
        let stroke = KrillaStroke {
            paint: Paint::from(krilla_color),
            opacity: Self::opacity_from_alpha(color.a),
            width: width as f32,
            miter_limit: 4.0,
            line_cap: LineCap::default(),
            line_join: LineJoin::default(),
            dash: None,
        };
        self.surface.set_stroke(Some(stroke));
    }

    fn clear_stroke(&mut self) {
        self.surface.set_stroke(None);
    }

    fn clear_fill(&mut self) {
        self.surface.set_fill(None);
    }

    fn apply_fill_stroke(&mut self, style: &FillStrokeStyle) {
        if let Some(fill) = &style.fill {
            self.set_fill_color(fill);
        } else {
            self.clear_fill();
        }

        if let Some(stroke) = &style.stroke {
            self.set_stroke_color(&stroke.color, stroke.width);
        } else {
            self.clear_stroke();
        }
    }

    fn bezpath_to_krilla_path(path: &BezPath) -> Option<krilla::geom::Path> {
        let mut pb = PathBuilder::new();
        for el in path.elements() {
            match el {
                PathEl::MoveTo(p) => {
                    pb.move_to(p.x as f32, p.y as f32);
                }
                PathEl::LineTo(p) => {
                    pb.line_to(p.x as f32, p.y as f32);
                }
                PathEl::QuadTo(p1, p2) => {
                    pb.quad_to(p1.x as f32, p1.y as f32, p2.x as f32, p2.y as f32);
                }
                PathEl::CurveTo(p1, p2, p3) => {
                    pb.cubic_to(
                        p1.x as f32,
                        p1.y as f32,
                        p2.x as f32,
                        p2.y as f32,
                        p3.x as f32,
                        p3.y as f32,
                    );
                }
                PathEl::ClosePath => {
                    pb.close();
                }
            }
        }
        pb.finish()
    }
}

impl PageRenderer for PdfRenderer<'_, '_> {
    fn draw_rect(&mut self, rect: Rect, style: &FillStrokeStyle) {
        let mut pb = PathBuilder::new();
        pb.move_to(rect.x0 as f32, rect.y0 as f32);
        pb.line_to(rect.x1 as f32, rect.y0 as f32);
        pb.line_to(rect.x1 as f32, rect.y1 as f32);
        pb.line_to(rect.x0 as f32, rect.y1 as f32);
        pb.close();
        if let Some(path) = pb.finish() {
            self.apply_fill_stroke(style);
            self.surface.draw_path(&path);
        }
    }

    fn draw_rounded_rect(
        &mut self,
        rect: Rect,
        radii: (f64, f64, f64, f64),
        style: &FillStrokeStyle,
    ) {
        let (tl, tr, br, bl) = radii;
        let x0 = rect.x0 as f32;
        let y0 = rect.y0 as f32;
        let x1 = rect.x1 as f32;
        let y1 = rect.y1 as f32;
        let k = 0.552_284_8;

        let mut pb = PathBuilder::new();
        // 从左上角开始(圆弧之后)
        pb.move_to(x0 + tl as f32, y0);
        // 上边 → 右上角
        pb.line_to(x1 - tr as f32, y0);
        if tr > 0.0 {
            let r = tr as f32;
            let kr = r * k;
            pb.cubic_to(
                x1 - tr as f32 + kr,
                y0,
                x1,
                y0 + tr as f32 - kr,
                x1,
                y0 + tr as f32,
            );
        }
        // 右边 → 右下角
        pb.line_to(x1, y1 - br as f32);
        if br > 0.0 {
            let r = br as f32;
            let kr = r * k;
            pb.cubic_to(
                x1,
                y1 - br as f32 + kr,
                x1 - br as f32 + kr,
                y1,
                x1 - br as f32,
                y1,
            );
        }
        // 下边 → 左下角
        pb.line_to(x0 + bl as f32, y1);
        if bl > 0.0 {
            let r = bl as f32;
            let kr = r * k;
            pb.cubic_to(
                x0 + bl as f32 - kr,
                y1,
                x0,
                y1 - bl as f32 + kr,
                x0,
                y1 - bl as f32,
            );
        }
        // 左边 → 左上角
        pb.line_to(x0, y0 + tl as f32);
        if tl > 0.0 {
            let r = tl as f32;
            let kr = r * k;
            pb.cubic_to(
                x0,
                y0 + tl as f32 - kr,
                x0 + tl as f32 - kr,
                y0,
                x0 + tl as f32,
                y0,
            );
        }
        pb.close();

        if let Some(path) = pb.finish() {
            self.apply_fill_stroke(style);
            self.surface.draw_path(&path);
        }
    }

    fn draw_circle(&mut self, center: Point, radius: f64, style: &FillStrokeStyle) {
        let k = 0.552_284_8;
        let r = radius as f32;
        let cx = center.x as f32;
        let cy = center.y as f32;
        let kr = r * k;

        let mut pb = PathBuilder::new();
        pb.move_to(cx, cy - r);
        pb.cubic_to(cx + kr, cy - r, cx + r, cy - kr, cx + r, cy);
        pb.cubic_to(cx + r, cy + kr, cx + kr, cy + r, cx, cy + r);
        pb.cubic_to(cx - kr, cy + r, cx - r, cy + kr, cx - r, cy);
        pb.cubic_to(cx - r, cy - kr, cx - kr, cy - r, cx, cy - r);
        pb.close();

        if let Some(path) = pb.finish() {
            self.apply_fill_stroke(style);
            self.surface.draw_path(&path);
        }
    }

    fn draw_line(&mut self, start: Point, end: Point, style: &StrokeStyle) {
        let mut pb = PathBuilder::new();
        pb.move_to(start.x as f32, start.y as f32);
        pb.line_to(end.x as f32, end.y as f32);

        if let Some(path) = pb.finish() {
            self.clear_fill();
            self.set_stroke_color(&style.color, style.width);
            self.surface.draw_path(&path);
        }
    }

    fn draw_polyline(&mut self, points: &[Point], style: &StrokeStyle) {
        if points.len() < 2 {
            return;
        }

        let mut pb = PathBuilder::new();
        pb.move_to(points[0].x as f32, points[0].y as f32);
        for p in &points[1..] {
            pb.line_to(p.x as f32, p.y as f32);
        }

        if let Some(path) = pb.finish() {
            self.clear_fill();
            self.set_stroke_color(&style.color, style.width);
            self.surface.draw_path(&path);
        }
    }

    fn draw_path(&mut self, path: &BezPath, style: &FillStrokeStyle) {
        if let Some(krilla_path) = Self::bezpath_to_krilla_path(path) {
            self.apply_fill_stroke(style);
            self.surface.draw_path(&krilla_path);
        }
    }

    fn draw_gradient_path(
        &mut self,
        path: &BezPath,
        gradient: &GradientDef,
        stroke: Option<&Stroke>,
    ) {
        let Some(krilla_path) = Self::bezpath_to_krilla_path(path) else {
            return;
        };

        let bounds = path.bounding_box();

        let stops: Vec<Stop> = gradient
            .stops
            .iter()
            .map(|(offset, color)| Stop {
                offset: NormalizedF32::new(*offset as f32).unwrap_or(NormalizedF32::ONE),
                color: KrillaColor::from(RgbColor::new(color.r, color.g, color.b)),
                opacity: NormalizedF32::new(color.a as f32 / 255.0).unwrap_or(NormalizedF32::ONE),
            })
            .collect();

        let linear_gradient = LinearGradient {
            x1: bounds.x0 as f32,
            y1: bounds.y0 as f32,
            x2: bounds.x1 as f32,
            y2: bounds.y0 as f32,
            transform: KrillaTransform::default(),
            spread_method: SpreadMethod::Pad,
            stops,
            anti_alias: false,
        };

        self.clear_stroke();
        let fill = Fill {
            paint: Paint::from(linear_gradient),
            opacity: NormalizedF32::ONE,
            rule: FillRule::NonZero,
        };
        self.surface.set_fill(Some(fill));
        self.surface.draw_path(&krilla_path);

        if let Some(stroke) = stroke {
            self.clear_fill();
            self.set_stroke_color(&stroke.color, stroke.width);
            self.surface.draw_path(&krilla_path);
        }
    }

    fn begin_group(&mut self, transform: Option<&Transform>) {
        if let Some(t) = transform {
            if t.translate.x != 0.0 || t.translate.y != 0.0 {
                self.surface
                    .push_transform(&KrillaTransform::from_translate(
                        t.translate.x as f32,
                        t.translate.y as f32,
                    ));
                self.push_count += 1;
            }
            if t.rotate != 0.0 {
                self.surface
                    .push_transform(&KrillaTransform::from_rotate(t.rotate.to_degrees() as f32));
                self.push_count += 1;
            }
            if t.scale.x != 1.0 || t.scale.y != 1.0 {
                self.surface.push_transform(&KrillaTransform::from_scale(
                    t.scale.x as f32,
                    t.scale.y as f32,
                ));
                self.push_count += 1;
            }
        }
    }

    fn end_group(&mut self) {
        for _ in 0..self.push_count {
            self.surface.pop();
        }
        self.push_count = 0;
    }

    fn draw_text_run(&mut self, run: &crate::text::TextRun, position: Point) {
        use krilla::text::GlyphId;

        // position: 文本行左上角在页面上的位置(行顶)
        // run.baseline_x/y: 基线相对行顶的偏移
        //
        // 注意:krilla 的 draw_glyphs 把 origin 当作基线位置,
        // 而 position 是行顶。所以直接用 baseline 值计算基线原点:
        //   - origin = position + (baseline_x, baseline_y)
        //   - glyph 坐标减去 baseline 偏移,变成相对基线的归一化偏移

        if run.glyphs.is_empty() {
            return;
        }

        // 行内背景色(行内代码/高亮):在字形之前先绘制背景矩形
        if let Some(bg) = run.background_color {
            // 背景矩形:以行基线为参照,左右各加一点水平内边距,高度略高于字形
            let pad = run.font_size * 0.1;
            let x = position.x as f32 + run.baseline_x - pad;
            let y = position.y as f32;
            let w = run.advance + pad * 2.0;
            let h = run.font_size * 1.25;
            let rect = Rect::new(x as f64, y as f64, (x + w) as f64, (y + h) as f64);
            let style = FillStrokeStyle {
                fill: Some(bg),
                stroke: None,
            };
            self.draw_rect(rect, &style);
        }

        let font_key = FontCacheKey::from_font_data(&run.font_data);

        if let std::collections::hash_map::Entry::Vacant(e) = self.font_cache.entry(font_key) {
            let data = run.font_data.data.as_ref();
            if let Some(font) = Font::new(krilla::Data::from(data.to_vec()), run.font_data.index) {
                e.insert(font);
            } else {
                return;
            }
        }

        let krilla_font = match self.font_cache.get(&font_key) {
            Some(f) => f.clone(),
            None => return,
        };

        // 基线位置 = 行顶 + baseline 偏移
        let krilla_origin = KrillaPoint::from_xy(
            position.x as f32 + run.baseline_x,
            position.y as f32 + run.baseline_y,
        );

        // 如果 run 有 URL,收集链接区域
        if let Some(ref url) = run.url {
            let link_x = position.x as f32 + run.baseline_x;
            let link_y = position.y as f32;
            let link_w = run.advance;
            let link_h = run.font_size * 1.4;
            self.links
                .push((link_x, link_y, link_w, link_h, url.clone()));
        }

        let mut krilla_glyphs = Vec::new();
        for g in &run.glyphs {
            if g.id == 0 {
                continue;
            }
            // glyph 坐标转为相对基线的归一化偏移
            krilla_glyphs.push(krilla::text::KrillaGlyph::new(
                GlyphId::new(g.id),
                0.0,
                (g.x - run.baseline_x) / run.font_size,
                (g.y - run.baseline_y) / run.font_size,
                0.0,
                0..0,
                None,
            ));
        }

        if krilla_glyphs.is_empty() {
            return;
        }

        // 确保没有残留的 stroke 状态(否则 krilla 会生成 2 Tr fill+stroke 模式 + 灰色描边)
        self.surface.set_stroke(None);

        let krilla_color = RgbColor::new(run.color.r, run.color.g, run.color.b);
        let paint = Paint::from(krilla_color);
        let opacity = NormalizedF32::new(run.color.a as f32 / 255.0).unwrap_or(NormalizedF32::ONE);
        let fill = Fill {
            paint,
            opacity,
            rule: FillRule::NonZero,
        };

        self.surface.set_fill(Some(fill.clone()));
        self.surface.draw_glyphs(
            krilla_origin,
            &krilla_glyphs,
            krilla_font,
            &run.text,
            run.font_size,
            false,
        );

        // 绘制删除线
        if run.decoration == crate::text::TextDecoration::LineThrough {
            // 删除线位置:基线以上 0.3em
            let strike_y = position.y as f32 + run.baseline_y - run.font_size * 0.3;
            let line_x1 = position.x as f32 + run.baseline_x;
            let line_x2 = line_x1 + run.advance;
            let stroke_w = (run.font_size * 0.06).max(0.5);

            // 保存当前 fill,清除,设置 stroke
            self.surface.set_fill(None);
            let krilla_color = RgbColor::new(run.color.r, run.color.g, run.color.b);
            let stroke = KrillaStroke {
                paint: Paint::from(krilla_color),
                opacity: NormalizedF32::new(run.color.a as f32 / 255.0)
                    .unwrap_or(NormalizedF32::ONE),
                width: stroke_w,
                miter_limit: 4.0,
                line_cap: LineCap::default(),
                line_join: LineJoin::default(),
                dash: None,
            };
            self.surface.set_stroke(Some(stroke));

            let mut pb = PathBuilder::new();
            pb.move_to(line_x1, strike_y);
            pb.line_to(line_x2, strike_y);
            if let Some(path) = pb.finish() {
                self.surface.draw_path(&path);
            }

            // 恢复 stroke 状态
            self.surface.set_stroke(None);
            self.surface.set_fill(Some(fill.clone()));
        }
    }

    fn draw_image(&mut self, data: &[u8], format: &str, position: Point, size: (f64, f64)) {
        use krilla::image::Image;

        let image = match format.to_lowercase().as_str() {
            "png" => Image::from_png(krilla::Data::from(data.to_vec()), true),
            "jpeg" | "jpg" => Image::from_jpeg(krilla::Data::from(data.to_vec()), true),
            "gif" => Image::from_gif(krilla::Data::from(data.to_vec()), true),
            "webp" => Image::from_webp(krilla::Data::from(data.to_vec()), true),
            _ => return,
        };

        let image = match image {
            Ok(img) => img,
            Err(_) => return,
        };

        self.surface
            .push_transform(&KrillaTransform::from_translate(
                position.x as f32,
                position.y as f32,
            ));

        let Some(image_size) = Size::from_wh(size.0 as f32, size.1 as f32) else {
            self.surface.pop();
            return;
        };
        self.surface.draw_image(image, image_size);
        self.surface.pop();
    }
}