Khurram Badar / Archive / Papers / Word document generation with Node.js styling

Word document generation with Node.js styling

other · 2026-03-04 · 2779 words · Khurram Badar

Code implementation for programmatically generating formatted Word documents using docx library with custom styling.

document-generation · node.js · word · programming · technical

const {
Document, Packer, Paragraph, TextRun, Table, TableRow, TableCell,
HeadingLevel, AlignmentType, BorderStyle, WidthType, ShadingType,
LevelFormat, PageNumber, PageBreak
} = require('docx');
const fs = require('fs');

const border = { style: BorderStyle.SINGLE, size: 1, color: "CCCCCC" };
const borders = { top: border, bottom: border, left: border, right: border };

const accentColor = "1A5276";
const lightBlue = "D6EAF8";
const lightGreen = "D5F5E3";
const lightAmber = "FDEBD0";
const white = "FFFFFF";

function heading1(text) {
return new Paragraph({
heading: HeadingLevel.HEADING_1,
children: [new TextRun({ text, bold: true, size: 32, color: accentColor, font: "Arial" })],
spacing: { before: 360, after: 120 },
border: { bottom: { style: BorderStyle.SINGLE, size: 6, color: accentColor, space: 1 } }
});
}

function heading2(text) {
return new Paragraph({
heading: HeadingLevel.HEADING_2,
children: [new TextRun({ text, bold: true, size: 26, color: "2471A3", font: "Arial" })],
spacing: { before: 240, after: 80 }
});
}

function para(text, opts = {}) {
return new Paragraph({
children: [new TextRun({ text, size: 22, font: "Arial", ...opts })],
spacing: { before: 60, after: 60 }
});
}

function bullet(text) {
return new Paragraph({
numbering: { reference: "bullets", level: 0 },
children: [new TextRun({ text, size: 22, font: "Arial" })],
spacing: { before: 40, after: 40 }
});
}

function keyValueTable(rows, leftColor = lightBlue) {
return new Table({
width: { size: 9360, type: WidthType.DXA },
columnWidths: [2800, 6560],
rows: rows.map(([key, value]) =>
new TableRow({
children: [
new TableCell({
borders,
width: { size: 2800, type: WidthType.DXA },
shading: { fill: leftColor, type: ShadingType.CLEAR },
margins: { top: 80, bottom: 80, left: 120, right: 120 },
children: [new Paragraph({ children: [new TextRun({ text: key, bold: true, size: 20, font: "Arial" })] })]
}),
new TableCell({
borders,
width: { size: 6560, type: WidthType.DXA },
shading: { fill: white, type: ShadingType.CLEAR },
margins: { top: 80, bottom: 80, left: 120, right: 120 },
children: [new Paragraph({ children: [new TextRun({ text: value, size: 20, font: "Arial" })] })]
})
]
})
)
});
}

function sectionBox(title, content, fillColor = lightBlue) {
return new Table({
width: { size: 9360, type: WidthType.DXA },
columnWidths: [9360],
rows: [
new TableRow({
children: [new TableCell({
borders,
width: { size: 9360, type: WidthType.DXA },
shading: { fill: accentColor, type: ShadingType.CLEAR },
margins: { top: 80, bottom: 80, left: 120, right: 120 },
children: [new Paragraph({ children: [new TextRun({ text: title, bold: true, size: 22, color: "FFFFFF", font: "Arial" })] })]
})]
}),
new TableRow({
children: [new TableCell({
borders,
width: { size: 9360, type: WidthType.DXA },
shading: { fill: fillColor, type: ShadingType.CLEAR },
margins: { top: 100, bottom: 100, left: 160, right: 160 },
children: content.map(t => new Paragraph({ children: [new TextRun({ text: t, size: 20, font: "Arial" })], spacing: { before: 40, after: 40 } }))
})]
})
]
});
}

const doc = new Document({
numbering: {
config: [{
reference: "bullets",
levels: [{ level: 0, format: LevelFormat.BULLET, text: "\u2022", alignment: AlignmentType.LEFT,
style: { paragraph: { indent: { left: 720, hanging: 360 } } } }]
}]
},
styles: {
default: { document: { run: { font: "Arial", size: 22 } } },
paragraphStyles: [
{ id: "Heading1", name: "Heading 1", basedOn: "Normal", next: "Normal", quickFormat: true,
run: { size: 32, bold: true, font: "Arial", color: accentColor },
paragraph: { spacing: { before: 360, after: 120 }, outlineLevel: 0 } },
{ id: "Heading2", name: "Heading 2", basedOn: "Normal", next: "Normal", quickFormat: true,
run: { size: 26, bold: true, font: "Arial", color: "2471A3" },
paragraph: { spacing: { before: 240, after: 80 }, outlineLevel: 1 } }
]
},
sections: [{
properties: {
page: {
size: { width: 12240, height: 15840 },
margin: { top: 1440, right: 1440, bottom: 1440, left: 1440 }
}
},
children: [

// TITLE BLOCK
new Table({
width: { size: 9360, type: WidthType.DXA },
columnWidths: [9360],
rows: [new TableRow({
children: [new TableCell({
borders: { top: border, bottom: border, left: border, right: border },
width: { size: 9360, type: WidthType.DXA },
shading: { fill: "1A5276", type: ShadingType.CLEAR },
margins: { top: 200, bottom: 200, left: 240, right: 240 },
children: [
new Paragraph({ alignment: AlignmentType.CENTER, children: [new TextRun({ text: "CHAT SESSION SUMMARY", bold: true, size: 40, color: "FFFFFF", font: "Arial" })] }),
new Paragraph({ alignment: AlignmentType.CENTER, children: [new TextRun({ text: "Pakistan Digital Finance, Tokenization & Agriculture Strategy", size: 24, color: "AED6F1", font: "Arial" })] }),
new Paragraph({ alignment: AlignmentType.CENTER, children: [new TextRun({ text: "Session Date: March 4, 2026 | Prepared for: Continuation Chat", size: 20, color: "AED6F1", font: "Arial" })] }),
]
})]
})]
}),

new Paragraph({ children: [new TextRun("")], spacing: { before: 200, after: 0 } }),

// CONTEXT
heading1("1. Session Context & Background"),
para("This conversation was initiated via voice message and covered a high-level strategic briefing on Pakistan's emerging digital finance architecture. The central thread connects several recent international visits, deal signings, and a key government initiative around a new national asset holding company."),
new Paragraph({ children: [new TextRun("")], spacing: { before: 80 } }),
keyValueTable([
["Core Topic", "Pakistan National Asset Holding Company — board member recommendations requested by Ministry of Finance"],
["User Role", "Advisor being consulted by Pakistan's Ministry of Finance"],
["Holding Co. Purpose", "Custodian/holding vehicle for Pakistan's national assets (fractional reserves, foreign currency, tokenized sovereign assets)"],
["Session Format", "Voice transcription + deep dive research across 3 major themes"],
]),

new Paragraph({ children: [new TextRun("")], spacing: { before: 200 } }),

// PART 1 - WLF
heading1("2. World Liberty Financial (WLF) & USD1 Stablecoin"),

heading2("April 2025 — Letter of Intent"),
para("World Liberty Financial (the Trump family's DeFi platform, co-founded by Trump's three sons and the two Witkoff sons) signed an LOI with the Pakistan Crypto Council. Signatories included Zach Witkoff, Zak Folkman, and Chase Herro. Attendees included Pakistan's Finance Minister, State Bank Governor, and SECP Chairman."),
new Paragraph({ children: [new TextRun("")], spacing: { before: 60 } }),
sectionBox("LOI Scope of Work", [
"Regulatory sandboxes for blockchain product testing",
"Stablecoin applications for remittances and trade",
"Real-world asset (RWA) tokenization",
"Decentralized finance (DeFi) protocol development",
], lightBlue),

new Paragraph({ children: [new TextRun("")], spacing: { before: 120 } }),
heading2("January 14, 2026 — MOU Signed"),
para("Pakistan's Ministry of Finance signed an MOU with SC Financial Technologies (a Delaware-registered affiliated entity of World Liberty Financial). CEO Zach Witkoff (also son of US Special Envoy Steve Witkoff) visited Islamabad to formally sign the deal."),
new Paragraph({ children: [new TextRun("")], spacing: { before: 60 } }),
keyValueTable([
["Agreement Type", "MOU — Ministry of Finance with SC Financial Technologies"],
["Key Mechanism", "Integrate USD1 stablecoin into Pakistan's regulated digital payments framework"],
["Use Case", "Cross-border payments and remittances ($36B+ annual flows)"],
["Central Bank Role", "State Bank of Pakistan to work alongside USD1 infrastructure"],
["Political Significance", "One of the first sovereign-state tie-ups for World Liberty Financial globally"],
]),

new Paragraph({ children: [new TextRun("")], spacing: { before: 120 } }),
heading2("Key Person: Bilal Bin Saqib"),
para("Chairman of Pakistan's Virtual Assets Regulatory Authority (PVARA); CEO of Pakistan Crypto Council; Special Assistant to PM on blockchain & crypto; Chief Adviser to Finance Minister. Became a WLF adviser in April 2025 shortly after Witkoff's visit."),

new Paragraph({ children: [new TextRun("")], spacing: { before: 200 } }),

// PART 2 - DAMAC / PRYPCO
heading1("3. DAMAC Group / Amira Sajwani / PRYPCO Mint"),

heading2("January 7, 2026 — Delegation Visit"),
para("A high-level delegation led by One Group Chairman Syed Zeeshan Shah, including DAMAC Co-Managing Director Amira Hussain Sajwani (also CEO of PRYPCO) and PRYPCO General Manager of Tokenisation Joseph El Am, visited Islamabad and Lahore."),
new Paragraph({ children: [new TextRun("")], spacing: { before: 60 } }),
sectionBox("Meetings Held", [
"Finance Minister Muhammad Aurangzeb — digital finance & tokenization collaboration",
"IT Minister Shaza Fatima Khawaja — PropTech, tech talent, digitisation",
"Punjab CM Maryam Nawaz — Punjab government tokenization agreement signed",
], lightGreen),

new Paragraph({ children: [new TextRun("")], spacing: { before: 120 } }),
heading2("Punjab Government Agreement"),
para("Punjab (Pakistan's agricultural and economic heartland) signed a formal agreement with DAMAC to accelerate the tokenisation of government and commercial assets in the province. CM Maryam declared Punjab would be 'Pakistan's gateway for foreign direct investment in digital assets.'"),

new Paragraph({ children: [new TextRun("")], spacing: { before: 120 } }),
heading2("What is PRYPCO Mint?"),
keyValueTable([
["What it is", "MENA's first licensed real estate tokenization platform"],
["Government Partner", "Dubai Land Department (DLD) — world's first to tokenize property title deeds with a government entity"],
["Regulator", "Dubai's VARA (Virtual Assets Regulatory Authority)"],
["Marketplace Launch", "February 20, 2026 — first tokenized property resale marketplace went live"],
["Phase 1 Results", "AED 18.5M+ in tokenized investments; investors from 50+ nationalities; one property funded in under 2 minutes"],
["Infrastructure", "Fireblocks selected as enterprise digital asset infrastructure provider (January 2026)"],
["Global Expansion", "MOU signed with Georgia's Ministry of Justice for real estate tokenization; Pakistan engagement ongoing"],
], lightGreen),

new Paragraph({ children: [new TextRun("")], spacing: { before: 200 } }),

// PART 3 - BINANCE
heading1("4. Binance — December 2025"),
para("Pakistan signed an MOU with Binance (world's largest crypto exchange) to explore tokenization of up to $2 billion in sovereign bonds, treasury bills, and commodity reserves. Binance and HTX also received no-objection certificates to operate in Pakistan. Former Binance CEO Changpeng Zhao (CZ) serves as adviser to Pakistan Crypto Council."),
new Paragraph({ children: [new TextRun("")], spacing: { before: 80 } }),
keyValueTable([
["Assets to Tokenize", "Sovereign bonds, treasury bills, commodity reserves"],
["Target Value", "Up to $2 billion"],
["Goal", "Attract foreign investment, unlock liquidity via blockchain"],
["CZ Quote", "Called it 'a great signal for the global blockchain industry and for Pakistan'"],
]),

new Paragraph({ children: [new TextRun("")], spacing: { before: 200 } }),

// PART 4 — CLEAN ENERGY
heading1("5. Clean Energy — Pakistan's Solar Revolution"),

heading2("The Headline Statistic"),
new Table({
width: { size: 9360, type: WidthType.DXA },
columnWidths: [9360],
rows: [new TableRow({
children: [new TableCell({
borders,
width: { size: 9360, type: WidthType.DXA },
shading: { fill: "D5F5E3", type: ShadingType.CLEAR },
margins: { top: 120, bottom: 120, left: 200, right: 200 },
children: [
new Paragraph({ alignment: AlignmentType.CENTER, children: [new TextRun({ text: "Solar went from 0% to 30% of Pakistan's power mix in just 6 years.", bold: true, size: 26, color: "1A5276", font: "Arial" })] }),
new Paragraph({ alignment: AlignmentType.CENTER, children: [new TextRun({ text: "Described by analysts as 'preposterous' — one of the fastest solar revolutions ever recorded.", size: 20, font: "Arial" })] }),
]
})]
})]
}),

new Paragraph({ children: [new TextRun("")], spacing: { before: 120 } }),
heading2("Key Drivers"),
bullet("Global solar panel prices fell ~50% due to Chinese manufacturing overcapacity"),
bullet("Pakistan exempted solar PV imports from duties and taxes (until mid-2025)"),
bullet("Removal of diesel subsidies made solar pumps economically superior for farmers"),
bullet("High grid tariffs pushed households and export industries to install rooftop systems"),
bullet("GCF-backed Pakistan Distributed Solar Project: 43MW financed for households, agribusinesses, SMEs"),

new Paragraph({ children: [new TextRun("")], spacing: { before: 120 } }),
heading2("Government Targets"),
keyValueTable([
["2030 Renewable Target", "60% of electricity from renewables"],
["EV Target", "30% electric vehicles by 2030"],
["Energy Transition Cost", "Estimated $101 billion required"],
["Financing Split", "15% domestic / 35% international (concessional)"],
["Framework", "Sustainable Financing Framework 2025 — green bonds, blue bonds, Sukuks covering solar, wind, hydro, sustainable agriculture, clean transport"],
], lightGreen),

new Paragraph({ children: [new TextRun("")], spacing: { before: 200 } }),

// PART 5 — AGRICULTURE
heading1("6. Sustainable Agriculture — The Tokenization Opportunity"),

heading2("Why Pakistan's Agriculture is a Unique Opportunity"),
bullet("Pakistan is among the world's largest producers of wheat, rice, cotton, sugarcane, and mangoes"),
bullet("Agriculture employs ~37% of Pakistan's workforce and contributes ~20% of GDP"),
bullet("Smallholder farmers chronically underfinanced — banks don't accept crops as collateral"),
bullet("Solar pumps already transforming irrigation — creating a clean energy + agriculture nexus"),
bullet("Punjab (largest agricultural province) has already signed tokenization agreement with DAMAC"),

new Paragraph({ children: [new TextRun("")], spacing: { before: 120 } }),
heading2("Crop Tokenization — How It Works"),
para("Tokenizing agricultural commodities converts physical harvests (wheat, rice, cotton) into digital tokens on a blockchain. Each token represents a fractional share of the physical harvest. Farmers gain working capital before harvest; global investors get a commodity-backed digital asset."),
new Paragraph({ children: [new TextRun("")], spacing: { before: 60 } }),
sectionBox("Agricultural Tokenization Benefits for Pakistan", [
"Pre-harvest financing: farmers sell future crop shares to global investors via tokens",
"Eliminates middlemen: direct farmer-to-investor transactions, improving margins",
"Traceability: IoT sensors on farms feed real-time data to blockchain (proof of existence)",
"Carbon credits: sustainable farming practices tokenized and sold to global ESG funds",
"Diaspora investment: Pakistan's $36B+ annual remittance base can invest directly into homeland agriculture",
"Collateral: tokenized crops and farmland serve as DeFi loan collateral",
], lightAmber),

new Paragraph({ children: [new TextRun("")], spacing: { before: 200 } }),

// PART 6 — THE INTEGRATED ARCHITECTURE
heading1("7. The Integrated Architecture — How It All Connects"),

para("The national asset holding company sits at the convergence of all these threads. The following four-layer model describes how the full system would operate:"),
new Paragraph({ children: [new TextRun("")], spacing: { before: 120 } }),

new Table({
width: { size: 9360, type: WidthType.DXA },
columnWidths: [1440, 2200, 5720],
rows: [
new TableRow({
children: [
new TableCell({ borders, width: { size: 1440, type: WidthType.DXA }, shading: { fill: accentColor, type: ShadingType.CLEAR }, margins: { top: 80, bottom: 80, left: 120, right: 120 },
children: [new Paragraph({ children: [new TextRun({ text: "Layer", bold: true, size: 20, color: "FFFFFF", font: "Arial" })] })] }),
new TableCell({ borders, width: { size: 2200, type: WidthType.DXA }, shading: { fill: accentColor, type: ShadingType.CLEAR }, margins: { top: 80, bottom: 80, left: 120, right: 120 },
children: [new Paragraph({ children: [new TextRun({ text: "Component", bold: true, size: 20, color: "FFFFFF", font: "Arial" })] })] }),
new TableCell({ borders, width: { size: 5720, type: WidthType.DXA }, shading: { fill: accentColor, type: ShadingType.CLEAR }, margins: { top: 80, bottom: 80, left: 120, right: 120 },
children: [new Paragraph({ children: [new TextRun({ text: "Function", bold: true, size: 20, color: "FFFFFF", font: "Arial" })] })] }),
]
}),
...[
["Layer 1", "Binance + PRYPCO/DAMAC", "Tokenization of agricultural land, crop futures, solar farms, wind projects, sovereign bonds — converting physical assets into fractional digital tokens accessible to global investors"],
["Layer 2", "National Asset Holding Co.", "The CUSTODIAN — holds underlying physical assets on behalf of token holders; provides legal certainty, regulatory backing and sovereignty guarantee"],
["Layer 3", "USD1 Stablecoin (WLF)", "SETTLEMENT CURRENCY — investors transact in dollar-pegged stable currency; remittances flow directly into tokenized agricultural/energy investments; bypasses traditional banking rails"],
["Layer 4", "Carbon Credits + Green Bonds", "MONETIZATION LAYER — sustainable farming practices and clean energy generate tokenized carbon credits; Pakistan's SFF 2025 green bonds attract ESG capital globally"],
].map(([l, c, f], i) =>
new TableRow({
children: [
new TableCell({ borders, width: { size: 1440, type: WidthType.DXA }, shading: { fill: i % 2 === 0 ? lightBlue : white, type: ShadingType.CLEAR }, margins: { top: 80, bottom: 80, left: 120, right: 120 },
children: [new Paragraph({ children: [new TextRun({ text: l, bold: true, size: 20, font: "Arial" })] })] }),
new TableCell({ borders, width: { size: 2200, type: WidthType.DXA }, shading: { fill: i % 2 === 0 ? lightBlue : white, type: ShadingType.CLEAR }, margins: { top: 80, bottom: 80, left: 120, right: 120 },
children: [new Paragraph({ children: [new TextRun({ text: c, bold: true, size: 20, font: "Arial" })] })] }),
new TableCell({ borders, width: { size: 5720, type: WidthType.DXA }, shading: { fill: i % 2 === 0 ? lightBlue : white, type: ShadingType.CLEAR }, margins: { top: 80, bottom: 80, left: 120, right: 120 },
children: [new Paragraph({ children: [new TextRun({ text: f, size: 20, font: "Arial" })] })] }),
]
})
)
]
}),

new Paragraph({ children: [new TextRun("")], spacing: { before: 200 } }),

// PART 7 — BOARD IMPLICATIONS
heading1("8. Board Composition Implications"),
para("Given the scope of what the national asset holding company must govern, the board needs to represent four distinct domains of expertise:"),
new Paragraph({ children: [new TextRun("")], spacing: { before: 80 } }),
keyValueTable([
["Tokenization Infrastructure", "Experience with RWA tokenization platforms, blockchain protocol governance, and custodial digital asset systems (PRYPCO/DAMAC model)"],
["Sustainable Finance", "Green bond structuring, ESG capital markets, carbon credit frameworks, and international climate finance (SFF 2025 alignment)"],
["Agricultural Economics", "Pakistan-specific agri finance, smallholder credit systems, commodity markets, and supply chain infrastructure"],
["International Capital Markets", "Cross-border investment structures, DeFi protocol governance, stablecoin regulatory compliance, and sovereign debt management"],
], lightAmber),

new Paragraph({ children: [new TextRun("")], spacing: { before: 200 } }),

// KEY NUMBERS
heading1("9. Key Numbers at a Glance"),
new Table({
width: { size: 9360, type: WidthType.DXA },
columnWidths: [3000, 6360],
rows: [
["$101 billion", "Pakistan's estimated energy transition investment need (to 2030)"],
["$36 billion+", "Annual remittances to Pakistan — primary USD1 stablecoin use case"],
["$2 billion", "Binance MOU value — tokenization of sovereign bonds & commodity reserves"],
["40 million", "Estimated crypto users in Pakistan"],
["30%", "Share of solar in Pakistan's power mix (up from 0% in 6 years)"],
["60%", "Pakistan's 2030 renewable energy target"],
["9th globally", "Pakistan's rank in global crypto adoption (Chainalysis index)"],
["AED 18.5M+", "PRYPCO Mint Phase 1 tokenized investments (50+ nationalities)"],
].map(([num, desc], i) =>
new TableRow({
children: [
new TableCell({ borders, width: { size: 3000, type: WidthType.DXA }, shading: { fill: i % 2 === 0 ? "1A5276" : "2471A3", type: ShadingType.CLEAR }, margins: { top: 80, bottom: 80, left: 120, right: 120 },
children: [new Paragraph({ alignment: AlignmentType.CENTER, children: [new TextRun({ text: num, bold: true, size: 24, color: "FFFFFF", font: "Arial" })] })] }),
new TableCell({ borders, width: { size: 6360, type: WidthType.DXA }, shading: { fill: i % 2 === 0 ? lightBlue : white, type: ShadingType.CLEAR }, margins: { top: 80, bottom: 80, left: 120, right: 120 },
children: [new Paragraph({ children: [new TextRun({ text: desc, size: 20, font: "Arial" })] })] }),
]
})
)
}),

new Paragraph({ children: [new TextRun("")], spacing: { before: 200 } }),

// FOOTER NOTE
new Table({
width: { size: 9360, type: WidthType.DXA },
columnWidths: [9360],
rows: [new TableRow({
children: [new TableCell({
borders,
width: { size: 9360, type: WidthType.DXA },
shading: { fill: "F2F3F4", type: ShadingType.CLEAR },
margins: { top: 120, bottom: 120, left: 160, right: 160 },
children: [
new Paragraph({ children: [new TextRun({ text: "Prepared by Claude (Anthropic) — Chat Session Summary for Continuity", bold: true, size: 18, font: "Arial", color: "555555" })] }),
new Paragraph({ children: [new TextRun({ text: "This document summarises a strategic advisory conversation regarding Pakistan's Ministry of Finance, national asset holding company governance, and the intersection of digital finance, clean energy, and sustainable agriculture. All deal details sourced from verified news reports (Dawn, Reuters, CoinTelegraph, WRI, CNN) as of March 4, 2026.", size: 16, font: "Arial", color: "777777" })] }),
]
})]
})]
}),

]
}]
});

Packer.toBuffer(doc).then(buffer => {
fs.writeFileSync('/home/claude/pakistan_strategy_chat_summary.docx', buffer);
console.log('Done');
});

← future tokeniztion build and newworld education final and nixor and city proposal docsNewWorldEdu — Master Handoff Summary →
Two years of working thought, indexed.
Ask me to present it in your conference room — WhatsApp +971 55 623 9111
Book Session →