Turn an Emailed Supplier Invoice into a Shopify Draft-Order Payload
Take the PDF invoice out of a supplier's email, read the shipping address separately from the line items, and map item codes, quantities and prices to the JSON for a Shopify draft order, leaving a missing item code blank.
A supplier emails an invoice as a PDF attachment, and someone retypes it into Shopify: the address the goods go to, then each line with its item code and quantity. Retyping is slow and it's where the errors come in, such as a quantity on the wrong line or the billing address used as the shipping address.
This notebook turns the email into the JSON an order script sends to Shopify, with PyMuPDF and the Python standard library:
- Take the PDF invoice out of the email.
- Read the shipping address from the
SHIP TObox only, separate from the billing address and the line items. - Read the line items from the invoice table, and map each column to a field of the order script's JSON. A line with no item code gets a blank
sku: no code is guessed. - Build the draft-order payload and save it as JSON.
- Check the payload against the invoice: every line is there, and the line totals add up to the invoice subtotal.
Tested with PyMuPDF 2.2.
%pip install -q pymupdf[notice] A new release of pip is available: 26.0.1 -> 26.3 [notice] To update, run: pip install --upgrade pip Note: you may need to restart the kernel to use updated packages.
Sample email
The sample is an .eml file, the format most mail clients use when you save or export a message. It has a short text body and the supplier's invoice as a PDF attachment. The invoice has:
- a
BILL TObox with the shop's own address, and aSHIP TObox with the end customer's address, side by side; - a line-item table, with one description long enough to wrap onto a second line and one line where the supplier left the item code blank;
- subtotal, shipping, VAT and total lines below the table, which are not line items.
To use your own email, set email_path and skip the cell's sample-making code.
from email.message import EmailMessage
import pymupdf
ITEMS = [
("KH-1042", "Linen cushion cover, 45 x 45 cm, sage", 6, 12.50),
("KH-2210", "Stoneware mug, speckled white", 12, 6.75),
("", "Oak serving board with leather hanging strap, large", 2, 34.00), # no item code
("KH-3305", "Wool throw, charcoal", 3, 48.00),
("KH-0871", "Beeswax candle, set of 3", 10, 9.20),
]
def right(page, x, y, text, font="helv", size=9):
"""Write text with its right edge at x and its baseline at y."""
page.insert_text((x - pymupdf.get_text_length(text, font, size), y), text, fontsize=size, fontname=font)
def make_invoice(path):
doc = pymupdf.open()
page = doc.new_page() # A4 portrait
page.insert_text((50, 60), "Grassland Supplies Ltd", fontname="hebo", fontsize=16)
page.insert_text((50, 76), "1 Udderly Way, Cowbury ZZ99 3CC | VAT GB 000 0000 00", fontsize=8)
page.insert_text((400, 60), "INVOICE", fontname="hebo", fontsize=16)
page.insert_text((400, 78), "Invoice No: SI-4471", fontsize=10)
page.insert_text((400, 92), "Date: 2026-12-02", fontsize=10)
page.insert_text((400, 106), "Your PO: PO-0098", fontsize=10)
boxes = {
"BILL TO": (50, ["The Cowshed Homeware Ltd", "21 Pasture Street", "Lowing-on-the-Wold ZZ99 1AA", "United Kingdom"]),
"SHIP TO": (300, ["Daisy Moofield", "Unit 4, Buttercup Barns", "12 Clover Lane", "Moocaster ZZ99 2BB",
"United Kingdom", "Tel: +44 113 496 0123"]),
}
for label, (x, lines) in boxes.items():
page.draw_rect((x - 6, 128, x + 224, 228), color=(0.7, 0.7, 0.7), width=0.5)
page.insert_text((x, 142), label, fontname="hebo", fontsize=9)
for k, line in enumerate(lines):
page.insert_text((x, 158 + 13 * k), line, fontsize=10)
cols = [50, 120, 330, 380, 460, 545] # column edges
heads = ["Item Code", "Description", "Qty", "Unit Price", "Amount"]
rows = [(code, desc, str(q), f"£{p:,.2f}", f"£{q * p:,.2f}") for code, desc, q, p in ITEMS]
y = 260
heights = [20] + [34 if len(r[1]) > 40 else 20 for r in rows]
for i, cells in enumerate([heads, *rows]):
h = heights[i]
font = "hebo" if i == 0 else "helv"
for j, text in enumerate(cells):
cell = pymupdf.Rect(cols[j], y, cols[j + 1], y + h)
page.draw_rect(cell, color=(0.4, 0.4, 0.4), width=0.5)
if h > 20 and j == 1: # wrapped description
page.insert_textbox(cell + (4, 3, -4, 0), text, fontsize=9, fontname=font)
elif j >= 2: # numbers: right-aligned
right(page, cell.x1 - 7, y + 14, text, font)
else:
page.insert_text((cell.x0 + 4, y + 14), text, fontsize=9, fontname=font)
y += h
subtotal = sum(q * p for _, _, q, p in ITEMS)
shipping, vat = 8.50, round((subtotal + 8.50) * 0.2, 2)
for k, (label, amount) in enumerate([("Subtotal", subtotal), ("Shipping", shipping),
("VAT 20%", vat), ("Total", subtotal + shipping + vat)]):
page.insert_text((380, y + 22 + 15 * k), label, fontname="hebo" if label == "Total" else "helv", fontsize=10)
right(page, 538, y + 22 + 15 * k, f"£{amount:,.2f}", "helv", 10)
page.insert_text((50, 800), "Payment terms: 30 days. Bank: 00-00-00 00000000", fontsize=8)
doc.save(path, garbage=3, deflate=True)
make_invoice("SI-4471.pdf")
msg = EmailMessage()
msg["From"] = "Grassland Supplies <accounts@grassland.example>"
msg["To"] = "orders@the-cowshed.example"
msg["Subject"] = "Invoice SI-4471 for PO-0098"
msg["Date"] = "Wed, 02 Dec 2026 09:14:00 +0000"
msg.set_content("Hello,\n\nPlease find attached invoice SI-4471 for your order PO-0098, "
"shipping direct to your customer.\n\nKind regards,\nMoo-tual Supplies Accounts")
with open("SI-4471.pdf", "rb") as f:
msg.add_attachment(f.read(), maintype="application", subtype="pdf", filename="SI-4471.pdf")
with open("supplier_invoice.eml", "wb") as f:
f.write(msg.as_bytes())
email_path = "supplier_invoice.eml"Step 1: Take the PDF out of the email
Python's email package parses the message. iter_attachments() goes through the attachments, and the first one that is a PDF is opened straight from its bytes with pymupdf.open(stream=...). Nothing has to be saved to disk first.
An attachment is taken to be a PDF if its content type is application/pdf or its file name ends in .pdf, because some mail systems send PDFs as application/octet-stream.
from email import policy
from email.parser import BytesParser
with open(email_path, "rb") as f:
message = BytesParser(policy=policy.default).parse(f)
def first_pdf(message):
for part in message.iter_attachments():
name = part.get_filename() or ""
if part.get_content_type() == "application/pdf" or name.lower().endswith(".pdf"):
return name, part.get_content()
raise ValueError("the email has no PDF attachment")
pdf_name, pdf_bytes = first_pdf(message)
invoice = pymupdf.open(stream=pdf_bytes, filetype="pdf")
page = invoice[0]
print(f'From: {message["From"]}\nSubject: {message["Subject"]}')
print(f"Attachment: {pdf_name}, {invoice.page_count} page, {len(pdf_bytes):,} bytes")From: Grassland Supplies <accounts@grassland.example> Subject: Invoice SI-4471 for PO-0098 Attachment: SI-4471.pdf, 1 page, 15,064 bytes
from IPython.display import Image
page.get_pixmap(dpi=60).save("invoice_preview.png")
Image("invoice_preview.png")Step 2: Read the shipping address
The invoice has two addresses side by side, and the order needs the one under SHIP TO. Reading the whole page's text would mix the two boxes line by line. Instead, Page.search_for() finds the SHIP TO label, and Page.get_text(clip=...) reads only the rectangle under it, the width of the box. The billing address and the line items are outside that rectangle, so they can't get into the shipping address.
The lines are then split into the address fields:
- a line starting
Telis the phone number. Shopify wants phone numbers in international (E.164) format, such as+441134960123, so spaces and punctuation are removed. A number without a+country code is left blank rather than given a guessed country code; - the last remaining line is the country, turned into a two-letter country code;
- the line ending in a postcode is the city and postcode;
- the first line is the recipient's name, and anything between the name and the city is the street address.
This works for the address layout on this supplier's invoices. Addresses are laid out differently in different countries, so check the rules against your own suppliers' invoices. parse_address() raises an error instead of guessing when an address doesn't fit them.
import re
SHIP_TO_WIDTH, SHIP_TO_HEIGHT = 225, 90 # size of the SHIP TO box, in points
UK_POSTCODE = re.compile(r"^(?P<city>.+?)\s+(?P<zip>[A-Z]{1,2}\d[A-Z\d]?\s*\d[A-Z]{2})$", re.I)
COUNTRY_CODES = {"united kingdom": "GB", "uk": "GB", "ireland": "IE", "france": "FR", "germany": "DE"}
def address_lines(page, label="SHIP TO"):
hits = page.search_for(label)
if not hits:
raise ValueError(f"no {label!r} label on the page")
r = hits[0]
box = pymupdf.Rect(r.x0, r.y1, r.x0 + SHIP_TO_WIDTH, r.y1 + SHIP_TO_HEIGHT)
return [line.strip() for line in page.get_text("text", clip=box).splitlines() if line.strip()]
def parse_address(lines):
lines = list(lines)
phone = next((l for l in lines if re.match(r"(tel|phone)\b", l, re.I)), "")
if phone:
lines.remove(phone)
phone = re.sub(r"[^\d+]", "", re.sub(r"^(tel|phone)\.?:?", "", phone, flags=re.I))
if not re.fullmatch(r"\+\d{8,15}", phone):
phone = "" # not international format: don't guess the country code
country = lines.pop()
if country.casefold() not in COUNTRY_CODES:
raise ValueError(f"unknown country {country!r}: add it to COUNTRY_CODES")
city_line = UK_POSTCODE.match(lines.pop())
if not city_line:
raise ValueError("no city and postcode line in the address")
name, *street = lines
if not 1 <= len(street) <= 2:
raise ValueError(f"expected one or two street lines, found {street}")
first, _, last = name.rpartition(" ")
return {
"firstName": first,
"lastName": last,
"address1": street[0],
"address2": street[1] if len(street) > 1 else "",
"city": city_line["city"],
"zip": city_line["zip"].upper(),
"countryCode": COUNTRY_CODES[country.casefold()],
"phone": phone,
}
ship_lines = address_lines(page, "SHIP TO")
print("Text in the SHIP TO box:", *ship_lines, sep="\n ")
shipping_address = parse_address(ship_lines)
print()
for field, value in shipping_address.items():
print(f" {field:<12} {value}")Text in the SHIP TO box: Daisy Moofield Unit 4, Buttercup Barns 12 Clover Lane Moocaster ZZ99 2BB United Kingdom Tel: +44 113 496 0123 firstName Daisy lastName Moofield address1 Unit 4, Buttercup Barns address2 12 Clover Lane city Moocaster zip ZZ99 2BB countryCode GB phone +441134960123
The shop's own address in the BILL TO box, a few points to the left, isn't in the result.
Step 3: Read the line items and map them to the order fields
Page.find_tables() finds the line-item table from its ruling lines and returns its cells row by row, with a wrapped description as one cell containing a line break. The totals under the table aren't in its grid, so they don't turn into line items.
COLUMN_MAP says which invoice column goes to which field of the order script's JSON. It matches on the column header, ignoring case, so the code doesn't depend on the column order. Each supplier names columns their own way: add their headers here, such as "sku", "product code" or "quantity".
Each value is cleaned up for the order:
- Item code goes to
skuas written. A blank cell stays a blanksku. Guessing a code from the description could order the wrong product, so a blank code is left for the order script, or a person, to deal with. - Quantity becomes a whole number.
- Unit price loses the currency symbol and thousands separators, and is kept as a
Decimalso no rounding errors creep in. The currency symbol sets the currency code. - Description has its line breaks joined with spaces.
from decimal import Decimal
COLUMN_MAP = { # invoice column header -> order field
"item code": "sku", "sku": "sku", "product code": "sku",
"description": "title", "item": "title",
"qty": "quantity", "quantity": "quantity",
"unit price": "unit_price", "price": "unit_price",
"amount": "amount", "line total": "amount",
}
CURRENCIES = {"£": "GBP", "€": "EUR", "$": "USD"}
def money(text):
return Decimal(re.sub(r"[^\d.\-]", "", text))
def read_line_items(page):
tables = page.find_tables().tables
for table in tables:
rows = table.extract()
header = [(h or "").replace("\n", " ").strip().casefold() for h in rows[0]]
fields = [COLUMN_MAP.get(h) for h in header]
if {"sku", "title", "quantity", "unit_price"} <= set(fields):
break
else:
raise ValueError("no table with item code, description, quantity and price columns")
items = []
for row in rows[1:]:
cell = {f: (v or "").strip() for f, v in zip(fields, row) if f}
if not any(cell.values()):
continue # empty row
currency = next((CURRENCIES[c] for c in cell["unit_price"] if c in CURRENCIES), None)
items.append({
"sku": cell["sku"], # blank stays blank
"title": " ".join(cell["title"].split()),
"quantity": int(cell["quantity"]),
"unit_price": money(cell["unit_price"]),
"amount": money(cell["amount"]) if cell.get("amount") else None,
"currency": currency,
})
return items
items = read_line_items(page)
for it in items:
print(f'{it["sku"] or "(blank)":<9} {it["quantity"]:>3} x {it["unit_price"]:>6} {it["currency"]} {it["title"]}')KH-1042 6 x 12.50 GBP Linen cushion cover, 45 x 45 cm, sage KH-2210 12 x 6.75 GBP Stoneware mug, speckled white (blank) 2 x 34.00 GBP Oak serving board with leather hanging strap, large KH-3305 3 x 48.00 GBP Wool throw, charcoal KH-0871 10 x 9.20 GBP Beeswax candle, set of 3
Step 4: Build the draft-order payload
The order script takes JSON in the shape of the input argument to Shopify's GraphQL draftOrderCreate mutation, a DraftOrderInput:
shippingAddress: the address from Step 2, using theMailingAddressInputfield names, withcountryCoderather than the deprecatedcountry;lineItems: one entry per invoice line, withtitle,sku,quantityandoriginalUnitPriceWithCurrency(the price and its currency code);note: where the order came from, so anyone looking at the draft order in Shopify can find the original invoice.
The lines are custom line items: they have no variantId, so Shopify takes the title, SKU and price from the payload. Shopify only uses title, sku and originalUnitPriceWithCurrency for custom line items. If a line has a variantId, Shopify ignores those three fields and uses the product variant's own.
Prices are written as strings, such as "12.50", so they arrive exactly as printed on the invoice. That's how Shopify's Decimal type is written too. The draft order is a starting point that a person reviews and completes in Shopify, so the lines with a blank sku are listed below for review.
These field names are from the 2026-10 version of the Shopify Admin GraphQL API. Field names change between versions: if your script uses the REST API, or another version of the GraphQL API, change the keys in build_payload() to match it.
import json
def build_payload(shipping_address, items, invoice_no, supplier, po):
currencies = {it["currency"] for it in items}
if len(currencies) != 1 or None in currencies:
raise ValueError(f"expected one currency on the invoice, found {currencies}")
return {
"input": {
"note": f"From supplier invoice {invoice_no} ({supplier}), PO {po}",
"shippingAddress": shipping_address,
"lineItems": [
{
"title": it["title"],
"sku": it["sku"],
"quantity": it["quantity"],
"originalUnitPriceWithCurrency": {
"amount": str(it["unit_price"]),
"currencyCode": it["currency"],
},
}
for it in items
],
}
}
text = page.get_text()
invoice_no = re.search(r"Invoice No:[ \t]*(\S+)", text).group(1)
po = re.search(r"Your PO:[ \t]*(\S+)", text).group(1)
sender = message["From"].addresses[0]
supplier = sender.display_name or sender.addr_spec
payload = build_payload(shipping_address, items, invoice_no, supplier, po)
with open("draft_order.json", "w", encoding="utf-8") as f:
json.dump(payload, f, indent=2, ensure_ascii=False)
print(json.dumps(payload, indent=2, ensure_ascii=False))
missing_sku = [li["title"] for li in payload["input"]["lineItems"] if not li["sku"]]
print(f"\n{len(missing_sku)} line(s) with no item code, sent with a blank sku: {missing_sku}")Show full output
{
"input": {
"note": "From supplier invoice SI-4471 (Grassland Supplies), PO PO-0098",
"shippingAddress": {
"firstName": "Daisy",
"lastName": "Moofield",
"address1": "Unit 4, Buttercup Barns",
"address2": "12 Clover Lane",
"city": "Moocaster",
"zip": "ZZ99 2BB",
"countryCode": "GB",
"phone": "+441134960123"
},
"lineItems": [
{
"title": "Linen cushion cover, 45 x 45 cm, sage",
"sku": "KH-1042",
"quantity": 6,
"originalUnitPriceWithCurrency": {
"amount": "12.50",
"currencyCode": "GBP"
}
},
{
"title": "Stoneware mug, speckled white",
"sku": "KH-2210",
"quantity": 12,
"originalUnitPriceWithCurrency": {
"amount": "6.75",
"currencyCode": "GBP"
}
},
{
"title": "Oak serving board with leather hanging strap, large",
"sku": "",
"quantity": 2,
"originalUnitPriceWithCurrency": {
"amount": "34.00",
"currencyCode": "GBP"
}
},
{
"title": "Wool throw, charcoal",
"sku": "KH-3305",
"quantity": 3,
"originalUnitPriceWithCurrency": {
"amount": "48.00",
"currencyCode": "GBP"
}
},
{
"title": "Beeswax candle, set of 3",
"sku": "KH-0871",
"quantity": 10,
"originalUnitPriceWithCurrency": {
"amount": "9.20",
"currencyCode": "GBP"
}
}
]
}
}
1 line(s) with no item code, sent with a blank sku: ['Oak serving board with leather hanging strap, large']Step 5: Check the payload against the invoice
A payload that looks right can still be wrong: a row missed by the table detection, or a quantity read from the wrong column. These checks compare the payload with what the invoice itself says:
- for every line, quantity × unit price equals the line amount printed on the invoice;
- the line amounts add up to the subtotal printed under the table, so no line is missing or extra;
- every
skuis either blank or appears on the page exactly as written, so no code was changed or made up; - no part of the billing address is in the shipping address;
- the phone number is blank or in E.164 format.
lines = payload["input"]["lineItems"]
for li, it in zip(lines, items):
price = Decimal(li["originalUnitPriceWithCurrency"]["amount"])
assert li["quantity"] * price == it["amount"], f'{li["title"]}: {li["quantity"]} x {price} != {it["amount"]}'
subtotal = money(re.search(r"Subtotal\s*\n?\s*(£[\d,.]+)", page.get_text("text", sort=True)).group(1))
line_total = sum(li["quantity"] * Decimal(li["originalUnitPriceWithCurrency"]["amount"]) for li in lines)
assert line_total == subtotal, f"line items add up to {line_total}, invoice subtotal is {subtotal}"
for li in lines:
assert li["sku"] == "" or page.search_for(li["sku"]), f'sku {li["sku"]} is not on the invoice'
bill_to = address_lines(page, "BILL TO")
assert not set(bill_to) & set(shipping_address.values()), "billing address details in the shipping address"
assert re.fullmatch(r"(\+\d{8,15})?", shipping_address["phone"]), "phone number is not in E.164 format"
print(f"{len(lines)} line items, {sum(li['quantity'] for li in lines)} units, total {line_total} = invoice subtotal {subtotal}")
print("all checks passed")5 line items, 33 units, total 460.00 = invoice subtotal 460.00 all checks passed
Limits to know
- Ruled tables.
find_tables()finds this table from its ruling lines. For an invoice whose table has no lines, trypage.find_tables(strategy="text"), which uses the alignment of the text instead, and check the rows it returns. - One page. The sample invoice fits on one page. For a longer invoice, run
read_line_items()on each page and join the results, skipping a header row repeated at the top of each page. - Text-based PDFs. A scanned invoice has no text to read. Run OCR first, for example with
Page.get_textpage_ocr(), and rely on the Step 5 checks: a misread quantity or price makes the totals disagree. - One address format.
parse_address()follows the layout of UK addresses on this supplier's invoices. Other countries put the postcode, city and region in a different order, and some need aprovinceCode. - The SKU is the supplier's code. The supplier's item code may not be your Shopify SKU. If they differ, look each code up in a table from supplier code to your SKU before building the payload, and leave the field blank when there's no match. To order your own catalogue products rather than custom line items, look up each product's
variantIdand send that with the quantity: Shopify then ignorestitle,skuand the price, and uses the variant's own.
Next steps
Page.find_tables(),Page.search_for()andPage.get_text()in the PyMuPDF documentationdraftOrderCreatein the Shopify Admin GraphQL API documentation- To process a mailbox, read new messages with
imapliband pass each one toBytesParserin place of the.emlfile.
Discuss This Article with the Community
Have a question, a different approach, or something you built after reading this? Share it on the forum or join the Discord, we'd love to hear from you.