惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

P
Proofpoint News Feed
C
CERT Recently Published Vulnerability Notes
O
OpenAI News
V
Vulnerabilities – Threatpost
C
Cybersecurity and Infrastructure Security Agency CISA
S
Schneier on Security
Latest news
Latest news
F
Full Disclosure
T
Tenable Blog
T
Troy Hunt's Blog
The Last Watchdog
The Last Watchdog
S
Secure Thoughts
L
LangChain Blog
有赞技术团队
有赞技术团队
Project Zero
Project Zero
Cloudbric
Cloudbric
爱范儿
爱范儿
GbyAI
GbyAI
C
CXSECURITY Database RSS Feed - CXSecurity.com
T
The Exploit Database - CXSecurity.com
S
Security @ Cisco Blogs
Hugging Face - Blog
Hugging Face - Blog
Recorded Future
Recorded Future
大猫的无限游戏
大猫的无限游戏
Last Week in AI
Last Week in AI
C
Cisco Blogs
WordPress大学
WordPress大学
Apple Machine Learning Research
Apple Machine Learning Research
小众软件
小众软件
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
V2EX - 技术
V2EX - 技术
Engineering at Meta
Engineering at Meta
Spread Privacy
Spread Privacy
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
Hacker News: Ask HN
Hacker News: Ask HN
Recent Commits to openclaw:main
Recent Commits to openclaw:main
Schneier on Security
Schneier on Security
T
Threat Research - Cisco Blogs
M
MIT News - Artificial intelligence
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
K
Kaspersky official blog
The Hacker News
The Hacker News
V
V2EX
F
Fortinet All Blogs
L
LINUX DO - 最新话题
Cisco Talos Blog
Cisco Talos Blog
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
N
News | PayPal Newsroom
博客园 - 三生石上(FineUI控件)
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org

freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More

Learn Command Line Interface (CLI) Development with Dart: From Zero to a Fully Published Developer Tool How to Bypass Cloud SMTP Restrictions Using Brevo and HTTP APIs How to Build a Live Options Database in Python – A Complete Guide How to Migrate to S3 Native State Locking in Terraform How to Use SCons to Build Software Projects [Full Handbook] How to Run Open Source LLMs Locally and in the Cloud QuRT: The Real-Time OS Inside Your Phone's Processor [Full Handbook] The Real Infrastructure Behind Remote Work (It’s Not Just Wi-Fi) The Lithography Handbook: Machines, Markets, and the Next Wave of Semiconductor Startups ITCM vs DTCM vs DDR: Embedded Memory Types Explained [Full Handbook] AI Paper Review: Improving Language Understanding by Generative Pre-Training (GPT-1) How to Build a Market Research Copilot with MCP and Python [Full Handbook] How to Build a Scoped Note-Taking API with Django Rest Framework and SimpleJWT The Complete SOC 2 Type II Implementation Handbook for Engineers: A Month-by-Month Roadmap with Real Commands Mastering the JavaScript Event Loop Data Science Insights: Why the Mean Lies When Handling Messy Retail Data How to Build High-Ranking SEO Landing Page How to Query Data in DynamoDB Using .Net How to Unblock Your AI PR Review Bottleneck: A Tech Lead’s Guide to Building a Codebase-Aware Reviewer How to Navigate Microservices as a Frontend Engineer How to Compress PDF Files in the Browser Using JavaScript (Step-by-Step) Stanford's youngest instructor talks InfoSec, AI, and catching cheaters - Rachel Fernandez interview [Podcast #217] Product Experimentation with Propensity Scores: Causal Inference for LLM-Based Features in Python How to Build a Multi-Agent AI System with LangGraph, MCP, and A2A [Full Book] How to Land Your First Cloud or DevOps Role: What Hiring Managers Actually Look For How to Deploy a Serverless Spam Classifier Using Scikit-Learn, AWS Lambda, & API Gateway How to Dockerize a Go Application – Full Step-by-Step Walkthrough Learn Hardware, Cloud, DevOps, Networking, Security, Databases, DNS, Git, and Linux Inside TreeHacks 2026, Stanford’s Elite Student Hakc Inside Stanford’s Elite Student Hackathon [Full Documentary] How to Measure Your AI Citation Rate Across ChatGPT, Perplexity, and Claude How to Deploy a Full-Stack Next.js App on Cloudflare Workers with GitHub Actions CI/CD How to Build a Multi-Tenant SaaS Platform with Next.js, Express, and Prisma How I Completed 15 freeCodeCamp Certifications in 4 Months: A Structured Learning Journey How to Build an Agentic Terminal Workflow with GitHub Copilot CLI and MCP Servers How AI Changed the Economics of Writing Clean Code How to Apply STRIDE Threat Modeling and SonarQube Analysis for Secure Software Development How to Set Up OpenID Connect (OIDC) in GitHub Actions for AWS How to Split PDF Files in the Browser Using JavaScript (Step-by-Step) How to Build Your Own Language-Specific LLM [Full Handbook] How to Build a Self-Learning RAG System with Knowledge Reflection How to Trace Multi-Agent AI Swarms with Jaeger v2 How I Tested Malaysia's Open Data Portals with Plain English How I Built a Production-Ready CI/CD Pipeline for a Monorepo-Based Microservices System with Jenkins, Docker Compose, and Traefik The Hidden Tax of Infrastructure: Why Your Team Shouldn’t Be Running It Anymore From Metrics to Meaning: How PaaS Helps Developers Understand Production From Symptoms to Root Cause: How to Use the 5 Whys Technique Product Experimentation for AI Rollouts: Why A/B Testing Breaks and How Difference-in-Differences in Python Fixes It How to Create a GPU-Optimized Machine Image with HashiCorp Packer on GCP 3D Web Development with Blender and Three.js How to Fix a Failing GitHub PR: Debugging CI, Lint Errors, and Build Errors Step by Step How to Merge PDF Files in the Browser Using JavaScript (Step-by-Step) How to Handle Stripe Webhooks Reliably with Background Jobs How to Build an Automatic Knowledge Graph for Your Blog with PHP and JSON-LD Understanding Proxies and Reverse Proxies: Your Gateway to Secure Networking The Evolution of Nvidia Blackwell GPU Memory Architecture How to Use PostgreSQL as a Cache, Queue, and Search Engine The New Definition of Software Engineering in the Age of AI Reclaim Your Time – Master Automation with Zapier How to Create Dynamic Emails in Go with React Email Why Many Beginner Self-Taught Developers Struggle (And What to Do About It) How to Build a Headless WordPress Frontend with Astro SSR on Cloudflare Pages How to Make Your GitHub Profile Stand Out How to Use Context Hub (chub) to Build a Companion Relevance Engine Why Chrome OS Is the Operating System the AI Era Was Built For How to Build Microservices-Based REST APIs for Healthcare Portals How to friction-max your learning with software engineer Jessica Rose [Podcast #216] Shadow AI Explained: Why Employees Are Using AI Behind Your Back Traditional Scraping vs AI Scraping: A Practical Guide for Developers and Data Teams How Database Indexes Work – A Practical Guide with PostgreSQL Examples How to Streamline Search in Web Applications with Elasticsearch How to Build an Open Source Data Lake for Batch Ingestion OpenAI Codex Essentials – AI Assisted Agentic Development Course Learn Software System Design How to Get Started with Terraform Service-to-Service Communication: When to Use REST, gRPC, and Event-Driven Messaging A Developer’s Guide to Lazy Loading in React and Next.js The Data Quality Handbook: Data Errors, the Developer's Role, and Validation Layers Explained. United States Residential Proxy: Why Local IP Accuracy Matters for SERP, Ads, and Pricing How to Build a Fashion App That Helps You Organize Your Wardrobe How to Build an Admin Dashboard Sidebar with shadcn/ui and Base UI The AI Governance Handbook: How to Build Responsible AI Systems That Actually Ship How to Build a Local DevOps HomeLab with Docker, Kubernetes, and Ansible How to Use Mixins in Flutter [Full Handbook] How to Prep for Technical Interviews – A Guide for Web Developers GPT-5.4 vs GLM-5: Is Open Source Finally Matching Proprietary AI? Data Visualization Tools for Svelte Developers How to Keep Human Experts Visible in Your AI-Assisted Codebase Efficient Data Processing in Python: Batch vs Streaming Pipelines Explained How to Build and Deploy Multi-Architecture Docker Apps on Google Cloud Using ARM Nodes (Without QEMU) How to Build a Secure AI PR Reviewer with Claude, GitHub Actions, and JavaScript How to Build a Positioning-Based Crude Oil Strategy in Python [Full Handbook] How to learn programming and CS in the AI hype era – interview with dev and prof Mark Mahoney [Podcast #215] CUDA Programming for NVIDIA H100s How to Build Reliable AI Systems. How to Build an Online Marketplace with Next.js, Express, and Stripe Connect How to Build a Cost-Efficient AI Agent with Tiered Model Routing The WebCodecs Handbook: Native Video Processing in the Browser The Bluetooth LE Audio Handbook: From "Why Does My Call Sound Like a Tin Can?" to AOSP Implementation How to Set Up OpenClaw and Design an A2A Plugin Bridge
How to Generate PDF Files in the Browser Using JavaScript (With a Real Invoice Example)
2026-04-16 · via freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
How to Generate PDF Files in the Browser Using JavaScript (With a Real Invoice Example)

Generating PDF files is something most developers eventually need to do. Whether it’s invoices, reports, or downloadable documents, PDFs are still one of the most widely used formats.

The usual approach involves backend services. You send data to a server, generate the file there, and return it to the user. It works, but it adds complexity, latency, and maintenance overhead.

Modern browsers make this much simpler.

In this tutorial, you’ll learn how to generate PDF files directly in the browser using JavaScript. There’s no server involved, no file uploads, and everything happens instantly on the client side.

To make things practical, we’ll build a simple invoice-style PDF generator so you can see how this works in a real-world scenario.

Table of Contents

  1. How PDF Generation Works in the Browser

  2. Project Setup

  3. What Library Are We Using?

  4. Creating the HTML Structure

  5. Adding JavaScript to Generate the PDF

  6. How the PDF Is Created

  7. Handling Dynamic Content (Important)

  8. Improving Layout and Spacing

  9. How to Download the PDF

  10. Important Notes from Real-World Use

  11. Common Mistakes to Avoid

  12. Demo: How the PDF Generator Works

  13. Conclusion

How PDF Generation Works in the Browser

A PDF is essentially a structured document that defines how text and elements are positioned on a page.

Instead of manually constructing that structure, we use a JavaScript library that handles it for us. You pass content into the library, and it generates a downloadable file.

The key advantage here is that everything runs locally. This makes the process faster and avoids sending any data to a server.

Project Setup

This project is intentionally simple.

You only need an HTML file and a JavaScript file. There’s no backend, no API, and no database involved. This keeps the focus on understanding how PDF generation works inside the browser.

What Library Are We Using?

We’ll use jsPDF, a lightweight library that allows you to create PDF files directly in JavaScript.

Add it using a CDN:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>

Creating the HTML Structure

We’ll start with a simple interface where users can enter invoice data and generate a PDF.

<input type="text" id="title" placeholder="Invoice Title">
<textarea id="content" placeholder="Enter invoice details"></textarea>
<button onclick="generatePDF()">Generate PDF</button>

This creates a basic input flow where users can provide the title and content for the PDF.

In real-world applications, this input could include more structured data like customer details, item lists, and pricing. But for this tutorial, we’ll keep things simple and focus on how the PDF generation works.

Now we connect the inputs to the PDF logic.

function generatePDF() {
  const { jsPDF } = window.jspdf;
  const doc = new jsPDF();

  const title = document.getElementById("title").value;
  const content = document.getElementById("content").value;

  if (!title.trim() && !content.trim()) {
    alert("Please enter valid content before generating the PDF.");
    return;
  }

  const margin = 10;
  let y = 20;

  const pageWidth = doc.internal.pageSize.getWidth();
  const pageHeight = doc.internal.pageSize.getHeight();
  const maxWidth = pageWidth - margin * 2;

  doc.setFontSize(18);

  // ✅ Wrap title
  const titleLines = doc.splitTextToSize(title, maxWidth);
  doc.text(titleLines, margin, y);

  const titleLineHeight = doc.getLineHeight() / doc.internal.scaleFactor;
  y += titleLines.length * titleLineHeight + 5;

  doc.setFontSize(12);

  // ✅ Wrap content
  const lines = doc.splitTextToSize(content, maxWidth);

  const lineHeight = doc.getLineHeight() / doc.internal.scaleFactor;

  lines.forEach((line) => {
    // ✅ Page break
    if (y > pageHeight - margin) {
      doc.addPage();
      y = margin;
    }

    doc.text(line, margin, y);
    y += lineHeight;
  });

  doc.save("invoice.pdf");
}

This creates a PDF directly in the browser. It handles long text, maintains proper spacing, and automatically adds new pages if the content exceeds the page height.

How the PDF Is Created

When you initialize jsPDF, it creates a blank document.

Each text() call places content at a specific coordinate. This gives you full control over layout, but it also means you need to manage spacing carefully.

Finally, calling save() converts everything into a downloadable file.

Handling Dynamic Content (Important)

In real-world use cases like invoices, content length is rarely fixed. If a user enters multiple lines or longer text, it can overflow or go outside the page.

To handle this, you should wrap text based on the page width instead of using fixed values.

const pageWidth = doc.internal.pageSize.getWidth();
const margin = 10;
const maxWidth = pageWidth - margin * 2;

const lines = doc.splitTextToSize(content, maxWidth);
doc.text(lines, margin, 40);

This ensures your content wraps properly and fits within the page.

If the content is long, you should also update spacing dynamically:

const lineHeight = doc.getLineHeight() / doc.internal.scaleFactor;
let y = 40;

lines.forEach((line) => {
  doc.text(line, margin, y);
  y += lineHeight;
});

This keeps the layout readable and prevents overlapping when working with dynamic input.

Improving Layout and Spacing

Good layout makes a big difference in how your PDF looks and feels.

Instead of placing everything at fixed positions, you can gradually adjust the Y position as content grows. This helps prevent overlapping and keeps the document visually structured.

For example, instead of hardcoding positions, you can do something like this:

const margin = 10;
let y = 20;

const pageWidth = doc.internal.pageSize.getWidth();
const maxWidth = pageWidth - margin * 2;

doc.setFontSize(18);

// Wrap title
const titleLines = doc.splitTextToSize(title, maxWidth);
doc.text(titleLines, margin, y);

const lineHeight = doc.getLineHeight() / doc.internal.scaleFactor;
y += titleLines.length * lineHeight + 5;

doc.setFontSize(12);

// Wrap content
const lines = doc.splitTextToSize(content, maxWidth);
doc.text(lines, margin, y);

y += lines.length * lineHeight;

Here, the y value increases based on actual content height instead of fixed spacing. This ensures consistent spacing between elements and avoids overlapping.

Another important issue is handling long text. If content is too long, it can go outside the page width or overlap with other elements. Instead of using fixed values, you should always calculate width dynamically:

const pageWidth = doc.internal.pageSize.getWidth();
const maxWidth = pageWidth - margin * 2;

const lines = doc.splitTextToSize(content, maxWidth);
doc.text(lines, margin, y);

This automatically breaks the text into multiple lines so it fits properly within the page.

Using dynamic spacing and text wrapping together ensures that your layout remains clean and readable, even when the content size changes. This becomes especially important when generating documents like invoices, where multiple sections need consistent alignment.

How to Download the PDF

The download process is handled using the save() method:

doc.save("invoice.pdf");

This tells the browser to generate the PDF and download it instantly.

You can also customize the file name dynamically based on user input:

const fileName = (title || "document").trim() + ".pdf";
doc.save(fileName);

This makes the downloaded file more meaningful instead of always using a fixed name.

Since everything runs in the browser, no server is involved and no data is uploaded. This makes the process fast and keeps user data private.

Important Notes from Real-World Use

When building tools like invoice generators, layout control becomes more important than the logic itself.

In a browser, layouts are flexible. But in a PDF, everything is fixed. That means you need to carefully control spacing, positioning, and readability.

For example, if you add multiple sections without adjusting spacing, content can easily overlap. Instead of using fixed positions, it’s better to update the Y position dynamically as content grows:

let y = 20;

doc.text("Invoice Title", 10, y);
y += 10;

doc.text("Customer Name", 10, y);
y += 10;

This ensures each section appears below the previous one without overlapping.

Another common issue is long content. If text is too long, it won’t automatically wrap like it does in HTML. You need to handle this manually using dynamic width:

const pageWidth = doc.internal.pageSize.getWidth();
const margin = 10;
const maxWidth = pageWidth - margin * 2;

const lines = doc.splitTextToSize(content, maxWidth);
doc.text(lines, margin, y);

const lineHeight = doc.getLineHeight() / doc.internal.scaleFactor;
y += lines.length * lineHeight;

This keeps the text readable and ensures it fits within the page.

You also need to think about how screen inputs translate into a fixed-size document. For example, a long description in a textarea may look fine on screen, but in a PDF it needs proper spacing, wrapping, and sometimes even pagination.

Optimizing PDF Generation Performance

Performance is another important factor. Generating large PDFs with a lot of content can slow down rendering in the browser.

One simple approach is to limit input size:

if (content.length > 2000) {
  alert("Content is too large. Consider splitting it into multiple sections.");
  return;
}

Another approach is to split content across multiple pages instead of forcing everything onto one page:

const pageHeight = doc.internal.pageSize.getHeight();
const lineHeight = doc.getLineHeight() / doc.internal.scaleFactor;

lines.forEach((line) => {
  if (y > pageHeight - margin) {
    doc.addPage();
    y = margin;
  }

  doc.text(line, margin, y);
  y += lineHeight;
});

This ensures large content is handled efficiently without breaking layout or performance.

In real-world tools, small decisions like spacing, wrapping, pagination, and content limits make a big difference in how usable and professional your generated PDFs feel.

Common Mistakes to Avoid

One common issue is skipping validation. If users generate a PDF with empty fields, the result won’t be useful.

To avoid this, always validate input properly and handle whitespace:

if (!title.trim() && !content.trim()) {
  alert("Please enter valid content before generating the PDF.");
  return;
}

This ensures users don’t download empty or broken PDFs.

Another mistake is ignoring text overflow. In a browser, text wraps automatically, but in a PDF it does not. Without handling this, long content can overlap or go outside the page.

You can fix this using dynamic text wrapping:

const pageWidth = doc.internal.pageSize.getWidth();
const margin = 10;
const maxWidth = pageWidth - margin * 2;

const lines = doc.splitTextToSize(content, maxWidth);
doc.text(lines, margin, 40);

This keeps the content inside the page and improves readability.

A related issue is overlapping content caused by fixed positioning. If you place everything at static coordinates, sections can stack on top of each other.

Instead, update positions dynamically:

let y = 20;

doc.text(title, 10, y);
y += 10;

const lines = doc.splitTextToSize(content, maxWidth);
doc.text(lines, 10, y);

const lineHeight = doc.getLineHeight() / doc.internal.scaleFactor;
y += lines.length * lineHeight;

This keeps spacing consistent and prevents layout issues.

Finally, forgetting to load the jsPDF library properly will break the entire feature. If the script is missing or incorrect, the PDF won’t generate at all.

Always make sure the CDN is included correctly:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>

In practice, most issues come down to proper validation, dynamic spacing, and handling content size correctly. Fixing these early makes your PDF generator much more reliable.

Demo: How the PDF Generator Works

For this example, we’ll generate a simple invoice PDF to demonstrate how this works in a real-world scenario.

Step 1: Enter Company Details

Invoice generator form showing company information fields like company name, address, email, phone, and GST details

Start by entering your company details such as name, address, contact information, and other identifiers. This data will appear at the top of the generated invoice.

Step 2: Add Customer Information

Customer information section with fields for customer name, billing address, shipping address, and contact details

Next, fill in the customer details including billing and shipping addresses. This ensures the invoice is correctly assigned.

Step 3: Enter Invoice Details

Invoice details form showing invoice number, invoice date, due date, and additional notes fields

Provide invoice-specific details such as invoice number, dates, and any additional notes. These values help structure the document properly.

Step 4: Add Items to the Invoice

Invoice items section with multiple items, quantity, rate, tax, discount, and total calculation fields

Add the items or services included in the invoice. Each item can include quantity, pricing, tax, and discounts, which are automatically calculated.

Step 5: Configure Payment and Terms

Payment and terms section showing payment instructions, QR code option, terms and conditions, and signature fields

Define payment instructions, terms, and any additional conditions. This section ensures the invoice is complete and ready for real use.

Step 6: Preview the Generated Invoice

Live invoice preview displaying company details, customer info, item table, totals, and final invoice layout

The interface provides a live preview of the invoice so you can review everything before generating the PDF.

Step 7: Generate and Download the PDF

Quick stats and action buttons showing total amount, total tax, and generate PDF button

Finally, click the generate button to create and download the PDF instantly. The file is generated directly in the browser without any server interaction.

Conclusion

In this tutorial, you built a PDF generator using JavaScript that runs entirely in the browser.

More importantly, you learned how to think about building real tools using client-side capabilities. This approach reduces complexity, improves performance, and keeps user data private.

Once you understand this pattern, you can extend it to build more advanced tools like invoice systems, report generators, and document exporters.

And that’s where things start to get really interesting.



Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started