Skip to content

PDF API (dte-sdk/pdf)

The printed samples: the PDF417 stamp and the PDF as the SII manual asks. Node only, because the batch functions read and write files. For how to produce and review the samples, see Printed samples.

TypeScript
import { parsePrintableDocuments, renderPrintedSample } from 'dte-sdk/pdf'

Peer dependencies#

pdf-lib (^1.17.1) and bwip-js (^4.11.4) are optional peer dependencies. Install them in your project; the SDK loads them on first use, not at import. Without them, the render functions throw DEPENDENCY_UNAVAILABLE. A failure inside the PDF library while drawing is PDF_RENDER_FAILED.

Shell
npm install pdf-lib bwip-js

The printed samples have not been reviewed by the SII yet. They are tested against synthetic data. See Status.

The functions that read or write files take a trailing load parameter that exists only so the SDK's own tests can replace node:fs; it is left out of the signatures below.

Parsing#

Turns any EnvioDTE, EnvioBOLETA, bare SetDTE or bare DTE XML into printable documents, with each TED copied verbatim.

TypeScript
// The printable documents of an XML: an `EnvioDTE`, `EnvioDTEB`, `EnvioDTETraslado` or
// `EnvioBOLETA` envelope, a bare `SetDTE`, or a bare `DTE` (what `SignedDocument.xml` holds). Any
// other root yields an empty list.
function parsePrintableDocuments(xml: string): readonly PrintableDocument[]
TypeDescription
PrintableAdjustmentA global discount or surcharge.
PrintableDocumentWhat the printed sample needs of a document, parsed from its XML. Strings are empty and numbers undefined when the tag is absent.
PrintableIssuerThe issuer of the printed document.
PrintableItemA detail line.
PrintablePartyA party of the printed document, as written in the XML.
PrintableReferenceA reference to another document.
PrintableTotalsThe totals that print; absent ones are undefined.

Fields of PrintableAdjustment

FieldTypeDescription
kind'D' | 'R'D discount or R surcharge.
valueType'%' | '$'% or $.
value?numberValue in that unit.

Fields of PrintableDocument

FieldTypeDescription
typenumberDocument type; TD of the TED when IdDoc lacks it; 0 when neither has it.
foliostringFolio; F of the TED as fallback.
issueDatestringIssue date as written (YYYY-MM-DD); FE of the TED as fallback.
transferReasonnumber | nullTransfer reason of a dispatch guide, null when absent.
grossAmountsbooleanLine amounts include VAT.
issuerPrintableIssuerThe issuer, with its branch.
receiverPrintablePartyThe receiver.
totalsPrintableTotalsThe five totals that print.
globalAdjustmentsreadonly PrintableAdjustment[]Global discounts and surcharges.
itemsreadonly PrintableItem[]Detail lines.
referencesreadonly PrintableReference[]References to other documents.
tedXmlstringThe <TED>…</TED> substring of the input, verbatim; empty when none.

Fields of PrintableIssuer

FieldTypeDescription
rutstringRUT as written.
namestringLegal name.
activitystringLine of business.
addressstringStreet address.
communestringCommune.
branchstringBranch, empty when none.

Fields of PrintableItem

FieldTypeDescription
codestringItem code (the first when there are several).
namestringItem name.
quantity?numberQuantity.
unit?stringUnit of measure.
unitPrice?numberUnit price.
amount?numberLine amount.
discountAmount?numberLine discount amount.
discountPercent?numberLine discount percent.

Fields of PrintableParty

FieldTypeDescription
rutstringRUT as written.
namestringLegal name.
activitystringLine of business.
addressstringStreet address.
communestringCommune.

Fields of PrintableReference

FieldTypeDescription
documentTypestringReferenced document type, as written (SET and non-DTE codes included).
foliostringReferenced folio.
datestringReferenced date.
reasonstringReason.

Fields of PrintableTotals

FieldTypeDescription
net?numberNet amount.
exempt?numberExempt amount.
vat?numberVAT.
vatRate?numberVAT rate.
total?numberTotal.

Rendering#

One single-page PDF per document, and the PDF417 stamp alone as a PNG. RenderPrintedSampleOptions adds transferable to the options shared by every sample.

TypeScript
// The PDF417 stamp of a TED as a PNG: error correction level 5, the TED bytes exactly as they were
// signed. The renderer embeds it under the totals; callers with a layout of their own use it
// directly.
function renderTedBarcode(tedXml: string): Promise<Uint8Array>
 
// True when the printed document carries a transferable copy: 33, 34, 43 and 46 always; 52 only
// when the transfer is a sale (reason 1 or 9, 1 assumed when absent), as the manual excludes
// transfers that are not sales; never for notes or receipts.
function needsTransferableCopy(doc: PrintableDocument): boolean
 
// The printed sample of one document as a single-page PDF per the SII printed-samples manual:
// issuer and the red type box, issue date, receiver, transfer reason (guides), references, detail,
// totals, the acknowledgement box and the `CEDIBLE` mark on a transferable copy, and the PDF417
// stamp with its legends.
function renderPrintedSample(
  doc: PrintableDocument,
  options?: RenderPrintedSampleOptions,
): Promise<Uint8Array>
TypeDescription
PrintedLogoA logo for the top left of the sample.
PrintedSampleOptionsOptions shared by every printed sample.
RenderPrintedSampleOptionsOptions of renderPrintedSample.

Fields of PrintedLogo

FieldTypeDescription
bytesUint8ArrayPNG or JPEG bytes.
format'png' | 'jpeg'Image format.

Fields of PrintedSampleOptions

FieldTypeDescription
siiOffice?stringSII office under the type box; default the office of the issuer's commune (CmnaOrigen), by siiOfficeForCommune, or S.I.I. - SANTIAGO CENTRO when the table lacks the commune.
resolution?stringResolution line under the stamp; default Res. Ex. SII N° 0 del {year}.
logo?PrintedLogoLogo at the top left; one the library cannot embed is ignored.
now?() => DateClock for the year of the default resolution.

Fields of RenderPrintedSampleOptions

FieldTypeDescription
siiOffice?stringSII office under the type box; default the office of the issuer's commune (CmnaOrigen), by siiOfficeForCommune, or S.I.I. - SANTIAGO CENTRO when the table lacks the commune.
resolution?stringResolution line under the stamp; default Res. Ex. SII N° 0 del {year}.
logo?PrintedLogoLogo at the top left; one the library cannot embed is ignored.
now?() => DateClock for the year of the default resolution.
transferable?booleanDraw the transferable copy (acknowledgement box and CEDIBLE mark) when the document admits one; default false.

SII offices#

The table behind the default siiOffice: the office of each commune, keyed by the legend printed under the type box. Both exports are pure and need neither pdf-lib nor bwip-js.

TypeScript
import { SII_OFFICES, siiOfficeForCommune } from 'dte-sdk/pdf'
 
siiOfficeForCommune(' ÑUÑOA ') // 'S.I.I. - ÑUÑOA'
siiOfficeForCommune('Nunoa') // 'S.I.I. - ÑUÑOA'
siiOfficeForCommune('Atlantis') // null
TypeScript
// The SII office of each commune: 355 commune names in 40 offices, every official commune included.
// Keys are the legend printed under the type box (`S.I.I. - {office}`); values are the communes
// that office serves, in lowercase, without accents and with single spaces.
const SII_OFFICES: Readonly<Record<string, readonly string[]>>
 
// The legend for a commune (the issuer's `CmnaOrigen`), or null when the table does not have it.
// Case, surrounding spaces and accents are ignored.
function siiOfficeForCommune(commune: string): string | null

The printed samples use it when siiOffice is not given: they print siiOfficeForCommune(issuer.commune), and S.I.I. - SANTIAGO CENTRO only for a commune the table lacks.

Batches in memory#

Renders every document of every envelope in memory, into the test and simulation sets. Failures are reported as data and the batch goes on.

TypeScript
// Renders every document of every envelope, in memory: one sample per document and, with
// `transferable`, a second one for each document that admits a transferable copy.
function renderPrintedSamples(input: PrintedSamplesInput): Promise<PrintedSamplesResult>
TypeDescription
PrintedEnvelopeAn envelope to print: a name (the file name, the artefact key) and its XML.
PrintedSampleOne rendered sample.
PrintedSampleFailureOne envelope or document that could not be rendered.
PrintedSampleFileA sample file as the certification uploads it: its base name and its bytes.
PrintedSampleSetThe two sets of printed samples the certification asks for. Defined as 'tests' | 'simulation'.
PrintedSamplesInputInput of renderPrintedSamples.
PrintedSamplesResultResult of renderPrintedSamples.

Fields of PrintedEnvelope

FieldTypeDescription
namestringName; it decides the set.
xmlstringThe envelope XML.

Fields of PrintedSample

FieldTypeDescription
namestringmuestra_{type}_{folio}.pdf, with _cedible before the extension on a transferable copy.
setPrintedSampleSetThe set the sample belongs to.
sourcestringThe envelope name.
typenumberDocument type.
foliostringFolio.
transferablebooleanTrue on the transferable copy.
bytesUint8ArrayThe PDF bytes.

Fields of PrintedSampleFailure

FieldTypeDescription
sourcestringThe envelope name.
type?numberAbsent when the envelope itself failed to parse.
folio?stringFolio of the document that failed.
transferable?booleanTrue when the transferable copy failed.
code?DteErrorCodeThe DteError code, when it was one.
reasonstringThe error message.

Fields of PrintedSampleFile

FieldTypeDescription
fileNamestringThe file name, [A-Za-z0-9_.-]+.pdf.
bytesUint8ArrayThe PDF bytes.

Fields of PrintedSamplesInput

FieldTypeDescription
envelopesreadonly PrintedEnvelope[]The envelopes to render, each with a name.
options?PrintedSampleOptionsRendering options shared by every sample.
transferable?booleanAlso produce the transferable copy of every document that admits one; default false.

Fields of PrintedSamplesResult

FieldTypeDescription
successbooleanTrue when nothing failed.
samplesreadonly PrintedSample[]The samples rendered.
failuresreadonly PrintedSampleFailure[]The envelopes and documents that failed.
documentsnumberDocuments parsed.
testsnumberSamples in the test set.
simulationnumberSamples in the simulation set.

Files#

The same batch over files: find the envelope files, write the PDFs under SET-PRUEBAS and SET-SIMULACION, and read them back for the upload to the samples portal (uploadPrintedSamples in dte-sdk/portal).

TypeScript
// The envelope files under a path: the file itself, or every `.xml` under a directory
// (recursively) whose name contains `envio-set-`, `envio-simulacion` or `envioboleta`, so the
// responses and receipt envelopes of the exchange, which carry no DTE, are skipped.
function findEnvelopeFiles(inputPath: string): Promise<readonly string[]>
 
// Every `.pdf` under a directory, recursively, in name order at every level, so the test set's
// folder (`SET-PRUEBAS`) comes before the simulation's (`SET-SIMULACION`) as `writePrintedSamples`
// lays them out; each with its base name and its bytes, ready for the printed samples step.
function readPrintedSamples(dir: string): Promise<readonly PrintedSampleFile[]>
 
// Renders the samples of every file into `{outDir}/SET-PRUEBAS` and `{outDir}/SET-SIMULACION`, one
// PDF per sample under its sample name.
function writePrintedSamples(input: WritePrintedSamplesInput): Promise<WritePrintedSamplesResult>
TypeDescription
WritePrintedSamplesInputInput of writePrintedSamples.
WritePrintedSamplesResultResult of writePrintedSamples.
WrittenPrintedSampleA sample written to disk.

Fields of WritePrintedSamplesInput

FieldTypeDescription
xmlFilesreadonly string[]Envelope XML files.
outDirstringOutput directory; SET-PRUEBAS and SET-SIMULACION are created inside it.
options?PrintedSampleOptionsRendering options shared by every sample.
logoPath?stringLogo file, read once; replaces options.logo. A missing file or an extension other than png, jpg or jpeg means no logo.
transferable?booleanAlso write the transferable copies; default false.

Fields of WritePrintedSamplesResult

FieldTypeDescription
documentsnumberDocuments parsed.
simulationnumberSamples in the simulation set.
testsnumberSamples in the test set.
successbooleanTrue when nothing failed.
failuresreadonly PrintedSampleFailure[]The envelopes and documents that failed.
samplesreadonly WrittenPrintedSample[]The samples written, with path and size.

Fields of WrittenPrintedSample

FieldTypeDescription
foliostringFolio.
typenumberDocument type.
namestringmuestra_{type}_{folio}.pdf, with _cedible before the extension on a transferable copy.
setPrintedSampleSetThe set the sample belongs to.
sourcestringThe envelope name.
transferablebooleanTrue on the transferable copy.
pathstringPath of the PDF.
sizenumberSize in bytes.