DEV Community

SpellzCode
SpellzCode

Posted on Edited on

Invoice attachments to spreadsheet rows in n8n, scans included (and why DOCX and XLSX need no library)

Most "read the invoice" automations break on the same three things: the PDF is a scan with no text in it, the supplier sent a Word or Excel file instead, or the layout changed and the regex died. This post walks through a small n8n workflow that survives all three, then opens the hood on the two parts that are easier than they look: reading office files, and getting page images out of a scanned PDF.

Disclosure: I work on the tool used in the examples (it is made by SpellzCode). The techniques in the second half work without it, and I say where it stops working.

The workflow

Three nodes:

  1. Gmail Trigger, with Download Attachments on and a search such as has:attachment (invoice OR faktura OR rechnung).
  2. Agent Data Tools > Document > Extract Fields (community node n8n-nodes-agent-data-tools), with File Source set to File From an Earlier Node, Input Binary Field attachment_0, and the fields you want:
   supplier, invoice_number, invoice_date, due_date, customer, net_amount, vat_amount, total, currency, bankgiro, ocr_number, org_number
Enter fullscreen mode Exit fullscreen mode
  1. Google Sheets > Append Row, mapping {{ $json.data.supplier }} and the other fields to columns.

The middle node sends the file and the field names in one request and gets one JSON object back. For a Swedish invoice it looks like this:

{
  "type": "pdf",
  "ocr": true,
  "data": {
    "supplier": "Bergslagen Bygg & Trä AB",
    "invoice_number": "58231",
    "invoice_date": "2026-10-28",
    "due_date": "2026-11-27",
    "customer": "Östra Hamnens Café HB",
    "net_amount": 17330,
    "vat_amount": 4332.5,
    "total": 21662.5,
    "currency": "SEK",
    "bankgiro": "712-4589",
    "ocr_number": "5823100047",
    "org_number": "556712-3344"
  },
  "missing": [],
  "truncated": false
}
Enter fullscreen mode Exit fullscreen mode

Two details matter more than they seem:

  • A field that is not in the document comes back as null and is listed under missing. Map missing to a column and you have a review queue for free. A tool that always returns something for every field will eventually pay the wrong invoice.
  • Amounts come back as numbers: 21 662,50 on the paper became 21662.5 in the answer.

Without n8n it is one HTTP request with the file as the body:

curl -H "Authorization: Bearer $API_KEY" \
     -H "Content-Type: application/octet-stream" \
     --data-binary @invoice.pdf \
     "https://tools.funwords.eu/document/extract?fields=supplier,invoice_number,due_date,total,currency"
Enter fullscreen mode Exit fullscreen mode

What I tested, and what I did not

I ran that invoice (a made-up one, rendered as an image) through in four forms: a clean PNG, a clean JPEG, a scanned PDF (one JPEG per page, no text layer), and a deliberately bad "scan": rotated 2.6 degrees, 900 pixels wide, low contrast, speckled, JPEG quality 38, with a fold line across the totals. All four returned all twelve fields, the answer shown above. A second invoice, as a PDF with a text layer, returned the eleven fields it stated and null for the IBAN it did not have. Calls that needed OCR took 10 to 40 seconds; text-layer files are much quicker.

What that does not prove: those were renderings of two invoices I wrote myself, not a pile of real supplier scans. I have not tested handwriting, stamps over the totals, or multi-page scans beyond three pages (three is the limit per call). An AI model reads the file, so treat amounts as "check before paying", not as ground truth. That is what the missing column and a human glance are for.

Under the hood 1: DOCX, XLSX and PPTX are ZIP files of XML

You do not need a library to read modern office files, only an unzip and an XML parser. Rename report.docx to report.zip and look inside:

  • Word: word/document.xml. Paragraphs are <w:p>, text runs are <w:t>, a tab is <w:tab/>, a line break <w:br/>. The paragraph style is in <w:pStyle w:val="Heading1"/>, which is all you need to emit # headings. A list item has a <w:numPr> inside its paragraph properties. Tables are <w:tbl> / <w:tr> / <w:tc>, and a cell holds ordinary paragraphs.
  • Excel: xl/workbook.xml lists the sheets, xl/_rels/workbook.xml.rels maps each to a file, and xl/sharedStrings.xml holds every distinct string once. A cell <c r="B2" t="s"><v>17</v></c> means "string number 17". Without t="s" the value is the number itself. Two traps: empty cells are simply absent, so place each cell by its reference (B2), not by counting; and dates are stored as day numbers (45,000-something), which only the cell style tells you.
  • PowerPoint: ppt/slides/slide1.xml, slide2.xml, … with text in <a:t> inside <a:p>. Sort the slides by number, not by file name, or slide 10 lands before slide 2.

Things that will bite you in production:

  • Deleted text is still in the file when change tracking is on (<w:del> / <w:delText>). Skip it, or your "extracted text" contains what the author removed.
  • Zip bombs. A 40 KB archive can declare a part that inflates to gigabytes. Never trust the size in the header: stop reading a part when it passes your own limit.
  • Old .doc, .xls, .ppt are a different, binary format (they start with the bytes D0 CF 11 E0). Detect them and say so, instead of returning garbage.

In a serverless runtime the unzip needs no dependency either: read the central directory at the end of the file, then inflate each entry with the platform's DecompressionStream("deflate-raw").

Under the hood 2: a scanned PDF usually contains its pages as plain JPEGs

OCR normally starts with "render the PDF page to an image", which needs a PDF renderer, which is exactly what you do not have in an edge function. But a scanner does not draw a page. It takes a photo, compresses it as a JPEG, and stores those JPEG bytes in the PDF unchanged, marked with the filter name /DCTDecode:

4 0 obj
<< /Type /XObject /Subtype /Image /Width 1240 /Height 1754
   /ColorSpace /DeviceRGB /BitsPerComponent 8 /Filter /DCTDecode /Length 105626 >>
stream
ÿØÿà..JFIF...            <- an ordinary JPEG starts here
endstream
Enter fullscreen mode Exit fullscreen mode

So for the common case there is nothing to render: find /DCTDecode, jump to stream, check that the data starts with FF D8 FF, and cut at endstream. What you hold is the page image, ready for any OCR or vision model. Skip tiny images (logos and stamps). This does not work for scans stored with fax compression (CCITT, JBIG2); those really do need decoding, and it is fair to refuse them with a clear message.

One trap worth knowing: PDF.js takes ownership of the buffer you give it. If you first try the text layer and then go looking for images in the same buffer, the buffer is empty. Hand the parser a copy.

When you should not use this

  • You process thousands of invoices from the same few suppliers and need line items with guaranteed accuracy: a template-based extractor or your accounting system's own import will beat a general model.
  • The documents are confidential enough that they may not leave your network: run the open-source route (the ZIP and JPEG tricks above, plus a local OCR) instead of any hosted API.
  • You need more than three pages of a scan read in one call, or files above 10 MB.

Try it

  • n8n: install the community node n8n-nodes-agent-data-tools and add Document > Extract Fields or Convert to Text. A ready workflow file is in the repository.
  • HTTP: the tool pages with inputs, prices and a sample answer are document/extract and document/text. Extraction costs $0.03 a document and text conversion $0.005; a failed call is not charged.

If you build the unzip-and-parse route yourself and hit a file that breaks it, I would like to hear which one.

Top comments (0)