### Invoice Generation Example Source: https://github.com/cirfmf/ksef-pdf-generator/blob/main/_autodocs/01-api-reference-main.md Example demonstrating how to use the generateInvoice function to create a PDF from an XML file, either as a blob for download or as a base64 string. ```typescript import { generateInvoice } from '@akmf/ksef-fe-invoice-converter'; const file = document.querySelector('input[type="file"]').files[0]; const additionalData = { nrKSeF: '1234567890', qrCode: 'https://example.com/invoice', isMobile: false, watermark: 'ORIGINAL' }; // Generate as blob const pdfBlob = await generateInvoice(file, additionalData, 'blob'); const url = URL.createObjectURL(pdfBlob); const link = document.createElement('a'); link.href = url; link.download = 'invoice.pdf'; link.click(); // Generate as base64 const pdfBase64 = await generateInvoice(file, additionalData, 'base64'); console.log(pdfBase64); // 'JVBERi0xLjQKJeLjz9MNCjEgMCBvYmo...' ``` -------------------------------- ### Minimal Configuration Example Source: https://github.com/cirfmf/ksef-pdf-generator/blob/main/_autodocs/04-configuration.md Demonstrates the minimum required configuration for generating a KSeF invoice PDF. Only the 'nrKSeF' field is mandatory. ```typescript import { generateInvoice } from '@akmf/ksef-fe-invoice-converter'; const basicConfig = { nrKSeF: '1234567890' }; const pdfBlob = await generateInvoice(xmlFile, basicConfig, 'blob'); ``` -------------------------------- ### Install and Import Ksef PDF Generator Source: https://github.com/cirfmf/ksef-pdf-generator/blob/main/_autodocs/06-quick-reference.md Install the converter package and import the generation function. Use this to generate PDFs from invoice data. ```typescript // Install npm install @akmf/ksef-fe-invoice-converter // Import import { generateInvoice } from '@akmf/ksef-fe-invoice-converter'; // Use const pdf = await generateInvoice(file, config, 'blob'); ``` -------------------------------- ### Full Configuration Example Source: https://github.com/cirfmf/ksef-pdf-generator/blob/main/_autodocs/04-configuration.md Shows how to use all available configuration fields for generating a KSeF invoice PDF, including QR codes and watermark. ```typescript const fullConfig = { nrKSeF: '1234567890', qrCode: 'https://example.com/invoice/FA-2024-001', qr2Code: 'https://compliance.example.com/ref123', isMobile: false, watermark: 'ORIGINAL' }; const pdfBlob = await generateInvoice(xmlFile, fullConfig, 'blob'); ``` -------------------------------- ### Mobile Optimized Configuration Example Source: https://github.com/cirfmf/ksef-pdf-generator/blob/main/_autodocs/04-configuration.md Illustrates a configuration optimized for mobile display, setting 'isMobile' to true and including a watermark. ```typescript const mobileConfig = { nrKSeF: '1234567890', isMobile: true, watermark: 'COPY' }; const pdfBlob = await generateInvoice(xmlFile, mobileConfig, 'blob'); ``` -------------------------------- ### Example Usage of getTStawkaPodatku Source: https://github.com/cirfmf/ksef-pdf-generator/blob/main/_autodocs/03-api-reference-utilities.md Demonstrates how to use the getTStawkaPodatku function with different tax codes, invoice versions, and margin scheme indicators. ```typescript import { getTStawkaPodatku } from '@akmf/ksef-fe-invoice-converter'; getTStawkaPodatku('23', 1); // 'const.fa.taxRate23' getTStawkaPodatku('8', 2); // 'const.fa.taxRate8' getTStawkaPodatku('', 1, '1'); // 'marża' (margin scheme) ``` -------------------------------- ### Configuration Object Example Source: https://github.com/cirfmf/ksef-pdf-generator/blob/main/_autodocs/README.md Define a configuration object for PDF generation, including required fields like `nrKSeF` and optional fields such as `qrCode`, `watermark`, and `isMobile`. ```typescript const config = { nrKSeF: '1234567890', // Required qrCode: 'https://...', // Optional but recommended watermark: 'ORIGINAL', // Optional isMobile: false // Optional }; ``` -------------------------------- ### Generate and Download Invoice PDF Source: https://github.com/cirfmf/ksef-pdf-generator/blob/main/_autodocs/README.md This minimal example demonstrates how to generate a PDF invoice from an XML file and initiate its download. It requires importing the `generateInvoice` function and provides a basic configuration object. ```typescript import { generateInvoice } from '@akmf/ksef-fe-invoice-converter'; const xmlFile = document.querySelector('input[type="file"]').files[0]; const config = { nrKSeF: '1234567890' }; const pdfBlob = await generateInvoice(xmlFile, config, 'blob'); // Download const url = URL.createObjectURL(pdfBlob); const link = document.createElement('a'); link.href = url; link.download = 'invoice.pdf'; link.click(); ``` -------------------------------- ### Generate Invoice with Comprehensive Error Handling Source: https://github.com/cirfmf/ksef-pdf-generator/blob/main/_autodocs/05-errors.md This example demonstrates how to wrap the invoice generation process in a try-catch block to handle potential errors. It includes specific checks for common issues like missing input files or incorrect KSeF numbers, and provides user-friendly error messages. ```typescript import { generateInvoice, i18nReady } from '@akmf/ksef-fe-invoice-converter'; async function generateInvoiceWithErrorHandling(xmlFile, additionalData) { try { // Wait for i18n await i18nReady; // Validate input if (!xmlFile) { throw new Error('XML file is required'); } if (!additionalData?.nrKSeF) { throw new Error('KSeF number is required in additionalData'); } // Generate PDF const pdfBlob = await generateInvoice(xmlFile, additionalData, 'blob'); // Success return pdfBlob; } catch (error) { // Handle known error types if (error.message?.startsWith('Unknown XML Version')) { console.error('Unsupported invoice format:', error.message); throw new Error('Invoice format not supported. Please use FA(1), FA(2), FA(3), or FA_RR(1)'); } if (error.message?.includes('XML') || error.message?.includes('parse')) { console.error('XML parsing error:', error.message); throw new Error('Invalid XML file. Ensure it is well-formed and valid KSeF invoice'); } // Re-throw or handle generic errors console.error('Unexpected error generating PDF:', error); throw error; } } // Usage document.getElementById('generateBtn').addEventListener('click', async () => { const xmlFile = document.querySelector('input[type="file"]').files[0]; const additionalData = { nrKSeF: '1234567890', watermark: 'ORIGINAL' }; try { const pdfBlob = await generateInvoiceWithErrorHandling(xmlFile, additionalData); const url = URL.createObjectURL(pdfBlob); const link = document.createElement('a'); link.href = url; link.download = 'invoice.pdf'; link.click(); } catch (error) { alert('Error: ' + error.message); } }); ``` -------------------------------- ### Example Section Generator Source: https://github.com/cirfmf/ksef-pdf-generator/blob/main/_autodocs/07-generator-architecture.md Illustrates the common pattern for generating a PDF section. It takes typed data, conditionally adds content like headers and labeled fields, and returns a pdfmake Content array. Returns an empty array if no data is provided. ```typescript // File: src/lib-public/generators/FA1/ExampleSection.ts import { Content } from 'pdfmake/interfaces'; import { FP } from '../../types/fa1.types'; import { createHeader, createLabelText, hasValue } from '@shared/PDF-functions'; // Interface for section data interface ExampleSectionData { fieldA?: FP; fieldB?: FP; items?: ExampleItem[]; } interface ExampleItem { name?: FP; value?: FP; } // Main generator function export function generateExampleSection(data: ExampleSectionData | undefined): Content[] { // Return empty if no data if (!data) { return []; } const content: Content[] = []; // Add header content.push(...createHeader('Section Title')); // Add fields conditionally if (hasValue(data.fieldA)) { content.push(...createLabelText('Field A: ', data.fieldA)); } // Return wrapped content return content.length > 0 ? content : []; } ``` -------------------------------- ### Enable i18next Debug Mode Source: https://github.com/cirfmf/ksef-pdf-generator/blob/main/_autodocs/05-errors.md To get more detailed logging for internationalization issues, set the 'debug' option to true in your i18next initialization. ```typescript // Modify src/lib-public/i18n/i18n-init.ts i18next.init({ debug: true, // Set to true for verbose logging // ... }) ``` -------------------------------- ### FP Type Usage Example Source: https://github.com/cirfmf/ksef-pdf-generator/blob/main/_autodocs/08-data-types-detailed.md Demonstrates how to use the FP type with helper functions getValue and hasValue. This type is used for all string, number, and date fields in invoice structures. ```typescript const field: FP = { _text: '12345' }; const value = getValue(field); // Returns '12345' const text = hasValue(field); // Returns true ``` -------------------------------- ### Invoice Data Hierarchy Source: https://github.com/cirfmf/ksef-pdf-generator/blob/main/_autodocs/07-generator-architecture.md Illustrates the hierarchical structure of invoice data, starting from the root 'Faktura' and branching into sections like header, parties, invoice details, line items, and footer. ```plaintext Faktura (root) ├── Naglowek ├── Podmiot1, Podmiot2, Podmiot3[], PodmiotUpowazniony ├── Fa (invoice details) │ ├── KodWaluty, P_1, P_2, etc. (simple FP fields) │ ├── FaWiersze (line items) │ │ └── FaWiersz[] (individual lines) │ ├── Adnotacje (annotations) │ ├── Rozliczenie (settlement) │ ├── Platnosc (payment) │ ├── WarunkiTransakcji (transaction terms) │ ├── Zamowienie (orders) │ └── ... └── Stopka (footer) ``` -------------------------------- ### Full Import of Utilities Source: https://github.com/cirfmf/ksef-pdf-generator/blob/main/_autodocs/06-quick-reference.md Import all available utilities from the library for comprehensive functionality. ```typescript import { generateInvoice, generateFA1, generateFA2, generateFA3, generateFARR, generatePDFUPO, generateStyle, formatText, getValue, hasValue, getNumber, i18next, i18nReady, FormatTyp, Position, Answer } from '@akmf/ksef-fe-invoice-converter'; ``` -------------------------------- ### Generate Invoice PDF - Get Base64 String Source: https://github.com/cirfmf/ksef-pdf-generator/blob/main/_autodocs/06-quick-reference.md Shows how to obtain the generated PDF invoice as a Base64 encoded string. This is useful for transmitting or storing the PDF data directly. ```typescript const pdfBase64 = await generateInvoice(xmlFile, config, 'base64'); console.log(pdfBase64); // 'JVBERi0xLjQK...' ``` -------------------------------- ### Import with Formatting Utilities Source: https://github.com/cirfmf/ksef-pdf-generator/blob/main/_autodocs/06-quick-reference.md Import `generateInvoice` along with formatting utilities like `formatText` and `FormatTyp`. ```typescript import { generateInvoice, formatText, FormatTyp } from '@akmf/ksef-fe-invoice-converter'; ``` -------------------------------- ### Get Tax Rate Name Source: https://github.com/cirfmf/ksef-pdf-generator/blob/main/_autodocs/03-api-reference-utilities.md Retrieves the tax rate name based on a tax code, invoice version, and an optional margin scheme indicator. Used for displaying tax information. ```typescript export function getTStawkaPodatku( code: string, version: 1 | 2 | 3 | 'RR', P_PMarzy?: string ): string ``` -------------------------------- ### Generate Buyer Information (Podmiot2) Source: https://github.com/cirfmf/ksef-pdf-generator/blob/main/_autodocs/07-generator-architecture.md Generates the buyer's information block, similar in structure to the seller's information. ```typescript export function generatePodmiot2(fa: Fa): Content[] ``` -------------------------------- ### Generate Invoice PDF - Full Configuration Source: https://github.com/cirfmf/ksef-pdf-generator/blob/main/_autodocs/06-quick-reference.md Illustrates using `generateInvoice` with a comprehensive configuration object, including options for QR codes, mobile view, and watermarks. The output is a PDF Blob. ```typescript const config = { nrKSeF: '1234567890', qrCode: 'https://example.com/invoice/FA-2024-001', qr2Code: 'https://track.example.com/xyz', isMobile: false, watermark: 'ORIGINAL' }; const pdfBlob = await generateInvoice(xmlFile, config, 'blob'); ``` -------------------------------- ### Generate and Download UPO PDF Source: https://github.com/cirfmf/ksef-pdf-generator/blob/main/_autodocs/06-quick-reference.md Use this snippet to generate a Proof of Delivery (UPO) PDF from an XML file and initiate a download. Ensure the XML file is correctly selected. ```typescript import { generatePDFUPO } from '@akmf/ksef-fe-invoice-converter'; const xmlFile = document.querySelector('input[type="file"]').files[0]; const pdfBlob = await generatePDFUPO(xmlFile); // Download const url = URL.createObjectURL(pdfBlob); const link = document.createElement('a'); link.href = url; link.download = 'upo.pdf'; link.click(); ``` -------------------------------- ### Generate Seller Information (Podmiot1) Source: https://github.com/cirfmf/ksef-pdf-generator/blob/main/_autodocs/07-generator-architecture.md Generates the seller's information block, including company name, tax ID, address, and contact details. ```typescript export function generatePodmiot1(fa: Fa): Content[] ``` -------------------------------- ### Initialize i18next for Localization Source: https://github.com/cirfmf/ksef-pdf-generator/blob/main/_autodocs/04-configuration.md Initializes the i18next library with a default language, debug mode, and resource bundles for English and Polish translations. Ensure translation files are correctly placed. ```typescript i18next.init({ lng: 'pl', // Default language debug: true, // Enable debug logging resources: { en: { translation: en }, pl: { translation: pl } } }) ``` -------------------------------- ### Invoice Generation Flow Source: https://github.com/cirfmf/ksef-pdf-generator/blob/main/_autodocs/07-generator-architecture.md Illustrates the step-by-step process of generating an invoice PDF, from initial user input to the final PDF creation using pdfMake. ```plaintext User Input ↓ XML File ↓ parseXML() ↓ JSON Object (matches Faktura type) ↓ detectFormat() [reads kodSystemowy] ↓ generateFA1/FA2/FA3/FARR() ↓ docDefinition: TDocumentDefinitions { content: [ generateNaglowek(), generatePodmioty(), generateSzczegoly(), generateWiersze() or generateRabat(), generatePodsumowanieStawekPodatkuVat(), generateAdnotacje(), generateDodatkoweInformacje(), generateRozliczenie(), generatePlatnosc(), generateWarunkiTransakcji(), generateStopka() ], styles: generateStyle(), footer: (currentPage, pageCount) => {...} } ↓ pdfMake.createPdf(docDefinition) ↓ TCreatedPdf ↓ .getBlob() or .getBase64() ↓ Output (Blob | string) ``` -------------------------------- ### Validate Required Configuration and File Source: https://github.com/cirfmf/ksef-pdf-generator/blob/main/_autodocs/06-quick-reference.md Ensure that essential configuration fields like 'nrKSeF' and a valid XML file are provided before proceeding. ```typescript if (!config.nrKSeF) { throw new Error('nrKSeF is required'); } if (!file || file.type !== 'text/xml') { throw new Error('Valid XML file required'); } ``` -------------------------------- ### Generate Tax Summary by Rate (PodsumowanieStawekPodatkuVat) Source: https://github.com/cirfmf/ksef-pdf-generator/blob/main/_autodocs/07-generator-architecture.md Generates a summary of taxes broken down by rate, including net, tax, and gross amounts per rate. Requires the invoice data. ```typescript export function generatePodsumowanieStawekPodatkuVat( invoice: Faktura ): Content[] ``` -------------------------------- ### Vite Build Configuration Source: https://github.com/cirfmf/ksef-pdf-generator/blob/main/_autodocs/06-quick-reference.md Configure Vite for building the Ksef PDF Generator library. Specifies entry point and output formats. ```typescript // vite.config.ts import { defineConfig } from 'vite'; export default defineConfig({ build: { lib: { entry: 'src/index.ts', name: 'KsefPdfGenerator', formats: ['es', 'umd'] } } }); ``` -------------------------------- ### Parsing XML Data with Utility Source: https://github.com/cirfmf/ksef-pdf-generator/blob/main/_autodocs/08-data-types-detailed.md Demonstrates how to parse XML files into a structured object using the `parseXML` utility. It shows how to access nested fields and highlights the optional nature of fields and the FP type wrapper. ```typescript import { parseXML } from '@akmf/ksef-fe-invoice-converter'; const data = await parseXML(xmlFile); const faktura: Faktura = data.Faktura; const version = faktura.Naglowek?.KodFormularza?._attributes?.kodSystemowy; // Type system ensures: // - All fields are optional (may not exist in XML) // - All values wrapped in FP type // - Use getValue() to extract _text // - Use hasValue() to check if field exists ``` -------------------------------- ### Generate UPO PDF from XML File Source: https://github.com/cirfmf/ksef-pdf-generator/blob/main/_autodocs/01-api-reference-main.md Generates a PDF visualization for the Unified Proof of Delivery (UPO) document in v4.2 format. This function is asynchronous and expects an XML file as input. It returns a Promise that resolves to a Blob representing the PDF. ```typescript export async function generatePDFUPO(file: File): Promise ``` ```typescript import { generatePDFUPO } from '@akmf/ksef-fe-invoice-converter'; const file = document.querySelector('input[type="file"]').files[0]; const pdfBlob = await generatePDFUPO(file); const url = URL.createObjectURL(pdfBlob); const link = document.createElement('a'); link.href = url; link.download = 'upo.pdf'; link.click(); ``` -------------------------------- ### Generate PDF Styling Configuration Source: https://github.com/cirfmf/ksef-pdf-generator/blob/main/_autodocs/01-api-reference-main.md Returns the complete styling configuration for a PDF document, including font specifications, color schemes, margins, and predefined text styles. This is useful for applying consistent styling across PDF elements. ```typescript import { generateStyle } from '@akmf/ksef-fe-invoice-converter'; const docDefinition = { content: [/* ... */], ...generateStyle(), }; ``` -------------------------------- ### Minimal Import Source: https://github.com/cirfmf/ksef-pdf-generator/blob/main/_autodocs/06-quick-reference.md Import only the necessary `generateInvoice` function for basic usage. ```typescript import { generateInvoice } from '@akmf/ksef-fe-invoice-converter'; ``` -------------------------------- ### Generate All Parties (Podmioty) Source: https://github.com/cirfmf/ksef-pdf-generator/blob/main/_autodocs/07-generator-architecture.md Coordinates the generation of all party sections, including seller, buyer, additional parties, and authorized representatives. It depends on the core invoice data. ```typescript export function generatePodmioty(invoice: Faktura): Content[] ``` -------------------------------- ### generatePDFUPO Source: https://github.com/cirfmf/ksef-pdf-generator/blob/main/_autodocs/01-api-reference-main.md Generates a PDF visualization for the Unified Proof of Delivery (Upoważnienie — UPO) document in format v4.2. This function creates a landscape-oriented document with header and detailed delivery/confirmation records in tabular layout. ```APIDOC ## generatePDFUPO ### Description Generates PDF visualization for Unified Proof of Delivery (Upoważnienie — UPO) document in format v4.2. Creates landscape-oriented document with header and detailed delivery/confirmation records in tabular layout. ### Signature ```typescript export async function generatePDFUPO(file: File): Promise ``` ### Parameters #### Path Parameters - **file** (File) - Required - XML file containing UPO v4.2 data structure ### Return Type Promise — Binary PDF blob, landscape A4 format ### Throws - **Error** - If XML parsing fails ### Example ```typescript import { generatePDFUPO } from '@akmf/ksef-fe-invoice-converter'; const file = document.querySelector('input[type="file"]').files[0]; const pdfBlob = await generatePDFUPO(file); const url = URL.createObjectURL(pdfBlob); const link = document.createElement('a'); link.href = url; link.download = 'upo.pdf'; link.click(); ``` ### Behavior Notes - Parses XML from file using `parseXML` utility - Waits for i18n initialization before generating PDF - Sets page orientation to landscape for better table layout - Includes page footer with current page and total page count - Applies default PDF styling and Roboto font ``` -------------------------------- ### Catch i18next Initialization Errors Source: https://github.com/cirfmf/ksef-pdf-generator/blob/main/_autodocs/05-errors.md Use a try-catch block to handle potential failures during i18n initialization. This is crucial as invoice generation functions depend on i18n being ready. ```typescript import { i18nReady } from '@akmf/ksef-fe-invoice-converter'; try { await i18nReady; // i18n is ready, translations available } catch (error) { console.error('i18n initialization failed:', error); // PDF generation will likely fail due to missing translations } ``` -------------------------------- ### generateStyle Source: https://github.com/cirfmf/ksef-pdf-generator/blob/main/_autodocs/01-api-reference-main.md Returns the complete styling configuration for PDF documents. This includes font specifications, color schemes, margins, and predefined text styles. ```APIDOC ## generateStyle ### Description Returns complete PDF document styling configuration including font specifications, color schemes, margins, and predefined text styles. ### Method ```typescript export function generateStyle(): Partial ``` ### Return Type Partial — Object containing: - `styles`: Named style definitions (Label, Value, Bold, HeaderContent, etc.) - `defaultStyle`: Default font (Roboto, 7pt), line height 1.2 ### Example ```typescript import { generateStyle } from '@akmf/ksef-fe-invoice-converter'; const docDefinition = { content: [/* ... */], ...generateStyle(), }; ``` ### Predefined Styles | Style Name | Properties | |------------|-----------| | Label | Bold, #343A40 color | | Value | #343A40 color | | Bold | Bold, 9pt | | HeaderContent | Bold, 10pt, #343A40 | | LabelMedium | Bold, 9pt, #343A40 | | GrayBoldTitle | Gray background (#F6F7FA), bold | | GrayTitle | Gray background (#F6F7FA) | | Link | Blue color | ``` -------------------------------- ### generatePDFUPO() Source: https://github.com/cirfmf/ksef-pdf-generator/blob/main/_autodocs/00-index.md Generates a UPO delivery confirmation PDF from the provided file. Returns the generated PDF as a Blob. ```APIDOC ## generatePDFUPO() ### Description Generates a UPO delivery confirmation PDF from the provided file. Returns the generated PDF as a Blob. ### Signature `generatePDFUPO(file) → Promise` ### Parameters - **file**: The file to generate the UPO PDF from. ### Returns - `Promise`: A Promise that resolves with the generated UPO PDF as a Blob. ``` -------------------------------- ### Common Invoice Generation Workflow Source: https://github.com/cirfmf/ksef-pdf-generator/blob/main/_autodocs/06-quick-reference.md A typical asynchronous workflow for generating an invoice PDF, including i18n readiness, configuration, generation, and download. ```typescript import { generateInvoice, i18nReady } from '@akmf/ksef-fe-invoice-converter'; async function handleInvoiceGeneration(xmlFile) { // Step 1: Wait for i18n await i18nReady; // Step 2: Prepare configuration const config = { nrKSeF: getUserKSeFNumber(), watermark: 'ORIGINAL' }; // Step 3: Generate PDF try { const pdfBlob = await generateInvoice(xmlFile, config, 'blob'); // Step 4: Download or transmit downloadPDF(pdfBlob, 'invoice.pdf'); } catch (error) { console.error('Generation failed:', error); showErrorMessage(error.message); } } function downloadPDF(blob, filename) { const url = URL.createObjectURL(blob); const link = document.createElement('a'); link.href = url; link.download = filename; link.click(); URL.revokeObjectURL(url); } ``` -------------------------------- ### Generate Discount Section (Rabat) Source: https://github.com/cirfmf/ksef-pdf-generator/blob/main/_autodocs/07-generator-architecture.md Generates a table for discount and correction details, specifically for corrective invoices. ```typescript export function generateRabat(fa: Fa): Content[] ``` -------------------------------- ### Wait for i18next Initialization Source: https://github.com/cirfmf/ksef-pdf-generator/blob/main/_autodocs/03-api-reference-utilities.md A promise that resolves when the i18next internationalization library is fully initialized and ready for use. This ensures translations are available before attempting to access them. ```typescript import { i18nReady } from '@akmf/ksef-fe-invoice-converter'; // Wait for i18n before using translations await i18nReady; i18n.t('invoice.footer.pagesTotal'); // Translations now available ``` -------------------------------- ### generateQRCode Source: https://github.com/cirfmf/ksef-pdf-generator/blob/main/_autodocs/03-api-reference-utilities.md Generates a QR code content element from a given string, with options for customization. ```APIDOC ## generateQRCode ### Description Generates QR code content element. ### Signature ```typescript export function generateQRCode(qrCode?: string): ContentQr | undefined ``` ### Parameters #### Parameters - **qrCode** (string) - Optional - QR code data string ### Return Type ContentQr | undefined — QR code element or undefined if no data ### Example ```typescript import { generateQRCode } from '@akmf/ksef-fe-invoice-converter'; const qr = generateQRCode('https://example.com/invoice/123'); // Result: { qr: 'https://...', fit: 150, foreground: 'black', background: 'white', eccLevel: 'M' } ``` ``` -------------------------------- ### createHeader Source: https://github.com/cirfmf/ksef-pdf-generator/blob/main/_autodocs/03-api-reference-utilities.md Creates a section header with consistent formatting for titles within the PDF. ```APIDOC ## createHeader ### Description Creates section header with consistent formatting. ### Signature ```typescript export function createHeader( text: string, margin?: Margins ): Content[] ``` ### Parameters #### Parameters - **text** (string) - Required - Header text - **margin** (Margins) - Optional - Top, right, bottom, left margins ### Return Type Content[] — Header element with HeaderContent style ``` -------------------------------- ### Generate Additional Parties (Podmiot3) Source: https://github.com/cirfmf/ksef-pdf-generator/blob/main/_autodocs/07-generator-architecture.md Generates information for additional parties, such as shipping or recipient details. ```typescript export function generatePodmiot3(fa: Fa): Content[] ``` -------------------------------- ### Generate Multi-Column Layout Source: https://github.com/cirfmf/ksef-pdf-generator/blob/main/_autodocs/03-api-reference-utilities.md Creates an equal-width multi-column layout. Accepts an array of column content arrays and an optional custom style. ```typescript export function generateColumns( contents: Content[][], style?: Style | undefined ): Content ``` -------------------------------- ### createLabelTextArray Source: https://github.com/cirfmf/ksef-pdf-generator/blob/main/_autodocs/03-api-reference-utilities.md Creates PDF content from an array of label-value pairs, simplifying the generation of multiple labeled data points. ```APIDOC ## createLabelTextArray ### Description Creates PDF content from array of label-value pairs. ### Signature ```typescript export function createLabelTextArray( data: CreateLabelTextData[] ): Content[] ``` ### Parameters #### Parameters - **data** (CreateLabelTextData[]) - Required - Array of label data objects ### CreateLabelTextData Structure ```typescript interface CreateLabelTextData { value: FP | string | number | undefined; formatTyp?: FormatTyp; currency?: string; } ``` ### Return Type Content[] — Array with formatted labels and values ``` -------------------------------- ### Generator Directory Structure Source: https://github.com/cirfmf/ksef-pdf-generator/blob/main/_autodocs/07-generator-architecture.md Illustrates the hierarchical organization of generator files within the library, categorized by invoice format (FA1, FA2, FA3, FA_RR, UPO4_2, UPO4_3) and common utilities. ```tree src/lib-public/generators/ ├── FA1/ # FA(1) format generators │ ├── Adnotacje.ts # Annotations/notes section │ ├── Adnotacje2.ts # Secondary annotations │ ├── DodatkoweInformacje.ts # Additional information │ ├── Platnosc.ts # Payment details │ ├── Podmiot1.ts # Seller data │ ├── Podmiot2.ts # Buyer data │ ├── Podmiot3.ts # Additional parties │ ├── PodmiotAdres.ts # Party address │ ├── PodmiotDaneIdentyfikacyjne.ts # ID data │ ├── PodmiotDaneKontaktowe.ts # Contact data │ ├── PodmiotUpowazniony.ts # Authorized rep │ ├── Podmioty.ts # All parties section │ ├── PodsumowanieStawekPodatkuVat.ts # Tax summary │ ├── Przewoznik.ts # Carrier/Transport │ ├── Rabat.ts # Discount section │ ├── Szczegoly.ts # Invoice details │ ├── WarunkiTransakcji.ts # Transaction conditions │ └── Wiersze.ts # Line items │ └── Zamowienie.ts # Order section ├── FA2/ # FA(2) format (extends FA1) │ └── [Similar structure with FA2-specific variations] ├── FA3/ # FA(3) format (extends FA2) │ └── [Includes attachment support] ├── FA_RR/ # FA_RR (corrective format) │ ├── DodatkoweInformacje.ts │ ├── Naglowek.ts │ ├── Platnosc.ts │ ├── Podmioty.ts │ ├── Szczegoly.ts │ └── Wiersze.ts ├── UPO4_2/ # UPO v4.2 format │ └── [UPO-specific generators] ├── UPO4_3/ # UPO v4.3 format │ ├── Dokumenty.ts # Document records │ ├── Naglowek.ts # Header │ └── [Additional sections] └── common/ # Shared across all formats ├── DaneFaKorygowanej.ts # Corrected invoice data ├── Naglowek.ts # Document header ├── Rozliczenie.ts # Settlement └── Stopka.ts # Footer src/shared/generators/common/ ├── functions.ts # Shared formatting functions └── [Additional utilities] ``` -------------------------------- ### Generate Settlement/Tax Calculation (Rozliczenie) Source: https://github.com/cirfmf/ksef-pdf-generator/blob/main/_autodocs/07-generator-architecture.md Generates the settlement and tax calculation section, detailing tax base amounts by rate, tax amounts, and currency information. Requires settlement data and the currency code. ```typescript export function generateRozliczenie( rozliczenie: Rozliczenie | undefined, currency: string ): Content[] ``` -------------------------------- ### generateStyle() Source: https://github.com/cirfmf/ksef-pdf-generator/blob/main/_autodocs/00-index.md Retrieves the PDF styling configuration. Returns a Partial object. ```APIDOC ## generateStyle() ### Description Retrieves the PDF styling configuration. Returns a Partial object. ### Signature `generateStyle() → Partial` ### Returns - `Partial`: An object containing the PDF styling configuration. ``` -------------------------------- ### Generate QR Code Element Source: https://github.com/cirfmf/ksef-pdf-generator/blob/main/_autodocs/03-api-reference-utilities.md Creates a QR code content element for embedding in a PDF. Pass the data string to be encoded. The result is a ContentQr object with default styling. ```typescript import { generateQRCode } from '@akmf/ksef-fe-invoice-converter'; const qr = generateQRCode('https://example.com/invoice/123'); // Result: { qr: 'https://...', fit: 150, foreground: 'black', background: 'white', eccLevel: 'M' } ``` -------------------------------- ### Error Handling: Specific Error Checks Source: https://github.com/cirfmf/ksef-pdf-generator/blob/main/_autodocs/README.md Implement try-catch blocks to handle potential errors during PDF generation. Specifically check for known error messages like 'Unknown XML Version' to manage unsupported formats. ```typescript try { const pdf = await generateInvoice(file, config); } catch (error) { if (error.message.startsWith('Unknown XML Version')) { // Handle unsupported format } // Handle other errors } ``` -------------------------------- ### generateColumns Source: https://github.com/cirfmf/ksef-pdf-generator/blob/main/_autodocs/03-api-reference-utilities.md Creates an equal-width multi-column layout for PDF content. It accepts an array of column contents and an optional style object for customization. ```APIDOC ## generateColumns ### Description Creates equal-width multi-column layout. ### Signature ```typescript export function generateColumns( contents: Content[][], style?: Style | undefined ): Content ``` ### Parameters #### Path Parameters - **contents** (Content[][]) - Required - Array of column content arrays - **style** (Style) - Optional - Custom style (defaults to columnGap: 20) ### Return Type Content — Multi-column layout ``` -------------------------------- ### generateInvoice() Source: https://github.com/cirfmf/ksef-pdf-generator/blob/main/_autodocs/00-index.md Auto-detects the format of the input file and generates an invoice PDF. It returns the generated PDF as a Blob or a string. ```APIDOC ## generateInvoice() ### Description Auto-detects the format of the input file and generates an invoice PDF. It returns the generated PDF as a Blob or a string. ### Signature `generateInvoice(file, config, format?) → Promise` ### Parameters - **file**: The input file to process. - **config**: Configuration object for PDF generation. - **format?**: Optional format for the PDF. ### Returns - `Promise`: A Promise that resolves with the generated PDF as a Blob or a string. ``` -------------------------------- ### generateNaglowekUPO() Source: https://github.com/cirfmf/ksef-pdf-generator/blob/main/_autodocs/00-index.md Generates the header section for a UPO document using the provided data. Returns a Content object. ```APIDOC ## generateNaglowekUPO() ### Description Generates the header section for a UPO document using the provided data. Returns a Content object. ### Signature `generateNaglowekUPO(data) → Content` ### Parameters - **data**: The data to use for generating the UPO header. ### Returns - `Content`: An object representing the UPO header content. ``` -------------------------------- ### Create PDF Content Elements Source: https://github.com/cirfmf/ksef-pdf-generator/blob/main/_autodocs/06-quick-reference.md Generate various PDF content elements including label-value pairs, section headers, and QR codes using provided utility functions. ```typescript import { createLabelText, createSection, createHeader, generateQRCode } from '@akmf/ksef-fe-invoice-converter'; // Create label-value pair const content = createLabelText('Name: ', 'John Doe', FormatTyp.Value); // Create header const header = createHeader('Invoice Details'); // Create QR code const qr = generateQRCode('https://example.com/invoice'); ``` -------------------------------- ### Generate Invoice PDF Source: https://github.com/cirfmf/ksef-pdf-generator/blob/main/_autodocs/00-index.md Use the generateInvoice function to create a PDF from an XML file. Ensure the necessary import is included. ```typescript import { generateInvoice } from '@akmf/ksef-fe-invoice-converter'; const pdf = await generateInvoice(file, config, 'blob'); ``` -------------------------------- ### generateDokumentUPO() Source: https://github.com/cirfmf/ksef-pdf-generator/blob/main/_autodocs/00-index.md Generates the document records section for a UPO document using the provided data. Returns a Content object. ```APIDOC ## generateDokumentUPO() ### Description Generates the document records section for a UPO document using the provided data. Returns a Content object. ### Signature `generateDokumentUPO(data) → Content` ### Parameters - **data**: The data to use for generating the UPO document records. ### Returns - `Content`: An object representing the UPO document records content. ``` -------------------------------- ### generateInvoice Source: https://github.com/cirfmf/ksef-pdf-generator/blob/main/_autodocs/01-api-reference-main.md Generates a PDF visualization of an invoice from an XML file. It supports multiple invoice formats and can return the PDF as a Blob or a Base64 encoded string. ```APIDOC ## generateInvoice ### Description Generates PDF visualization of an invoice from XML file. Supports invoice formats FA(1), FA(2), FA(3), and FA_RR(1). Automatically detects format version from XML and applies appropriate styling and layout. ### Method POST ### Endpoint /generateInvoice ### Parameters #### Path Parameters None #### Query Parameters * **formatType** (string) - Optional - Output format: 'blob' for binary PDF, 'base64' for base64-encoded string. Defaults to 'blob'. #### Request Body * **file** (File) - Required - XML file containing invoice data. Must conform to one of the supported KSeF schema versions (FA(1), FA(2), FA(3), or FA_RR(1)) * **additionalData** (object) - Required - Metadata including KSeF number, QR codes, watermark text, and mobile display flag - **nrKSeF** (string) - Required - KSeF number - **qrCode** (string) - Required - QR code URL - **isMobile** (boolean) - Required - Flag indicating mobile display - **watermark** (string) - Optional - Watermark text ### Request Example ```json { "file": "...", "additionalData": { "nrKSeF": "1234567890", "qrCode": "https://example.com/invoice", "isMobile": false, "watermark": "ORIGINAL" }, "formatType": "blob" } ``` ### Response #### Success Response (200) * **pdfOutput** (Blob | string) - The generated PDF, either as a binary Blob or a Base64 encoded string, depending on the `formatType` parameter. #### Response Example *Blob Output* ``` [Binary PDF Data] ``` *Base64 Output* ```json "JVBERi0xLjQKJeLjz9MNCjEgMCBvYmo..." ``` ### Throws * **Error** - If XML version is unknown (kodSystemowy attribute not recognized). * **Error** - If XML parsing fails during FileReader processing. ``` -------------------------------- ### createSubHeader Source: https://github.com/cirfmf/ksef-pdf-generator/blob/main/_autodocs/03-api-reference-utilities.md Creates a sub-header with a smaller font size than the main header, suitable for secondary titles. ```APIDOC ## createSubHeader ### Description Creates sub-header with smaller font than main header. ### Signature ```typescript export function createSubHeader( text: string, margin?: Margins ): Content[] ``` ### Parameters #### Parameters - **text** (string) - Required - Sub-header text - **margin** (Margins) - Optional - Top, right, bottom, left margins ### Return Type Content[] — Sub-header element with SubHeaderContent style ``` -------------------------------- ### Generate Document Header (Naglowek) Source: https://github.com/cirfmf/ksef-pdf-generator/blob/main/_autodocs/07-generator-architecture.md Generates the document header, including document type, version, issue date, KSeF number, QR codes, and seller information. Requires invoice core data, additional metadata, and optionally attachment data. ```typescript export function generateNaglowek( fa: Fa | undefined, additionalData: AdditionalDataTypes, zalacznik?: Zalacznik ): Content[] ``` -------------------------------- ### Generate Two-Column Layout Source: https://github.com/cirfmf/ksef-pdf-generator/blob/main/_autodocs/03-api-reference-utilities.md Creates a two-column layout for PDF content. Optional margins and unbreakable settings can be applied. ```typescript export function generateTwoColumns( kol1: Column, kol2: Column, margin?: Margins, unbreakable?: boolean ): Content ``` -------------------------------- ### generateDokumentUPO Source: https://github.com/cirfmf/ksef-pdf-generator/blob/main/_autodocs/01-api-reference-main.md Generates the document and records section for a Uniform Proof of Delivery (UPO). This function creates a detailed table containing delivery records, confirmations, and their status information. ```APIDOC ## generateDokumentUPO ### Description Generates document/records section for UPO. Creates detailed table with delivery records, confirmations, and status information. ### Method ```typescript export function generateDokumentUPO( potwierdzenie: Potwierdzenie ): Content ``` ### Parameters #### Path Parameters - **potwierdzenie** (Potwierdzenie) - Required - UPO data with document records ### Return Type Content — PDF content element for document table and records ``` -------------------------------- ### PDF Utility Functions Source: https://github.com/cirfmf/ksef-pdf-generator/blob/main/_autodocs/07-generator-architecture.md Core functions for PDF generation, covering text formatting, table generation, layout, styling, data extraction, and special utilities like QR code generation. ```typescript // Text formatting formatText(value, format, options, currency) createLabelText(label, value, format, style) createSection(content, isLineOnTop, margin) // Tables generateTable(array, keys) getContentTable(headers, data, defaultWidths, margin, wordBreak) // Layout generateTwoColumns(col1, col2, margin, unbreakable) generateColumns(contents, style) // Styling generateStyle() generateLine() createHeader(text) // Data extraction getValue(value) hasValue(value) getNumber(value) getNumberRounded(value) // Formatting normalizeCurrencySeparator(value) addThousandSeparator(value) formatBankAccountNumber(number) // Special generateQRCode(qrCode) getTStawkaPodatku(code, version, P_PMarzy) getKraj(code) ``` -------------------------------- ### Generate Invoice - Returns Blob Source: https://github.com/cirfmf/ksef-pdf-generator/blob/main/_autodocs/01-api-reference-main.md This overload generates a PDF visualization of an invoice and returns it as a Blob. It supports multiple invoice formats and automatically detects the version from the XML. ```typescript export async function generateInvoice( file: File, additionalData: AdditionalDataTypes, formatType: 'blob' ): Promise ``` -------------------------------- ### i18nReady Source: https://github.com/cirfmf/ksef-pdf-generator/blob/main/_autodocs/03-api-reference-utilities.md A promise that resolves when the i18next internationalization (i18n) system is fully initialized and ready for use. This ensures translations are available before they are accessed. ```APIDOC ## i18nReady ### Description A promise that resolves when the i18next internationalization (i18n) system is initialized and ready for use. This is crucial for ensuring that translation resources are loaded and accessible before attempting to use them. ### Declaration ```typescript export const i18nReady: Promise ``` ### Example ```typescript import { i18nReady } from '@akmf/ksef-fe-invoice-converter'; // Wait for i18n before using translations await i18nReady; i18n.t('invoice.footer.pagesTotal'); // Translations now available ``` ### Initialization - Languages: Polish (pl) and English (en). - Default language: Polish. - Resources loaded from JSON files in `src/lib-public/i18n/lang/`. ``` -------------------------------- ### Generate Invoice Details (Szczegoly) Source: https://github.com/cirfmf/ksef-pdf-generator/blob/main/_autodocs/07-generator-architecture.md Generates the invoice metadata section, including invoice number, date, period, and document type. Requires the core invoice data. ```typescript export function generateSzczegoly(fa: Fa): Content[] ``` -------------------------------- ### Generate Invoice - Default (Blob) Source: https://github.com/cirfmf/ksef-pdf-generator/blob/main/_autodocs/01-api-reference-main.md This overload generates a PDF visualization of an invoice and returns it as a Blob by default. It supports multiple invoice formats and automatically detects the version from the XML. ```typescript export async function generateInvoice( file: File, additionalData: AdditionalDataTypes, formatType?: FormatType = 'blob' ): Promise ``` -------------------------------- ### Registering PDFMake Fonts Source: https://github.com/cirfmf/ksef-pdf-generator/blob/main/_autodocs/04-configuration.md Automatically registers the Roboto font for PDF generation using pdfmake's virtual file system. Ensure pdfmake/build/vfs_fonts is imported. ```typescript import pdfFonts from 'pdfmake/build/vfs_fonts'; pdfMake.addVirtualFileSystem(pdfFonts); ``` -------------------------------- ### createLabelText Source: https://github.com/cirfmf/ksef-pdf-generator/blob/main/_autodocs/03-api-reference-utilities.md Creates a PDF content array with a label and its formatted value. It allows for custom formatting types and styles. ```APIDOC ## createLabelText ### Description Creates PDF content array with label and formatted value pair. ### Signature ```typescript export function createLabelText( label: string, value: FP | string | number | undefined | null, formatTyp: FormatTyp | FormatTyp[] = FormatTyp.Value, style: Style = {} ): Content[] ``` ### Parameters #### Parameters - **label** (string) - Required - Label text - **value** (FP | string | number | undefined | null) - Required - Value to display - **formatTyp** (FormatTyp | FormatTyp[]) - Optional - Default: FormatTyp.Value - Format style(s) - **style** (Style) - Optional - Default: {} - Additional pdfmake style ### Return Type Content[] — Array with single content element or empty array if value missing ### Example ```typescript import { createLabelText, FormatTyp } from '@akmf/ksef-fe-invoice-converter'; const content = createLabelText( 'Invoice Number: ', 'FA/2024/001', FormatTyp.Value ); const currencyContent = createLabelText( 'Total: ', '1234.56', FormatTyp.Currency ); ``` ``` -------------------------------- ### createSection Source: https://github.com/cirfmf/ksef-pdf-generator/blob/main/_autodocs/03-api-reference-utilities.md Generates a PDF section with an optional top border and configurable margins for layout control. ```APIDOC ## createSection ### Description Creates PDF section with optional top border and configurable margins. ### Signature ```typescript export function createSection( content: Content[], isLineOnTop: boolean, margin?: Margins ): Content[] ``` ### Parameters #### Parameters - **content** (Content[]) - Required - Content elements to wrap - **isLineOnTop** (boolean) - Required - If true, add horizontal line above content - **margin** (Margins) - Optional - Default: [0,0,0,8] - Top, right, bottom, left margins ### Return Type Content[] — Wrapped content with optional border ``` -------------------------------- ### Check Supported XML Format Version Source: https://github.com/cirfmf/ksef-pdf-generator/blob/main/_autodocs/06-quick-reference.md Validate the XML format version against a list of supported versions. Throw an error if the format is unsupported. ```typescript const version = xmlData.Faktura?.Naglowek?.KodFormularza?._attributes?.kodSystemowy; if (!['FA (1)', 'FA (2)', 'FA (3)', 'FA_RR (1)', 'FA_RR(1)'].includes(version)) { throw new Error(`Unsupported format: ${version}`); } ``` -------------------------------- ### generateFA2 Source: https://github.com/cirfmf/ksef-pdf-generator/blob/main/_autodocs/01-api-reference-main.md Generates a PDF visualization for invoice format FA(2). It constructs a comprehensive invoice layout including all standard sections. ```APIDOC ## generateFA2 ### Description Generates PDF visualization for invoice format FA(2). Creates complete invoice layout with header, parties, details, items, tax summary, notes, additional information, settlement, and payment sections. ### Method export function ### Signature generateFA2(invoice: Faktura, additionalData: AdditionalDataTypes): TCreatedPdf ### Parameters #### Path Parameters - **invoice** (Faktura) - Required - Parsed FA(2) invoice data structure - **additionalData** (AdditionalDataTypes) - Required - Additional metadata: KSeF number, QR codes, watermark, mobile flag ### Return Type TCreatedPdf — PDFMake document object ### Example ```typescript import { generateFA2 } from '@akmf/ksef-fe-invoice-converter'; const pdf = generateFA2(invoiceData, additionalData); const base64 = pdf.getBase64(); ``` ``` -------------------------------- ### Generate Order References (Zamowienie) Source: https://github.com/cirfmf/ksef-pdf-generator/blob/main/_autodocs/07-generator-architecture.md Generates the section for order references and related document numbers. ```typescript export function generateZamowienie(fa: Fa): Content[] ```