How to Generate and Edit PDF Files with JavaScript: Complete Guide, Libraries, and Practical Examples

目次

1. Introduction: Why Do We Need to Handle PDFs in JavaScript?

The Importance of PDF Processing and JavaScript’s Role

In recent years, PDF has become an indispensable file format in both business and personal use. Contracts, receipts, invoices, and reports are now commonly created in PDF format. As a result, the need to automate the creation and editing of PDF files has increased across many development environments. JavaScript runs directly in the browser and excels at dynamic client-side operations. Leveraging these capabilities makes it possible to efficiently generate and edit PDF files. In particular, the ability to process PDFs entirely on the client side—without involving a server—has gained significant attention.

Benefits of Using JavaScript for PDF Processing

1. Reduced Server Load

Traditionally, PDF generation and editing were handled on the server side. However, by using JavaScript, processing can be completed on the client side, greatly reducing the burden on servers.

2. Real-Time Processing

With JavaScript, user input can be immediately reflected in a PDF. For example, form data can be instantly converted into a PDF and provided as a download link.

3. High Flexibility and Customization

By using JavaScript libraries, you can easily create highly customizable PDFs with graphics, images, or formatted text. Because JavaScript works on most modern browsers, environment-specific issues are also minimized.

Practical Use Cases

1. Generating Business Documents

It can be used to automatically generate invoices and receipts, which can then be emailed. You can also instantly output documents customized for each client, improving efficiency.

2. Outputting Form Data

You can implement features that save survey or application form data as PDFs and register them in a management system. This helps transition from paper-based document handling to digital workflows.

3. Creating Reports and Presentation Materials

Reports can be generated dynamically based on data, including charts and images. This significantly reduces the time required to prepare materials for meetings or presentations.

Future Trends and Outlook

JavaScript-based PDF processing is expected to continue evolving. Two major trends are drawing attention:
  1. Stronger Cloud Integration Seamless integration with cloud storage or databases will increase demand for web apps with built-in PDF creation and editing.
  2. Improved Mobile Support As smartphone and tablet usability becomes more important, PDF generation optimized for responsive layouts will continue to advance.

2. Top 5 JavaScript PDF Libraries (With Comparison Table)

The Importance of Choosing the Right JavaScript PDF Library

Choosing the right library is crucial when generating or editing PDFs with JavaScript. A well-selected library boosts development efficiency and allows advanced customization, including Japanese text support. This section introduces five major PDF libraries and compares their features and use cases.

1. PDF.js

Overview

PDF.js is an open-source PDF viewer library developed by Mozilla. It specializes in PDF rendering inside the browser.

Features

  • Viewer-only: Focused purely on display; does not support PDF generation or editing.
  • High Compatibility: Works with only HTML5 and JavaScript—no plugins required.
  • High Performance: Fast rendering and efficient handling of large documents.

Use Cases

  • Applications that require PDF viewing, such as e-books or contracts.

2. jsPDF

Overview

jsPDF is a lightweight library primarily used for generating PDF files. It allows easy insertion of text, images, and tables, making it ideal for simple document creation.

Features

  • PDF Generation: Well-suited for client-side PDF creation.
  • Extensible: Supports plugins for additional features.
  • Japanese Support: Supported with font configuration.

Use Cases

  • Automatic generation of receipts, invoices, or simple reports.

3. pdf-lib

Overview

pdf-lib supports not only PDF generation but also editing and merging. It is compatible with TypeScript and integrates smoothly into modern development environments.

Features

  • Edit Capabilities: Add text or images to existing PDFs.
  • Flexible Customization: Offers font embedding and layout control.
  • High Performance: Efficient even for large-scale PDF operations.

Use Cases

  • Creating PDF forms or dynamic data reports.

4. pdfmake

Overview

pdfmake allows easy layout specification using a declarative API, making it ideal for complex designs and table layouts.

Features

  • Strong Layout Capabilities: Easy table and styling configuration.
  • Multilingual Support: Supports basic Japanese fonts.
  • JSON-Based: Easy to build dynamic documents.

Use Cases

  • Reports, catalogs, and documents containing tables.

5. html2pdf

Overview

html2pdf converts HTML elements directly into PDF files. It is ideal for generating PDFs based on existing web page designs.

Features

  • HTML-Based: Retains HTML/CSS design in PDF output.
  • Easy to Use: Quick setup for simple output.
  • Responsive Friendly: Maintains layout on mobile devices.

Use Cases

  • Print features for web pages or fixed-layout PDF output.

6. Comparison Table

LibraryViewerGenerateEditJapanese SupportKey Features
PDF.js××Focused on PDF viewing, fast rendering
jsPDF×Simple PDF creation, plugin extensibility
pdf-lib×Full-featured editing, TypeScript support
pdfmake×Powerful layout with declarative API
html2pdf××HTML-based easy PDF output

Summary

Each JavaScript PDF library has different strengths:
  • PDF.js: Best for viewing only.
  • jsPDF: Best for simple PDF generation.
  • pdf-lib: Ideal for editing or adding complex features.
  • pdfmake: Strong in table and custom layout design.
  • html2pdf: Best when you want to preserve HTML design.

3. Implementation Examples: Generating and Editing PDFs with JavaScript

Introduction

JavaScript enables easy client-side PDF generation and editing. This section introduces concrete implementations using major libraries. Try running these code samples to understand how they work.

1. Basic PDF Generation with jsPDF

Creating a Simple Text PDF

const doc = new jsPDF();
doc.text("Hello, PDF!", 10, 10);
doc.save("sample.pdf");

Key Points

  1. Create an instance:
  • new jsPDF() creates a new PDF document.
  1. Add text:
  • doc.text() places “Hello, PDF!” at coordinate (10, 10).
  1. Save PDF:
  • doc.save() downloads the PDF as “sample.pdf”.

Example: Adding an Image

const doc = new jsPDF();
const imgData = 'data:image/jpeg;base64,...';
doc.addImage(imgData, 'JPEG', 10, 40, 180, 160);
doc.save("image-sample.pdf");

2. Editing PDFs with pdf-lib

Adding Text to an Existing PDF

import { PDFDocument } from 'pdf-lib';

async function modifyPDF() {
  const url = 'sample.pdf';
  const existingPdfBytes = await fetch(url).then(res => res.arrayBuffer());
  const pdfDoc = await PDFDocument.load(existingPdfBytes);
  const pages = pdfDoc.getPages();
  const firstPage = pages[0];

  firstPage.drawText('追加されたテキスト', { x: 50, y: 500, size: 20 });

  const pdfBytes = await pdfDoc.save();
  download(pdfBytes, "modified-sample.pdf", "application/pdf");
}

Key Points

  1. Load PDF:
  • Use PDFDocument.load().
  1. Edit PDF:
  • drawText() adds text at the specified location.
  1. Save & download:
  • Save the edited PDF and download it.

3. Creating Layout-Heavy PDFs with pdfmake

Creating Complex Layouts

const docDefinition = {
  content: [
    { text: 'レポートタイトル', style: 'header' },
    { text: '以下はサンプル表です。' },
    {
      table: {
        body: [
          ['項目1', '項目2', '項目3'],
          ['データ1', 'データ2', 'データ3'],
          ['データ4', 'データ5', 'データ6'],
        ],
      },
    },
  ],
  styles: {
    header: {
      fontSize: 18,
      bold: true,
      margin: [0, 0, 0, 10],
    },
  },
};
pdfMake.createPdf(docDefinition).download('sample-table.pdf');

Key Points

  1. Define content: Tables and text are defined in content.
  2. Style definition: styles controls font and layout settings.
  3. Download: Use download() to output the PDF.

4. Japanese Font Support (jsPDF)

const doc = new jsPDF();
doc.addFileToVFS('NotoSansJP-Regular.ttf', fontData);
doc.addFont('NotoSansJP-Regular.ttf', 'NotoSansJP', 'normal');
doc.setFont('NotoSansJP');
doc.text('日本語対応テスト', 10, 10);
doc.save("japanese-sample.pdf");

Summary

This section introduced practical examples using major libraries:
  • jsPDF: Simple PDF creation and image insertion.
  • pdf-lib: Editing existing PDFs and page manipulation.
  • pdfmake: Strong table and layout customization, with partial Japanese support.

4. Handling Japanese Fonts & Troubleshooting

Introduction

When generating PDFs in JavaScript, handling Japanese fonts is one of the most common challenges. Issues such as unreadable characters or missing glyphs frequently occur. This section explains how to configure Japanese fonts correctly and how to troubleshoot common problems.

1. Common Issues with Japanese Fonts

Why Font Embedding Is Necessary

English-based PDFs are usually displayed correctly with default fonts, but Japanese requires special handling because:
  • Japanese fonts include many characters not available in default fonts.
  • Some libraries have limited Japanese font support.
  • Without embedding fonts, PDFs may display incorrectly depending on the environment.

Common Errors

  • Garbled characters: Shown as □ or ? due to missing font support.
  • Broken layout: Incorrect line spacing or font size.
  • Font loading errors: Custom font file cannot be loaded.

2. Japanese Font Handling in jsPDF

Preparing Font Files

To embed Japanese fonts, you need a TrueType (.ttf) font. Example: Noto Sans JP.
  1. Download: Get Noto Sans JP from Google Fonts.
  2. Convert to Base64: Convert the font file into a Base64 string.

Example Code

const doc = new jsPDF();
doc.addFileToVFS('NotoSansJP-Regular.ttf', fontData);
doc.addFont('NotoSansJP-Regular.ttf', 'NotoSansJP', 'normal');
doc.setFont('NotoSansJP');
doc.text('こんにちは、世界!', 10, 10);
doc.save('japanese-sample.pdf');

Explanation

  • addFileToVFS: Registers Base64 font data.
  • addFont: Defines the font name and style.
  • setFont: Applies the font.

3. Japanese Font Handling in pdfmake

Preparing and Setting Fonts

var fonts = {
  Roboto: {
    normal: 'Roboto-Regular.ttf',
    bold: 'Roboto-Bold.ttf',
    italics: 'Roboto-Italic.ttf',
    bolditalics: 'Roboto-BoldItalic.ttf',
  },
};

var docDefinition = {
  content: [
    { text: '日本語テスト', font: 'Roboto', fontSize: 14 },
    { text: 'Hello, World!', fontSize: 12 },
  ],
};

pdfMake.createPdf(docDefinition).download('japanese-sample.pdf');

Explanation

  • Each font style must be configured separately.
  • The font property is used to specify fonts in content.

4. Troubleshooting

Text Not Displaying Correctly

  • Possible Cause: Incorrect font file or Base64 conversion.
  • Solutions:
  1. Confirm Base64 embedding.
  2. Verify .ttf file integrity.
  3. Ensure MIME type is correct.

Broken Layout

  • Cause: Incorrect line spacing.
  • Solution: Manually define fontSize and lineHeight.

Mobile Encoding Issues

  • Cause: Device lacks Japanese fonts.
  • Solution: Always embed fonts.

Summary

  • jsPDF: Simple font embedding using Base64.
  • pdfmake: Strong layout control but requires detailed font configuration.

5. Advanced Techniques & Use Case Solutions

Introduction

PDF libraries in JavaScript can support advanced use cases such as dynamic PDF generation, database integration, custom layouts, and more.

1. Dynamic Data PDF Generation

Generate Reports from JSON

const doc = new jsPDF();
const data = [
  { 名前: "山田太郎", 年齢: 30, 職業: "エンジニア" },
  { 名前: "佐藤花子", 年齢: 25, 職業: "デザイナー" },
  { 名前: "田中一郎", 年齢: 40, 職業: "マネージャー" },
];
doc.text('ユーザーレポート', 10, 10);
doc.autoTable({
  head: [['名前', '年齢', '職業']],
  body: data.map(item => [item.名前, item.年齢, item.職業]),
});
doc.save('report.pdf');

Key Points

  • Dynamic Data: Convert JSON into table rows.
  • Layout Management: Use autoTable plugin for easy table creation.

2. Merging & Splitting PDFs

Merging Multiple PDFs (pdf-lib)

import { PDFDocument } from 'pdf-lib';

async function mergePDFs(pdfUrls) {
  const mergedPdf = await PDFDocument.create();

  for (let url of pdfUrls) {
    const existingPdf = await fetch(url).then(res => res.arrayBuffer());
    const pdfDoc = await PDFDocument.load(existingPdf);
    const copiedPages = await mergedPdf.copyPages(pdfDoc, pdfDoc.getPageIndices());
    copiedPages.forEach(page => mergedPdf.addPage(page));
  }

  const pdfBytes = await mergedPdf.save();
  download(pdfBytes, "merged.pdf", "application/pdf");
}

Key Points

  • Copy pages from multiple PDFs.
  • Merge into a single document.

3. PDF Form Fields

Creating Input Fields (pdf-lib)

import { PDFDocument } from 'pdf-lib';

async function createForm() {
  const pdfDoc = await PDFDocument.create();
  const page = pdfDoc.addPage([500, 700]);

  const form = pdfDoc.getForm();
  const nameField = form.createTextField('name');
  nameField.setText('名前を入力してください');
  nameField.addToPage(page, { x: 50, y: 600, width: 300, height: 30 });

  const pdfBytes = await pdfDoc.save();
  download(pdfBytes, "form.pdf", "application/pdf");
}

Key Points

  • Supports dynamic user input.
  • Field data can be used for further processing.

4. Custom Layouts

Header & Footer (pdfmake)

const docDefinition = {
  header: { text: 'レポートヘッダー', alignment: 'center', margin: [0, 10, 0, 0] },
  footer: function(currentPage, pageCount) {
    return { text: `${currentPage} / ${pageCount}`, alignment: 'right', margin: [0, 0, 10, 0] };
  },
  content: [
    { text: 'レポート本文', fontSize: 12 },
  ],
};
pdfMake.createPdf(docDefinition).download('custom-layout.pdf');

5. Mobile & Responsive Support

Generate PDF from HTML (html2pdf)

const element = document.getElementById('content');
html2pdf(element);

Summary

Key advanced techniques:
  • Dynamic data: Build PDFs from JSON.
  • Merging/editing: Use pdf-lib for advanced editing.
  • Form fields: Build interactive documents.
  • Custom design: Use pdfmake for layout-rich documents.

6. Frequently Asked Questions (FAQ)

Introduction

This section answers common questions that developers encounter when generating or editing PDFs in JavaScript.

1. Basic Operations

Q1. Which library is best for generating PDFs in JavaScript?

A: Choose based on your needs:
  • Simple PDF generation: jsPDF
  • Editing & merging: pdf-lib
  • Complex layouts: pdfmake
  • HTML-to-PDF: html2pdf

Q2. How do I display Japanese text correctly?

A: Follow these steps:
  1. Prepare a Japanese font (Noto Sans JP, IPA, etc.)
  2. Convert the font to Base64
  3. Embed it using addFileToVFS() and addFont()
  4. Select it using setFont()

Q3. Why does Japanese text break on mobile devices?

A: Mobile devices lack Japanese fonts. Solution: Always embed Japanese fonts.

Q4. How do I add a signature field?

A: You can insert a signature image using pdf-lib:
page.drawImage(imgData, {
  x: 50,
  y: 100,
  width: 200,
  height: 100,
});

2. Advanced Usage

Q5. Can I insert dynamic QR codes into PDFs?

A: Yes, using jsPDF.

Q6. Can I export HTML forms to PDF?

A: Yes, with html2pdf.

Summary

This FAQ should help you troubleshoot and optimize your JavaScript PDF workflow.

7. Conclusion

Introduction

This article provided an in-depth explanation of how to generate and edit PDFs using JavaScript, covering basic operations, advanced techniques, library comparisons, and Japanese font handling.

1. Convenience and Flexibility of JavaScript-based PDF Operations

JavaScript runs on the client side, enabling real-time PDF generation and editing. This reduces server load and supports interactive features.

Benefits:

  • Reduced server dependency
  • Real-time interaction and preview
  • High compatibility with modern browsers

2. Library Selection Summary

LibraryFeaturesBest Use Cases
PDF.jsViewer onlyPDF display apps
jsPDFSimple & lightweightText and image PDFs
pdf-libEditing, merging, form creationComplex dynamic PDFs
pdfmakeAdvanced layoutReports, catalogs
html2pdfHTML/CSS to PDFWeb-page PDF output

3. Implementation Examples Summary

  • Basic PDF creation
  • Dynamic data reports
  • Editing existing PDFs
  • Japanese font handling
  • Custom design & layout control

4. Future Outlook

The JavaScript PDF ecosystem will continue to evolve:
  1. Improved cloud integration
  2. AI-assisted document generation
  3. New libraries for speed and scalability

Conclusion

JavaScript is becoming increasingly essential for PDF processing in web apps and business systems. By leveraging the libraries and techniques discussed in this article, you can implement flexible and high-quality PDF solutions with ease.
広告