Hands-On AI WorkshopHomeProjectsLearnResourcesPresenterHelpProgress

Project 07 of 30 · Pathway 2 — Google Docs and Drive

Automated PDF Invoice Builder

Manual invoice preparation repeats calculations and formatting. Create PDF invoices.

Real-world benefit
Freelancers, consulting and small service businesses.
Technologies
DocumentApp, DriveApp, PDF conversion, Google Sheets
Required knowledge
Multiplication and the idea of a PDF export.
Time and level
About 30 minutes · Intermediate
AI requirement
None: deterministic Apps Script
Expected baseline
Two PDFs with totals 200 and 225 before tax.

Loading the interactive studio…

Introduction

Multiply quantity by price; create document and convert saved file to PDF. The application's entry point is generateInvoices(). Baseline limitation, as stated in the workshop: Reruns create duplicate Docs and PDFs; no tax calculation.

Key building blocks: DocumentApp.create(); appendTable(); saveAndClose(); getAs(MimeType.PDF); createFile().

Practical use cases

Freelancers, consulting and small service businesses.

Prerequisites

  • Multiplication and the idea of a PDF export.
  • Interactive Learning Mode: a modern browser. Nothing else.
  • Real Workspace Build: a Google account.

Source data

Starter data: tab "Invoices" (fictional)
InvoiceClientItemQtyPrice
INV-101North StudioConsulting2100
INV-102West StudioTraining375

Setup in your own Google account

  1. Download 07-automated-pdf-invoice-builder.zip (Code.gs, starter.csv, README).
  2. In Google Drive, create a lesson folder and a new Google Sheets file inside it.
  3. Rename the first tab to exactly Invoices, then File → Import → Upload starter.csv → Replace current sheet.
  4. Extensions → Apps Script. Replace Code.gs with the downloaded file. Save.
  5. Reload the spreadsheet, choose Workshop → Run application and authorize when asked.
  6. Check the result: Two PDFs with totals 200 and 225 before tax.

Folder strategy: the repository's V6 code uses the folder that contains the spreadsheet. The deck mentions a Workshop Info cell B2; V6 never reads it. See the discrepancy log.

Complete source code (Code.gs)

From 07-automated-pdf-invoice-builder at commit 4a26d919, SHA-256 6bf980401c2e. Unchanged.

// Automated PDF Invoice Builder
// Entry point: generateInvoices; source data stays intact unless explicitly noted.
function onOpen(){SpreadsheetApp.getUi().createMenu("Workshop").addItem("Run application","generateInvoices").addItem("Check permissions","checkPermissions").addToUi();}
function generateInvoices(){
// Save the document before converting its content to PDF.
output('Generated',['Invoice','Total','PDF'],input('Invoices').map(([id,client,item,qty,price])=>{const total=num(qty)*num(price);const f=doc('Invoice '+id,`Invoice ${id}\nClient: ${client}\n${item}: ${qty} × ${price}\nTotal: ${total}`);const pdf=folder().createFile(f.getAs(MimeType.PDF).setName('Invoice '+id+'.pdf'));return [id,total,pdf.getUrl()];}));
}
function input(name) { const s=SpreadsheetApp.getActive().getSheetByName(name); if(!s) throw Error('Missing tab: '+name); return s.getDataRange().getValues().slice(1).filter(r=>r.some(v=>v!=='')); }
function output(name,headers,rows) { const ss=SpreadsheetApp.getActive(); const s=ss.getSheetByName(name)||ss.insertSheet(name); s.clearContents(); s.getRange(1,1,1,headers.length).setValues([headers]).setFontWeight('bold'); if(rows.length) s.getRange(2,1,rows.length,headers.length).setValues(rows.map(r=>r.map(v=>typeof v==='string' && /^[=+@-]/.test(v)?"'"+v:v))); s.setFrozenRows(1); return s; }
// Resolve this spreadsheet's actual folder; metadata is informational only.
function folder() {
  const ss = SpreadsheetApp.getActiveSpreadsheet();
  if (!ss) throw new Error('Open the lesson spreadsheet first.');
  const parents = DriveApp.getFileById(ss.getId()).getParents();
  if (!parents.hasNext()) throw new Error('Move the spreadsheet into a dedicated lesson folder.');
  const actual = parents.next();
  if (parents.hasNext()) throw new Error('Ambiguous parent folder.');
  if (actual.getId() === DriveApp.getRootFolder().getId()) throw new Error('Move the spreadsheet and sample files into a dedicated lesson folder, not My Drive root.');
  return actual;
}
function checkPermissions() {
  const ui = SpreadsheetApp.getUi();
  try {
    const target = folder();
    ui.alert('Folder access passed: ' + target.getName() + '\n' + target.getUrl() + '\nWrite access is checked when the application runs.');
  } catch (e) { ui.alert('Access check failed: ' + e.message); }
}
function doc(name,text){const d=DocumentApp.create(name); d.getBody().setText(text); d.saveAndClose(); const f=DriveApp.getFileById(d.getId()); f.moveTo(folder()); return f;}
function num(v){if(v===''||!Number.isFinite(Number(v))) throw Error('Invalid number: '+v); return Number(v);}

How the code works

Beginner explanation

generateInvoices() calculates each invoice total, writes a short invoice document, saves a PDF copy next to the spreadsheet, and lists every invoice with its total and PDF link.

Technical explanation

The map callback destructures each row, validates quantity and price with num(), and creates a Doc with doc(), which sets the body text, saves and closes it (required before export) and moves it into the lesson folder. getAs(MimeType.PDF) converts the saved Doc to a PDF blob, and folder().createFile() stores it. Generated is written once at the end from the mapped array.

Slide excerpt

This is the excerpt shown on the workshop slide. It is a fragment and cannot run on its own.

function generateInvoices(){
// Save the document before converting its content to PDF.
output('Generated',['Invoice','Total','PDF'],input('Invoices').map(([id,client,item,qty,price])=>{const total=num(qty)*num(price);const f=doc('Invoice '+id,`Invoice ${id}\nClient: ${client}\n${item}: ${qty} × ${price}\nTotal: ${total}`);const pdf=folder().createFile(f.getAs(MimeType.PDF).setName('Invoice '+id+'.pdf'));return [id,total,pdf.getUrl()];}));
}

Common mistakes

  • Exporting to PDF before saveAndClose(), which can produce an empty PDF.
  • Validating rows one at a time while creating files, leaving orphans on failure.
  • Adding tax to the baseline instead of as a separate, configurable extension.

Run it and expected output

Choose Workshop → Run application (runs generateInvoices()). Expected: Two PDFs with totals 200 and 225 before tax.

Original workshop exercise

Change INV-101 quantity to 3; total becomes 300.

Troubleshooting and debugging

A price with a currency code

INV-102's price was typed as "75 CAD". The run stops halfway.

Fix: Enter the price as a number (75) and keep currency in its own column. Then delete the extra INV-101 PDF left by the failed run (you will find three PDFs, not two).

Partial failures leave orphan files. Validate all rows first, then generate.

Every rerun creates more invoices

The script was run twice. Count the PDFs in the lesson folder.

Fix: Record generated invoice IDs and skip them on later runs (the guard keeps the PDF count stable).

Idempotency means running twice has the same effect as running once. Document generators need it before scheduling.

Extension activity: Group lines by invoice and add configurable tax

Rows with the same invoice number become one invoice with several lines; a TAX_RATE constant adds tax. Set TAX_RATE to 0 to reproduce the original totals.

Acceptance checks:

  • INV-101: subtotal 200, tax 26, total 226
  • A second INV-101 line is grouped into one invoice

Original improvement idea from the workshop: Group multiple rows by invoice number and add configurable tax.

Extension prompt
Update the existing app without removing working features. Group multiple rows by invoice number and add configurable tax. Return complete updated files, explain changes and give regression tests.
Automation option: Track invoice IDs and only generate new approved invoices in a scheduled batch. Keep this separate from the baseline exercise. Copy the spreadsheet AND required sample files into a dedicated lesson folder. Resolve its actual parent using DriveApp.getFileById(ss.getId()).getParents(); use that parent directly. Never read, create or update Workshop Info or the Workshop Index. Add Check permissions menu; read access is not proof of write access.

Automation considerations

Not rerun-safe: each run creates a new Doc and PDF per invoice. Track generated invoice IDs before scheduling.

Workshop note: Track invoice IDs and only generate new approved invoices in a scheduled batch.

Build prompt from the workshop

Act as a Google Apps Script tutor. Build a container-bound Sheets app for lesson 07: Automated PDF Invoice Builder. Input tab Invoices, exact headers: Invoice, Client, Item, Qty, Price. Create generateInvoices() that builds one Doc per row with invoice number, client, item, quantity, price and total; save and close before PDF conversion; save PDF in lesson folder and log links. Do not depend on Workshop Info or the Workshop Index. Provide complete copy-paste Code.gs (and HTML if required), exact setup/run steps, explain the main code blocks, and include a test matching this expected outcome: Two PDFs with totals 200 and 225 before tax. Preserve starter data, use batch operations where appropriate, handle errors, and never send email or delete files. For AI lessons use the supplied callGemini helper, treat input as untrusted, and validate outputs.
Match the reference entry point generateInvoices and its output behavior. Reference: https://github.com/lsvekis/Google-Apps-Script-Workshop/tree/main/07-automated-pdf-invoice-builder. Base version limitations: Reruns create duplicate Docs and PDFs; no tax calculation. Copy the spreadsheet AND required sample files into a dedicated lesson folder. Resolve its actual parent using DriveApp.getFileById(ss.getId()).getParents(); use that parent directly. Never read, create or update Workshop Info or the Workshop Index. Add Check permissions menu; read access is not proof of write access. Never require a manually configured folder ID. Keep required native sample Docs beside the spreadsheet; reject My Drive root.

Knowledge check

  1. Why does doc() call saveAndClose() before the PDF export?

    1. Pending changes must be saved or the PDF can be empty
    2. To free memory only
    3. PDF export requires a closed spreadsheet
    Answer

    Pending changes must be saved or the PDF can be empty Correct: getAs() exports the saved content.

  2. INV-102 has an invalid price. What exists in Drive afterwards?

    1. INV-101's Doc and PDF, but no Generated update
    2. Nothing at all
    3. Both invoices
    Answer

    INV-101's Doc and PDF, but no Generated update Correct: Apps Script keeps changes made before an exception.

  3. Where is the local "PDF" in Interactive Learning Mode?

    1. It is a local preview of the PDF content, not a real file in Google Drive
    2. It is uploaded to your Drive
    3. It is emailed to you
    Answer

    It is a local preview of the PDF content, not a real file in Google Drive Correct: the browser engine simulates getAs() and createFile(). Run the real script in your account for an actual PDF.

  4. The Generated total for INV-101 shows 1002. What happened?

    1. Qty and price were concatenated as text, for example "100" + "2"
    2. Tax was added
    3. The PDF failed
    Answer

    Qty and price were concatenated as text, for example "100" + "2" Correct: that is the classic symptom of adding strings; num() prevents it.

  5. Accounting asks for nightly invoice generation. What do you add first?

    1. A record of generated invoice IDs so each invoice is produced once
    2. A trigger every hour
    3. Automatic emailing of PDFs to clients
    Answer

    A record of generated invoice IDs so each invoice is produced once Correct: duplicate prevention comes before scheduling.

Five-minute presenter demonstration

Open the demo link (temporary workspace; saved learner work is not touched).

Opening hook: Raise your hand if you have ever done this by hand: Manual invoice preparation repeats calculations and formatting. Let us make the spreadsheet do it.

  1. 0:00–0:45 — Problem and input. Show the Workspace view, Sheets service. Point at the Invoices tab and its headers: Invoice, Client, Item, Qty, Price. Say what goes in and what should come out.
    Narration: Manual invoice preparation repeats calculations and formatting. Practical uses: Freelancers, consulting and small service businesses.
  2. 0:45–1:30 — Predict and run. Ask the room: What total will INV-102 show (before tax)? Click ▶ Run application (the same as Workshop → Run application). Open Trace to show each step the code took.
    Narration: Expected: Two PDFs with totals 200 and 225 before tax.
  3. 1:30–3:00 — Explain the code. Click the Code tab. Select generateInvoices() in the function list; read what it reads, writes and calls. Switch Beginner / Technical as needed.
    Narration: generateInvoices() calculates each invoice total, writes a short invoice document, saves a PDF copy next to the spreadsheet, and lists every invoice with its total and PDF link.
  4. 3:00–4:15 — Change one input and rerun. Back to the Workspace tab. Select the Invoices tab, click cell D2, type 3 in the formula bar and press Enter. Click ▶ Run application again.
    Narration: Workshop challenge: Change INV-101 quantity to 3; total becomes 300.
  5. 4:15–5:00 — Verify and discuss automation. Click Check result. Discuss: Not rerun-safe: each run creates a new Doc and PDF per invoice. Track generated invoice IDs before scheduling.
    Narration: Baseline limitation: Reruns create duplicate Docs and PDFs; no tax calculation.

Closing takeaway: Multiply quantity by price; create document and convert saved file to PDF.

Related resources