Une facture électronique Factur-X

Une facture électronique : un fichier PDF/A-3 qui porte son propre XML.

Rust write_facturx.rs 339 lignes
  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
//! Writes an electronic invoice: a PDF/A-3 file carrying its own XML.
//!
//! This is what the whole library is for. A person opens the file and sees an
//! invoice; an accounting system opens the same file and reads the XML sealed
//! inside it. Neither can be separated from the other, which is the point: the
//! page and the data are one document, and cannot disagree.
//!
//! Whether the result is really PDF/A-3 is not for us to say. `veraPDF` says,
//! and `scripts/check_pdfa.sh` asks it.
//!
//! The page is written in the language `HQF_PDF_LANG` names. The XML is not: it
//! is read by an accounting system rather than by a person, its element names
//! come from a standard, and the same file goes to a buyer in any country. So
//! the words a person reads are held in `Words`, once per language, and the
//! attachment stands apart from them.
//!
//! Usage: `cargo run --example write_facturx -- tmp/facturx.pdf [font.ttf]`
//!        `HQF_PDF_LANG=fr cargo run --example write_facturx`

use std::env;
use std::fs;
use std::path::{Path, PathBuf};

use hqf_pdf::content::Content;
use hqf_pdf::metadata::attachment::{Attachment, Relationship};
use hqf_pdf::metadata::xmp::{Invoice, InvoiceProfile, Metadata, PdfA};
use hqf_pdf::{Document, Font, License, Page};

#[path = "shared/out.rs"]
mod out;

#[path = "shared/licence.rs"]
mod licence;

#[path = "shared/language.rs"]
mod language;

use language::Language;

/// The font the example draws with when none is given on the command line.
fn default_font() -> PathBuf {
    Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("tests")
        .join("fonts")
        .join("DejaVuSans.ttf")
}

/// When the invoice was issued. The library never reads the clock — a document
/// that stamped itself with the time would be a different file on every build —
/// so the caller says when, and here the caller is an example.
const ISSUED: &str = "2026-07-14T09:30:00+02:00";

/// The invoice, as a machine reads it.
///
/// This is a Factur-X MINIMUM profile document: the least the standard allows,
/// and enough to show the shape of the thing. A real invoice carries more, and
/// carries it under the same rules.
fn invoice_xml() -> Vec<u8> {
    let xml = r#"<?xml version="1.0" encoding="UTF-8"?>
<rsm:CrossIndustryInvoice
    xmlns:rsm="urn:un:unece:uncefact:data:standard:CrossIndustryInvoice:100"
    xmlns:ram="urn:un:unece:uncefact:data:standard:ReusableAggregateBusinessInformationEntity:100"
    xmlns:udt="urn:un:unece:uncefact:data:standard:UnqualifiedDataType:100">
  <rsm:ExchangedDocumentContext>
    <ram:GuidelineSpecifiedDocumentContextParameter>
      <ram:ID>urn:factur-x.eu:1p0:minimum</ram:ID>
    </ram:GuidelineSpecifiedDocumentContextParameter>
  </rsm:ExchangedDocumentContext>
  <rsm:ExchangedDocument>
    <ram:ID>1964413</ram:ID>
    <ram:TypeCode>380</ram:TypeCode>
    <ram:IssueDateTime>
      <udt:DateTimeString format="102">20260714</udt:DateTimeString>
    </ram:IssueDateTime>
  </rsm:ExchangedDocument>
  <rsm:SupplyChainTradeTransaction>
    <ram:ApplicableHeaderTradeAgreement>
      <ram:SellerTradeParty>
        <ram:Name>Olivier Pons</ram:Name>
        <ram:SpecifiedLegalOrganization>
          <ram:ID schemeID="0002">123456789</ram:ID>
        </ram:SpecifiedLegalOrganization>
        <ram:PostalTradeAddress>
          <ram:CountryID>FR</ram:CountryID>
        </ram:PostalTradeAddress>
      </ram:SellerTradeParty>
      <ram:BuyerTradeParty>
        <ram:Name>ACME Ltd</ram:Name>
      </ram:BuyerTradeParty>
    </ram:ApplicableHeaderTradeAgreement>
    <ram:ApplicableHeaderTradeDelivery/>
    <ram:ApplicableHeaderTradeSettlement>
      <ram:InvoiceCurrencyCode>EUR</ram:InvoiceCurrencyCode>
      <ram:SpecifiedTradeSettlementHeaderMonetarySummation>
        <ram:TaxBasisTotalAmount>4250.00</ram:TaxBasisTotalAmount>
        <ram:TaxTotalAmount currencyID="EUR">850.00</ram:TaxTotalAmount>
        <ram:GrandTotalAmount>5100.00</ram:GrandTotalAmount>
        <ram:DuePayableAmount>5100.00</ram:DuePayableAmount>
      </ram:SpecifiedTradeSettlementHeaderMonetarySummation>
    </ram:ApplicableHeaderTradeSettlement>
  </rsm:SupplyChainTradeTransaction>
</rsm:CrossIndustryInvoice>
"#;
    xml.as_bytes().to_vec()
}

/// The invoice's number, which the page shows and the XML carries under
/// `ram:ID`. One number, written once on each side.
const NUMBER: &str = "1964413";

/// What each of the three billed lines comes to, in the order they are set.
/// These are the figures the XML totals, so they read the same wherever the
/// page is read.
const AMOUNTS: [&str; 3] = ["4 250.00 EUR", "850.00 EUR", "5 100.00 EUR"];

/// How many characters a billed line runs to: its label, a space, the leader
/// dots, a space, then its amount. The dots take whatever is left, so the
/// amounts end on the same character however long the label before them is.
const LINE_CHARS: usize = 56;

/// The size each line of the page is set at, in points, in the order they are
/// drawn.
const SIZES: [f64; 5] = [16.0, 11.0, 11.0, 11.0, 12.0];

/// How far in from the left edge of the sheet every line is set, in points.
const LEFT: f64 = 72.0;

/// The words the page is written in, one set per language.
///
/// What is not language stays out of it: the invoice's number, who issued it
/// and the three amounts read the same wherever the page is read, and so does
/// every word of the XML.
#[derive(Debug)]
struct Words {
    /// What stands before the invoice's number, at the head of the page and in
    /// the document's own title.
    number_label: &'static str,
    /// What the file says it holds.
    subject: &'static str,
    /// The line that gives the day it was issued and the term it falls due in.
    dates: &'static str,
    /// What each billed line is called, in the order `AMOUNTS` prices them.
    items: [&'static str; AMOUNTS.len()],
}

impl Words {
    /// The words the page is written in, in `language`.
    fn of(language: Language) -> &'static Self {
        language::pick(&WORDS, language)
    }

    /// What the page is headed by, which is also what the file says of itself.
    fn title(&self) -> String {
        format!("{} {NUMBER}", self.number_label)
    }

    /// The lines the page shows, which say what the XML says.
    fn lines(&self) -> Vec<String> {
        let mut lines = vec![self.title(), self.dates.to_owned()];
        lines.extend(self.items.iter().zip(AMOUNTS).map(|(item, amount)| {
            let dots = LINE_CHARS.saturating_sub(item.chars().count() + amount.chars().count() + 2);
            format!("{item} {} {amount}", ".".repeat(dots))
        }));
        lines
    }
}

/// The page in English.
const ENGLISH: Words = Words {
    number_label: "Invoice No.",
    subject: "An electronic invoice, in the Factur-X format",
    dates: "Issued 14 July 2026 — due within 30 days",
    items: ["Rendering engine development", "VAT at 20 %", "Total due"],
};

/// The page in French.
const FRENCH: Words = Words {
    number_label: "Facture n°",
    subject: "Une facture électronique, au format Factur-X",
    dates: "Émise le 14 juillet 2026 — payable sous 30 jours",
    items: [
        "Développement du moteur de rendu",
        "TVA 20 %",
        "Total à payer",
    ],
};

/// Every language the example is written in. A language is added by writing its
/// own set of words and naming it here.
static WORDS: [(Language, &Words); 2] =
    [(Language::English, &ENGLISH), (Language::French, &FRENCH)];

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let language = Language::from_environment()?;
    let words = Words::of(language);

    let mut args: Vec<String> = env::args().skip(1).collect();

    // An archival file may carry no font it does not embed. An evaluation copy
    // must still be marked, so its notice is set in the document's own font and
    // embedded with it — which is what this asks for, so that a validator can
    // be pointed at a marked archival file and not only at a clean one.
    let evaluation = args.iter().any(|arg| arg == "--evaluation");
    args.retain(|arg| arg != "--evaluation");

    let mut args = args.into_iter();
    // A named file is written as named; the default one carries the language,
    // so the two languages do not overwrite each other in `tmp/`.
    let path = args
        .next()
        .unwrap_or_else(|| language.file_name(&out::default_path("facturx")));
    let font_path = args.next().map_or_else(default_font, PathBuf::from);

    let mut doc = Document::new();
    doc.set_license(if evaluation {
        License::evaluation()
    } else {
        licence::licensed()
    });
    doc.set_conformance(PdfA::A3B);

    doc.set_metadata(Metadata {
        title: Some(words.title()),
        author: Some("Olivier Pons".to_owned()),
        subject: Some(words.subject.to_owned()),
        producer: Some("hqf-pdf".to_owned()),
        created: Some(ISSUED.to_owned()),
        invoice: Some(Invoice {
            file_name: "factur-x.xml".to_owned(),
            profile: InvoiceProfile::Minimum,
            version: "1.0".to_owned(),
        }),
        ..Metadata::default()
    });

    // What the attachment *is* to the document is not decoration, and has no
    // sensible default: `Data` is right for the profiles that carry only part
    // of the invoice, and `Alternative` for those that carry all of it. This
    // one is MINIMUM, which carries part.
    doc.attach(Attachment::invoice(
        invoice_xml(),
        Relationship::Data,
        ISSUED,
    ));

    let font = doc.add_font(Font::parse(fs::read(&font_path)?)?);

    let mut content = Content::new();
    let mut top = 760.0;
    for (line, size) in words.lines().iter().zip(SIZES) {
        content.begin_text();
        content.set_font(font.name(), size)?;
        content.text_origin(LEFT, top)?;
        content.show_glyphs(&font.glyphs(line));
        content.end_text();
        top = size.mul_add(-2.0, top);
    }

    let mut page = Page::a4();
    page.content = content.into_bytes();
    doc.add_page(page)?;

    let bytes = doc.to_bytes()?;
    if let Some(parent) = Path::new(&path).parent() {
        fs::create_dir_all(parent)?;
    }
    fs::write(&path, &bytes)?;

    println!("wrote {path}: {} bytes", bytes.len());
    Ok(())
}

#[cfg(test)]
mod tests {
    use hqf_pdf::{Document, Font};

    use super::{LEFT, LINE_CHARS, SIZES, WORDS, default_font, language};

    /// The width of the sheet, in points: A4, which the page is.
    const SHEET_WIDTH: f64 = 595.276;

    /// The room a line set from the left margin has before it reaches the
    /// margin on the other side of the sheet.
    const PAPER: f64 = SHEET_WIDTH - 2.0 * LEFT;

    /// The lines two languages are allowed to write the same way. There are
    /// none: the invoice's number, the amounts and every word of the XML are
    /// held outside the words.
    const SPARED: [&str; 0] = [];

    #[test]
    fn every_language_draws_the_page_in_its_own_words() {
        let untranslated = language::untranslated_lines(&WORDS, &SPARED);

        assert!(
            untranslated.is_empty(),
            "the page says these in more than one language: {untranslated:?}"
        );
    }

    /// The leader dots are counted, not typed, so every billed line ends its
    /// amount on the same character in every language.
    #[test]
    fn every_billed_line_runs_to_the_same_width() {
        for (named, words) in WORDS {
            for line in words.lines().iter().skip(2) {
                assert_eq!(
                    line.chars().count(),
                    LINE_CHARS,
                    "the {} page bills {line:?}",
                    named.code()
                );
            }
        }
    }

    /// Nothing on the page is broken to a width: a line longer than the paper
    /// runs off the edge of it.
    #[test]
    fn every_language_writes_lines_that_fit_the_room_they_have() {
        let mut doc = Document::new();
        let text = doc.add_font(
            Font::parse(std::fs::read(default_font()).expect("the committed font is there"))
                .expect("the committed font parses"),
        );

        for (named, words) in WORDS {
            for (line, size) in words.lines().iter().zip(SIZES) {
                let measured = text.measure(line, size);
                assert!(
                    measured <= PAPER,
                    "the {} page draws {line:?} over {measured:.1} points, \
                     and it has {PAPER:.1}",
                    named.code()
                );
            }
        }
    }
}