dfe 0.5.6

DFE - Documentos Fiscais Eletrônicos Brasileiros
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
use barcoders::sym::code128::Code128;
use printpdf::*;

const PAGE_WIDTH_MM: f32 = 80.0;
const MARGIN_MM: f32 = 3.0;
const USABLE_WIDTH: f32 = PAGE_WIDTH_MM - MARGIN_MM * 2.0;

const FONT_SIZE_TITLE: f32 = 8.0;
const FONT_SIZE_HEADER: f32 = 7.0;
const FONT_SIZE_NORMAL: f32 = 6.5;
const FONT_SIZE_SMALL: f32 = 6.0;
const FONT_SIZE_CREDITS: f32 = 5.0;
const FONT_SIZE_VALUE: f32 = 9.0;

const LINE_HEIGHT: f32 = 3.0;
const SECTION_GAP: f32 = 3.0;
const EMIT_NAME_LINE_CHARS: usize = 34;
const DEST_NAME_LINE_CHARS: usize = 34;

pub struct PdfItem {
    pub n_item: String,
    pub x_prod: String,
    pub q_com: String,
    pub u_com: String,
    pub v_un_com: String,
    pub v_prod: String,
}

pub fn build_pdf_80mm(
    chave_acesso: &str,
    n_prot: &str,
    dh_recbto: &str,
    emit_x_nome: &str,
    emit_uf: &str,
    emit_cnpj: &str,
    emit_ie: &str,
    tp_nf: &str,
    serie: &str,
    n_nf: &str,
    dh_emi: &str,
    dest_x_nome: &str,
    dest_cnpj_cpf: &str,
    dest_uf: &str,
    dest_ie: &str,
    v_nf: &str,
    t_pag: &str,
    inf_cpl: &str,
    items: &[PdfItem],
) -> Result<Vec<u8>, String> {
    let emit_name_fallback = "EMITENTE NAO INFORMADO";
    let emit_name = if emit_x_nome.trim().is_empty() {
        emit_name_fallback
    } else {
        emit_x_nome
    };
    let mut emit_name_lines = wrap_text(emit_name, EMIT_NAME_LINE_CHARS);
    if emit_name_lines.is_empty() {
        emit_name_lines.push(emit_name_fallback.to_string());
    }

    let dest_name_fallback = "DESTINATARIO NAO INFORMADO";
    let dest_name = if dest_x_nome.trim().is_empty() {
        dest_name_fallback
    } else {
        dest_x_nome
    };
    let mut dest_name_lines = wrap_text(dest_name, DEST_NAME_LINE_CHARS);
    if dest_name_lines.is_empty() {
        dest_name_lines.push(dest_name_fallback.to_string());
    }

    // Altura dinamica: base + itens + barcode + observacao
    let barcode_height_mm = 10.0;
    let extra_emit_lines = emit_name_lines.len().saturating_sub(1) as f32;
    let extra_dest_lines = dest_name_lines.len().saturating_sub(1) as f32;
    let base_height =
        105.0 + barcode_height_mm + (extra_emit_lines + extra_dest_lines) * LINE_HEIGHT;
    let items_height = items.len() as f32 * (LINE_HEIGHT * 2.0 + 1.0);
    let obs_lines = if inf_cpl.is_empty() {
        2
    } else {
        wrap_text(inf_cpl, 55).len() + 1
    };
    let obs_height = obs_lines as f32 * LINE_HEIGHT + SECTION_GAP;
    let page_height_mm = (base_height + items_height + obs_height + MARGIN_MM * 2.0).max(135.0);

    let (doc, page1, layer1) = PdfDocument::new(
        "DANFE Simplificado",
        Mm(PAGE_WIDTH_MM),
        Mm(page_height_mm),
        "Layer 1",
    );

    let font = doc
        .add_builtin_font(BuiltinFont::Helvetica)
        .map_err(|e| format!("Erro ao carregar fonte: {}", e))?;
    let font_bold = doc
        .add_builtin_font(BuiltinFont::HelveticaBold)
        .map_err(|e| format!("Erro ao carregar fonte bold: {}", e))?;

    let layer = doc.get_page(page1).get_layer(layer1);
    let mut y = page_height_mm - MARGIN_MM;

    // ── TITULO ──────────────────────────────
    write_center(&layer, &font_bold, FONT_SIZE_TITLE, y, "DANFE SIMPLIFICADO");
    y -= 1.5;
    draw_line(&layer, y, 0.6);
    y -= SECTION_GAP;

    // ── EMITENTE ────────────────────────────
    write_center(&layer, &font_bold, FONT_SIZE_HEADER, y, "EMITENTE");
    y -= LINE_HEIGHT;
    for line in &emit_name_lines {
        write_center(&layer, &font, FONT_SIZE_NORMAL, y, line);
        y -= LINE_HEIGHT;
    }
    write_center(
        &layer,
        &font,
        FONT_SIZE_SMALL,
        y,
        &format!(
            "CNPJ: {}  IE: {}  UF: {}",
            format_cnpj_cpf(emit_cnpj),
            emit_ie,
            emit_uf
        ),
    );
    y -= 1.5;
    draw_line(&layer, y, 0.3);
    y -= SECTION_GAP;

    // ── DADOS DA NF-e ───────────────────────
    write_center(&layer, &font_bold, FONT_SIZE_HEADER, y, "DADOS DA NF-e");
    y -= LINE_HEIGHT;
    let tipo_op = match tp_nf {
        "0" => "ENTRADA",
        "1" => "SAIDA",
        _ => tp_nf,
    };
    write_center(
        &layer,
        &font,
        FONT_SIZE_NORMAL,
        y,
        &format!("Tipo: {}  Serie: {}  No: {}", tipo_op, serie, n_nf),
    );
    y -= LINE_HEIGHT;
    write_center(
        &layer,
        &font,
        FONT_SIZE_NORMAL,
        y,
        &format!("Emissao: {}", format_datetime(dh_emi)),
    );
    y -= 1.5;
    draw_line(&layer, y, 0.3);
    y -= SECTION_GAP;

    // ── DESTINATARIO ────────────────────────
    write_center(&layer, &font_bold, FONT_SIZE_HEADER, y, "DESTINATARIO");
    y -= LINE_HEIGHT;
    for line in &dest_name_lines {
        write_center(&layer, &font, FONT_SIZE_NORMAL, y, line);
        y -= LINE_HEIGHT;
    }
    let mut dest_info = format!(
        "CNPJ/CPF: {}  UF: {}",
        format_cnpj_cpf(dest_cnpj_cpf),
        dest_uf
    );
    if !dest_ie.is_empty() {
        dest_info.push_str(&format!("  IE: {}", dest_ie));
    }
    write_center(&layer, &font, FONT_SIZE_SMALL, y, &dest_info);
    y -= 1.5;
    draw_line(&layer, y, 0.3);
    y -= SECTION_GAP;

    // ── PRODUTOS / SERVICOS ─────────────────
    write_center(&layer, &font_bold, FONT_SIZE_HEADER, y, "PRODUTOS");
    y -= LINE_HEIGHT + 0.5;
    write_left(
        &layer,
        &font_bold,
        FONT_SIZE_SMALL,
        y,
        "#  Descricao | Qtd x Un x Vl Unit",
    );
    write_right(&layer, &font_bold, FONT_SIZE_SMALL, y, "Valor");
    y -= LINE_HEIGHT;
    draw_line(&layer, y + 1.0, 0.15);
    y -= 1.5;

    for item in items {
        let desc = truncate_str(&item.x_prod, 42);
        write_left(
            &layer,
            &font,
            FONT_SIZE_SMALL,
            y,
            &format!("{}  {}", item.n_item, desc),
        );
        y -= LINE_HEIGHT;
        write_left(
            &layer,
            &font,
            FONT_SIZE_SMALL,
            y,
            &format!(
                "    {} {} x R$ {}",
                format_decimal_br(&item.q_com),
                item.u_com,
                format_brl(&item.v_un_com)
            ),
        );
        write_right(
            &layer,
            &font,
            FONT_SIZE_SMALL,
            y,
            &format!("R$ {}", format_brl(&item.v_prod)),
        );
        y -= LINE_HEIGHT + 0.5;
    }

    draw_line(&layer, y + 0.5, 0.3);
    y -= SECTION_GAP;

    // ── FORMA DE PAGAMENTO ──────────────────
    let desc_pag = match t_pag {
        "01" => "Dinheiro",
        "02" => "Cheque",
        "03" => "Cartao de Credito",
        "04" => "Cartao de Debito",
        "05" => "Credito Loja",
        "10" => "Vale Alimentacao",
        "11" => "Vale Refeicao",
        "12" => "Vale Presente",
        "13" => "Vale Combustivel",
        "14" => "Duplicata Mercantil",
        "15" => "Boleto Bancario",
        "16" => "Deposito Bancario",
        "17" => "PIX",
        "18" => "Transferencia bancaria",
        "19" => "Programa fidelidade",
        "90" => "Sem Pagamento",
        "99" => "Outros",
        _ => t_pag,
    };
    write_left(
        &layer,
        &font_bold,
        FONT_SIZE_HEADER,
        y,
        "Forma de Pagamento",
    );
    write_right(&layer, &font, FONT_SIZE_NORMAL, y, desc_pag);
    y -= 1.5;
    y -= SECTION_GAP;

    // ── VALOR TOTAL ─────────────────────────
    write_left(
        &layer,
        &font_bold,
        FONT_SIZE_HEADER,
        y,
        "VALOR TOTAL DA NF-e",
    );
    write_right(
        &layer,
        &font_bold,
        FONT_SIZE_VALUE,
        y,
        &format!("R$ {}", format_brl(v_nf)),
    );
    y -= LINE_HEIGHT;
    draw_line(&layer, y, 0.3);
    y -= SECTION_GAP;

    // ── CHAVE DE ACESSO ─────────────────────
    write_center(&layer, &font_bold, FONT_SIZE_HEADER, y, "CHAVE DE ACESSO");
    y -= 1.5;

    // Codigo de barras Code128
    y = draw_barcode_128(&layer, chave_acesso, y, barcode_height_mm)?;
    y -= 3.0;

    let chave_fmt = format_chave_acesso(chave_acesso);
    write_center(&layer, &font, FONT_SIZE_NORMAL, y, &chave_fmt);
    y -= 1.5;
    draw_line(&layer, y, 0.3);
    y -= SECTION_GAP;

    // ── PROTOCOLO DE AUTORIZACAO ────────────
    write_center(
        &layer,
        &font_bold,
        FONT_SIZE_HEADER,
        y,
        "PROTOCOLO DE AUTORIZACAO",
    );
    y -= LINE_HEIGHT;
    write_center(
        &layer,
        &font,
        FONT_SIZE_NORMAL,
        y,
        &format!("{} - {}", n_prot, format_datetime(dh_recbto)),
    );
    y -= 1.5;
    draw_line(&layer, y, 0.6);

    // ── OBSERVACAO DO CONTRIBUINTE ──────────
    y -= SECTION_GAP;
    write_center(
        &layer,
        &font_bold,
        FONT_SIZE_HEADER,
        y,
        "OBSERVACAO DO CONTRIBUINTE",
    );
    y -= LINE_HEIGHT;
    if inf_cpl.is_empty() {
        write_left(
            &layer,
            &font,
            FONT_SIZE_SMALL,
            y,
            "Nenhuma informacao adicional",
        );
        y -= LINE_HEIGHT;
    } else {
        for line in wrap_text(inf_cpl, 55) {
            write_left(&layer, &font, FONT_SIZE_SMALL, y, &line);
            y -= LINE_HEIGHT;
        }
    }
    draw_line(&layer, y + 1.0, 0.6);

    // ── CREDITOS ────────────────────────────
    y -= SECTION_GAP;
    write_center(
        &layer,
        &font,
        FONT_SIZE_CREDITS,
        y,
        "Gerado por dfe - https://crates.io/crates/dfe",
    );

    let bytes = doc
        .save_to_bytes()
        .map_err(|e| format!("Erro ao gerar PDF: {}", e))?;

    Ok(bytes)
}

// ── Helpers ─────────────────────────────────────────────────

fn write_left(layer: &PdfLayerReference, font: &IndirectFontRef, size: f32, y: f32, text: &str) {
    layer.use_text(text, size, Mm(MARGIN_MM), Mm(y), font);
}

fn write_center(layer: &PdfLayerReference, font: &IndirectFontRef, size: f32, y: f32, text: &str) {
    let text_width = estimate_text_width(text, size);
    let x = (MARGIN_MM + (USABLE_WIDTH - text_width) / 2.0).max(MARGIN_MM);
    layer.use_text(text, size, Mm(x), Mm(y), font);
}

fn write_right(layer: &PdfLayerReference, font: &IndirectFontRef, size: f32, y: f32, text: &str) {
    let text_width = estimate_text_width(text, size);
    let x = (MARGIN_MM + USABLE_WIDTH - text_width).max(MARGIN_MM);
    layer.use_text(text, size, Mm(x), Mm(y), font);
}

fn estimate_text_width(text: &str, font_size: f32) -> f32 {
    let scale = font_size / 1000.0 * 0.3528; // pt to mm (1pt = 0.3528mm)
    text.chars()
        .map(|c| match c {
            ' ' => 278.0,
            '!' | 'i' | 'l' | ':' | ';' | ',' | '.' | '\'' => 278.0,
            'f' | 'j' | 't' => 333.0,
            'r' => 333.0,
            'I' | '[' | ']' | '(' | ')' | '/' | '-' => 278.0,
            'a' | 'c' | 'e' | 'o' | 's' => 556.0,
            'b' | 'd' | 'g' | 'h' | 'k' | 'n' | 'p' | 'q' | 'u' | 'v' | 'x' | 'y' | 'z' => 556.0,
            'm' | 'w' => 778.0,
            'A' | 'B' | 'C' | 'D' | 'E' | 'F' | 'G' | 'H' | 'K' | 'N' | 'P' | 'R' | 'S' | 'T'
            | 'U' | 'V' | 'X' | 'Y' | 'Z' => 667.0,
            'M' | 'O' | 'Q' | 'W' => 778.0,
            'J' | 'L' => 556.0,
            '0'..='9' => 556.0,
            _ => 556.0,
        })
        .sum::<f32>()
        * scale
}

fn draw_line(layer: &PdfLayerReference, y: f32, thickness: f32) {
    let points = vec![
        (Point::new(Mm(MARGIN_MM), Mm(y)), false),
        (Point::new(Mm(MARGIN_MM + USABLE_WIDTH), Mm(y)), false),
    ];
    let line = Line {
        points,
        is_closed: false,
    };
    layer.set_outline_thickness(thickness);
    layer.add_line(line);
}

fn truncate_str(s: &str, max_chars: usize) -> String {
    let chars: Vec<char> = s.chars().collect();
    if chars.len() <= max_chars {
        s.to_string()
    } else {
        let truncated: String = chars[..max_chars - 3].iter().collect();
        format!("{}...", truncated)
    }
}

fn format_chave_acesso(chave: &str) -> String {
    chave
        .chars()
        .collect::<Vec<_>>()
        .chunks(4)
        .map(|c| c.iter().collect::<String>())
        .collect::<Vec<_>>()
        .join(" ")
}

fn format_decimal_br(value: &str) -> String {
    value.replace('.', ",")
}

fn wrap_text(text: &str, max_chars: usize) -> Vec<String> {
    let mut lines = Vec::new();
    let mut current = String::new();
    for word in text.split_whitespace() {
        if current.is_empty() {
            current = word.to_string();
        } else if current.len() + 1 + word.len() <= max_chars {
            current.push(' ');
            current.push_str(word);
        } else {
            lines.push(current);
            current = word.to_string();
        }
    }
    if !current.is_empty() {
        lines.push(current);
    }
    lines
}

fn format_brl(value: &str) -> String {
    let v: f64 = value.replace(',', ".").parse().unwrap_or(0.0);
    let formatted = format!("{:.2}", v);
    let parts: Vec<&str> = formatted.split('.').collect();
    let int_part = parts[0];
    let dec_part = parts[1];
    let digits: Vec<char> = int_part.chars().collect();
    let with_dots: String =
        digits
            .iter()
            .rev()
            .enumerate()
            .fold(String::new(), |mut acc, (i, &c)| {
                if i > 0 && i % 3 == 0 {
                    acc.insert(0, '.');
                }
                acc.insert(0, c);
                acc
            });
    format!("{},{}", with_dots, dec_part)
}

fn format_cnpj_cpf(doc: &str) -> String {
    let d: String = doc.chars().filter(|c| c.is_ascii_digit()).collect();
    match d.len() {
        14 => format!(
            "{}.{}.{}/{}-{}",
            &d[0..2],
            &d[2..5],
            &d[5..8],
            &d[8..12],
            &d[12..14]
        ),
        11 => format!("{}.{}.{}-{}", &d[0..3], &d[3..6], &d[6..9], &d[9..11]),
        _ => doc.to_string(),
    }
}

fn format_datetime(dt: &str) -> String {
    if dt.len() >= 19 {
        let date = &dt[..10];
        let time = &dt[11..19];
        let parts: Vec<&str> = date.split('-').collect();
        if parts.len() == 3 {
            return format!("{}/{}/{} {}", parts[2], parts[1], parts[0], time);
        }
    }
    dt.to_string()
}

fn draw_barcode_128(
    layer: &PdfLayerReference,
    data: &str,
    y_top: f32,
    bar_height_mm: f32,
) -> Result<f32, String> {
    let barcode_data = format!("\u{0106}{}", data); // Ć = Code128 character-set C (numeric pairs)
    let barcode =
        Code128::new(&barcode_data).map_err(|e| format!("Erro ao gerar barcode: {}", e))?;
    let encoded: Vec<u8> = barcode.encode();

    let total_modules = encoded.len() as f32;
    let module_width_mm = USABLE_WIDTH / total_modules;
    // printpdf usa espessura em pontos (pt), nao em mm.
    let module_width_pt = module_width_mm * 72.0 / 25.4;

    let y_bottom = y_top - bar_height_mm;

    let mut i = 0usize;
    while i < encoded.len() {
        if encoded[i] == 0 {
            i += 1;
            continue;
        }

        let start = i;
        while i < encoded.len() && encoded[i] == 1 {
            i += 1;
        }

        let run_modules = (i - start) as f32;
        let run_width_pt = module_width_pt * run_modules;
        let run_center_x_mm =
            MARGIN_MM + start as f32 * module_width_mm + (run_modules * module_width_mm / 2.0);

        let points = vec![
            (Point::new(Mm(run_center_x_mm), Mm(y_top)), false),
            (Point::new(Mm(run_center_x_mm), Mm(y_bottom)), false),
        ];
        let line = Line {
            points,
            is_closed: false,
        };
        layer.set_outline_color(Color::Greyscale(Greyscale::new(0.0, None)));
        layer.set_outline_thickness(run_width_pt);
        layer.add_line(line);
    }

    Ok(y_bottom)
}