How to Work with PDFs in JavaScript: Top Libraries, Examples, and Japanese Font Fixes

目次

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

The Importance of PDF Processing and the Role of JavaScript

In recent years, PDF has become an essential file format for both business and personal use. A wide range of documents—such as contracts, receipts, invoices, and reports—are commonly created in PDF format. As a result, techniques for automating PDF generation and editing are in demand across many development environments.

JavaScript is a programming language that runs directly in the browser and excels at dynamic client-side processing. By leveraging this characteristic, you can generate and edit PDF files efficiently. In particular, the ability to complete processing on the client side without going through a server has gained attention in recent years.

Benefits of PDF Processing with JavaScript

1. Reduced Server Load

Traditionally, PDF generation and editing have often been handled on the server side. However, by using JavaScript, processing can be completed entirely on the client side, significantly reducing the burden on the server.

2. Real-Time Processing

With JavaScript, it is possible to reflect user input into a PDF on the spot. For example, you can implement features such as converting form input into a PDF immediately and providing a download link.

3. Flexible Customization

By using JavaScript libraries, you can easily create highly customizable PDFs—such as inserting graphic elements and images, or specifying text formatting. In addition, since JavaScript works in most modern browsers, it is less likely to run into environment-dependent issues.

Concrete Examples by Use Case

1. Generating Business Documents

You can use it to build systems that automatically generate invoices or receipts and send them via email. It also contributes to operational efficiency because customized documents can be output instantly for each business partner.

2. Exporting Form Data

You can implement a feature that saves data entered in surveys or application forms in PDF format and registers it in a management system. This enables a smoother transition from paper-based document management to digital management.

3. Creating Reports and Materials

You can generate reports from dynamic data and output visually easy-to-understand materials that include charts and images. This can significantly reduce the time required to create documents for meetings and presentations.

Future Trends and Outlook

PDF processing technology in JavaScript is expected to continue evolving. In particular, the following two points are drawing attention.

  1. Stronger Cloud Integration As integration with cloud storage and databases becomes easier, demand is expected to grow for web apps that incorporate PDF generation and editing features.
  2. Improved Mobile Support As usability on smartphones and tablets becomes increasingly important, optimization of PDF generation features with responsive design in mind will likely progress.

2. Top 5 JavaScript Libraries for Working with PDFs (With a Comparison Table)

Why Choosing the Right PDF Library Matters in JavaScript

When generating or editing PDFs with JavaScript, selecting the right library is extremely important. With an appropriate library, development becomes more efficient, advanced customization becomes easier, and Japanese language support may also be possible. In this section, we introduce five major PDF processing libraries and compare their features and use cases.

1. PDF.js

Overview

PDF.js is an open-source PDF viewer library developed by Mozilla. It is primarily specialized in displaying PDFs and renders them directly in the browser.

Key Features

  • Display-focused: Specialized in rendering PDFs; it does not provide generation or editing features.
  • Compatibility: Runs using only HTML5 and JavaScript; no additional plugins are required.
  • Performance: Fast rendering and efficient handling of large numbers of pages.

Example Use Cases

  • Applications that provide a PDF viewer for e-books, contracts, and similar documents.

2. jsPDF

Overview

jsPDF is a lightweight library specialized in generating PDF files. It is well-suited for simple document creation because you can easily add text, images, and tables.

Key Features

  • PDF generation: Ideal for client-side PDF generation.
  • Extensibility: Functionality can be extended via plugins.
  • Japanese support: Requires font configuration, but support is possible.

Example Use Cases

  • Automatically generating receipts and invoices, or creating simple reports.

3. pdf-lib

Overview

pdf-lib is a feature-rich library that supports not only generation but also editing and merging. It also supports TypeScript, making it a great fit for modern development environments.

Key Features

  • Editing: Add text and images to existing PDFs.
  • Customization: Flexible font embedding and layout control.
  • Performance: Fast processing and suitable for handling large-scale data.

Example Use Cases

  • Creating fillable PDFs and generating reports from dynamic data.

4. pdfmake

Overview

pdfmake is a library that lets you specify layouts easily using a declarative API. It is ideal when you need complex designs or table layouts.

Key Features

  • Layout-focused: Makes it easy to create tables and apply styling.
  • Multilingual support: Basic Japanese fonts can be used.
  • JSON-based: Easy-to-handle data structures and strong for dynamic PDF generation.

Example Use Cases

  • Creating reports, catalogs, and documents that include tables.

5. html2pdf

Overview

html2pdf is a library that converts HTML elements directly into PDFs. It is suitable for turning pages designed with HTML and CSS into PDFs as-is.

Key Features

  • HTML-based: Generates PDFs while preserving HTML/CSS design.
  • Easy adoption: Simple output can be implemented quickly.
  • Responsive-friendly: Helps keep the appearance consistent on mobile devices.

Example Use Cases

  • Printing web pages or exporting PDFs with fixed layouts.

6. Comparison Table

LibraryViewingGenerationEditingJapanese SupportHighlights
PDF.jsYesNoNoYesSpecialized in viewing, fast rendering
jsPDFNoYesPartialPartialEasy PDF generation, extensible via plugins
pdf-libNoYesYesYesFeature-rich, supports editing, TypeScript-friendly
pdfmakeNoYesPartialPartialDeclarative API enables complex layouts
html2pdfNoYesNoYesHTML-based PDF generation, preserves design

Summary

JavaScript PDF libraries differ in purpose and strengths.

  • If you need a lightweight viewer focused only on rendering, choose PDF.js.
  • For simple PDF generation, jsPDF is a solid option.
  • If you need editing and more advanced features, go with pdf-lib.
  • For tables and custom layouts, pdfmake is a great fit.
  • If you want to preserve your HTML/CSS design as-is, html2pdf is convenient.

By selecting the right library for your needs, you can build efficient and flexible PDF processing workflows.

3. Implementation Examples: How to Generate and Edit PDFs with JavaScript

Introduction

With JavaScript, you can easily generate and edit PDF files on the client side. In this section, we provide concrete implementation examples using major libraries. Try running the code while referencing these examples.

1. Basic PDF Generation with jsPDF

Creating a PDF with Text Only

The following code generates a PDF file that contains simple text.

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

Key Points in the Code

  1. Creating an instance:
  • new jsPDF() creates a new PDF document.
  1. Adding text:
  • doc.text() places the string “Hello, PDF!” at the coordinates (10, 10).
  1. Saving:
  • doc.save() triggers a download with the filename “sample.pdf”.

Advanced Example: Adding an Image

To insert an image, use the following code.

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

2. PDF Editing with pdf-lib

Example: 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('Added text', { x: 50, y: 500, size: 20 });

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

Key Points in the Code

  1. Loading the PDF:
  • PDFDocument.load() loads an existing PDF.
  1. Editing:
  • drawText() adds text at any position you choose.
  1. Saving and downloading:
  • Save the edited PDF and download it.

3. Creating a Layout-Rich PDF with pdfmake

Example: Building a PDF with a Complex Layout

const docDefinition = {
  content: [
    { text: 'Report Title', style: 'header' },
    { text: 'Below is a sample table.' },
    {
      table: {
        body: [
          ['Item 1', 'Item 2', 'Item 3'],
          ['Data 1', 'Data 2', 'Data 3'],
          ['Data 4', 'Data 5', 'Data 6'],
        ],
      },
    },
  ],
  styles: {
    header: {
      fontSize: 18,
      bold: true,
      margin: [0, 0, 0, 10],
    },
  },
};
pdfMake.createPdf(docDefinition).download('sample-table.pdf');

Key Points in the Code

  1. Defining content:
  • Inside content, you can specify text and tables.
  1. Defining styles:
  • Use styles to define styling such as font size and bold text.
  1. Downloading:
  • The download() function downloads the generated PDF.

4. Implementing Japanese Support

Embedding Japanese Fonts (jsPDF)

const doc = new jsPDF();
doc.addFileToVFS('NotoSansJP-Regular.ttf', fontData);
doc.addFont('NotoSansJP-Regular.ttf', 'NotoSansJP', 'normal');
doc.setFont('NotoSansJP');
doc.text('Japanese support test', 10, 10);
doc.save("japanese-sample.pdf");

Summary

In this section, we introduced practical examples of PDF generation and editing using major libraries.

  • jsPDF: Makes it easy to generate simple PDFs and insert images.
  • pdf-lib: Supports editing existing PDFs and page operations, making it highly versatile.
  • pdfmake: Strong at tables and layout customization, and can support Japanese to some extent.

By leveraging these libraries, you can build flexible PDF processing solutions that meet a wide range of needs.

4. Handling Japanese Fonts and Troubleshooting

Introduction

When generating PDFs with JavaScript, handling Japanese fonts is a common challenge for many developers. In particular, issues such as Japanese characters (kanji, hiragana, katakana) not displaying correctly or text becoming garbled can occur. This section explains how to configure Japanese fonts and how to resolve common problems.

1. Common Japanese Font Issues and Their Causes

Why Font Embedding Is Necessary

PDFs containing only English text often display correctly with standard fonts, but Japanese fonts require special handling. This is due to the following reasons.

  • Japanese fonts include a large character set, so they are not included in many default fonts.
  • Depending on the JavaScript library, Japanese font support may be limited.
  • If you do not embed the font file, the PDF may display garbled text depending on the environment in which it is opened.

Typical Error Examples

  • Garbled text: The font is not recognized correctly, and characters appear as □ or ?.
  • Layout breaking: Line spacing or font size does not match what you intended.
  • Font loading errors: Custom font files fail to load correctly.

2. How to Support Japanese Fonts in jsPDF

Preparing the Font File

To embed Japanese fonts into a PDF, you need a TrueType font (.ttf). The following steps use the free font “Noto Sans JP” as an example.

  1. Download the font file: Download “Noto Sans JP” from Google Fonts.
  2. Convert to Base64: Use a tool to Base64-encode the font and convert it into a Base64 string.

Code Example

const doc = new jsPDF();
doc.addFileToVFS('NotoSansJP-Regular.ttf', fontData);
doc.addFont('NotoSansJP-Regular.ttf', 'NotoSansJP', 'normal');
doc.setFont('NotoSansJP');
doc.text('Hello, world!', 10, 10);
doc.save('japanese-sample.pdf');

Key Points in the Code

  1. Adding font data:
  • Use addFileToVFS to register Base64 font data in the virtual file system.
  1. Configuring the font:
  • Use addFont to define the font name and style.
  1. Drawing text:
  • Select the font with setFont before drawing text.

3. How to Support Japanese Fonts in pdfmake

Font Preparation and Configuration

pdfmake requires you to configure fonts explicitly. The following example shows a configuration using the “Roboto” font.

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

var docDefinition = {
  content: [
    { text: 'Japanese test', font: 'Roboto', fontSize: 14 },
    { text: 'Hello, World!', fontSize: 12 },
  ],
};

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

Key Notes

  • Defining font options:
  • You need to configure each font style separately.
  • Specifying the font:
  • By setting the font via the font option, Japanese can be displayed correctly.

4. Troubleshooting and Fixes

When Fonts Do Not Display Correctly

  • Cause: Font data is not loaded, or the encoding format is incorrect.
  • Fix:
  1. Verify that you embedded the font in Base64 format.
  2. Confirm that the font file is the correct format (.ttf).
  3. Check that the MIME type is appropriate (e.g., application/x-font-ttf).

When Layout Breaks

  • Cause: Incorrect line spacing or font size settings.
  • Fix:
  • Explicitly set lineHeight and fontSize.

When Text Becomes Garbled on Mobile Devices

  • Cause: The device does not have the font installed.
  • Fix:
  • Embed the font to eliminate external dependencies.

Summary

Japanese support is an unavoidable challenge in PDF generation and editing, but it can be solved by choosing the right library and configuring fonts properly.

  • jsPDF: Supports Base64 font embedding and fits simple document structures.
  • pdfmake: Supports complex layouts and styling, but requires careful font configuration.

Use these steps to resolve garbled text and font-related issues, and generate Japanese-compatible PDFs smoothly.

5. Advanced Techniques and Use-Case-Based Solutions

Introduction

JavaScript PDF libraries support not only basic generation and editing, but also more advanced and practical requirements. In this section, we introduce advanced techniques such as database integration and dynamic PDF generation, and explain concrete solutions for specific use cases.

1. Generating PDFs with Dynamic Data

Dynamically Creating Reports from JSON Data

The following example generates a PDF report with a table based on JSON data.

const doc = new jsPDF();
const data = [
  { name: "Taro Yamada", age: 30, job: "Engineer" },
  { name: "Hanako Sato", age: 25, job: "Designer" },
  { name: "Ichiro Tanaka", age: 40, job: "Manager" },
];
doc.text('User Report', 10, 10);
doc.autoTable({
  head: [['Name', 'Age', 'Occupation']],
  body: data.map(item => [item.name, item.age, item.job]),
});
doc.save('report.pdf');

Key Points

  • Dynamic data: Generate array data from JSON and automatically convert it into a table.
  • Layout management: Use the autoTable plugin to easily create data tables.

2. Merging and Splitting Existing 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

  • Multi-page processing: Copy pages from each PDF and combine them into one file.
  • Flexible handling: You can modify layout or content on a per-page basis.

3. Creating PDF Forms and Filling Data

Adding Editable Form 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('Enter your name');
  nameField.addToPage(page, { x: 50, y: 600, width: 300, height: 30 });

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

Key Points

  • Dynamic forms: Easily add forms that users can fill out.
  • Data integration: Form data can be read and reused in subsequent processing.

4. Custom Design and Layout Adjustments

Creating Custom Headers and Footers (pdfmake)

const docDefinition = {
  header: { text: 'Report Header', alignment: 'center', margin: [0, 10, 0, 0] },
  footer: function(currentPage, pageCount) {
    return { text: `${currentPage} / ${pageCount}`, alignment: 'right', margin: [0, 0, 10, 0] };
  },
  content: [
    { text: 'Report Body', fontSize: 12 },
  ],
};
pdfMake.createPdf(docDefinition).download('custom-layout.pdf');

Key Points

  • Headers and footers: Insert fixed elements such as page numbers and logos.
  • Layout flexibility: Fine-grained styling allows you to reflect brand identity.

5. Mobile Support and Responsive Design

Generating PDFs from HTML with html2pdf

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

Key Points

  • Easy integration: Low learning cost because existing HTML structures can be reused.
  • Responsive-friendly: Suitable for smartphones and tablets.

Summary

By leveraging advanced techniques, the possibilities of PDF handling with JavaScript expand even further.

  • Database integration: Dynamic PDF generation using JSON and external data.
  • Editing, merging, and splitting: Flexible PDF manipulation with pdf-lib.
  • Form creation: Efficient data collection using fillable PDFs.
  • Design optimization: Easily implement complex layouts with pdfmake and html2pdf.

Use these techniques to build highly practical PDF generation and editing features.

6. Frequently Asked Questions (FAQ)

Introduction

When generating and editing PDFs with JavaScript, a wide range of questions can arise—from beginners to advanced users. This section summarizes common questions and their solutions to help you resolve issues during development.

1. Questions About Basic Operations

Q1. Which library is recommended for generating PDFs with JavaScript?

A: Choose a library based on your purpose.

  • Simple PDF generation: jsPDF is ideal and allows easy insertion of text and images.
  • Editing and merging: pdf-lib supports editing existing PDFs and creating forms.
  • Complex layouts and tables: pdfmake is convenient for highly designed documents.
  • Generating PDFs from HTML: html2pdf is suitable when you want to preserve CSS design.

Q2. How can I display Japanese fonts correctly?

A: Japanese fonts are not supported by default, so follow these steps.

  1. Prepare font files: Use Japanese-compatible fonts such as Noto Sans JP or IPA fonts.
  2. Convert to Base64: Convert the font file into Base64 format.
  3. Embed in the library: In jsPDF, use addFileToVFS() and addFont().
  4. Set the font: Select the font using setFont() before rendering text.

Q3. Why does text become garbled on mobile devices?

A: Mobile devices often have different font environments from PCs, so garbled text can occur if fonts are not embedded.

Solution:

  • Create PDFs with embedded fonts to remove external dependencies.
  • Test PDFs on mobile devices in advance.

Q4. How can I add a signature to a PDF?

A: With pdf-lib, you can add signature areas using images or drawing tools.

const imgData = 'data:image/png;base64,...';
page.drawImage(imgData, {
  x: 50,
  y: 100,
  width: 200,
  height: 100,
});

You can also create form fields for handwritten signatures inside the PDF.

2. Questions About Advanced Features

Q5. Can I insert dynamic QR codes into a PDF?

A: Yes, it is possible. The following example inserts a QR code using jsPDF.

const qrCode = new QRCode(document.createElement('div'), {
  text: "https://example.com",
  width: 100,
  height: 100,
});

const qrImg = qrCode._oDrawing._elImage.src;
doc.addImage(qrImg, 'PNG', 10, 10, 50, 50);
doc.save('qrcode-sample.pdf');

Q6. How can I reflect HTML form content in a PDF?

A: By using html2pdf, you can convert HTML elements directly into a PDF.

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

This approach also reflects CSS styling, making it suitable for visually rich PDFs.

Summary

While handling PDFs with JavaScript can raise various questions and challenges, many issues can be resolved by choosing the right library and configuration.

We hope this FAQ helps you troubleshoot and solve problems during real-world development.

7. Conclusion

Introduction

In this article, we explored techniques and implementation methods for generating and editing PDFs with JavaScript in detail. We covered everything from basic operations to advanced techniques, including comparisons of major libraries and key points for Japanese language support. In this section, we review the entire article and summarize the main takeaways.

1. Convenience and Key Characteristics of Handling PDFs with JavaScript

Because JavaScript runs on the client side, it offers the advantage of generating and editing PDF files in real time. Its flexibility—allowing dynamic data processing and design customization while reducing server load—is highly valued in modern development environments.

Main benefits:

  • Reduced server dependency and improved response times.
  • Interactive features such as real-time previews and form generation.
  • Low environment dependency and compatibility with most modern browsers.

2. Library-Specific Features and How to Choose the Right Tool

This article introduced five major JavaScript libraries. Their characteristics can be summarized as follows.

LibraryKey FeaturesRecommended Use Cases
PDF.jsSpecialized PDF viewer; no editing features.Applications focused solely on PDF viewing.
jsPDFLightweight and easy PDF generation.Creating simple PDFs with text and images.
pdf-libFeature-rich, supports editing and page manipulation.Dynamic forms, editing existing PDFs, advanced customization.
pdfmakeStrong layout and table generation capabilities.Complexly designed PDFs such as reports and catalogs.
html2pdfDirect conversion of HTML and CSS into PDFs.Preserving web page designs for PDF output and printing.

3. Review of the Implementation Examples

Through practical code examples, we demonstrated how to address a wide variety of requirements.

Main features covered:

  1. Basic PDF generation: Creating PDFs that include text and images.
  2. Using dynamic data: Automatically generating reports and documents from JSON data.
  3. Editing existing PDFs: Merging, splitting pages, and adding form fields.
  4. Japanese language support: Font embedding and preventing garbled text.
  5. Custom design: Layout control, headers, and footers.

These examples are designed to be useful for developers ranging from beginners to advanced users.

4. Future Outlook and Expectations for Emerging Technologies

PDF handling with JavaScript is expected to continue evolving in the future.

Key trends to watch:

  1. Stronger cloud integration: Easier integration with serverless environments and cloud storage.
  2. AI-assisted generation: AI support for dynamic design and automated report analysis.
  3. New libraries: The emergence of new libraries focused on performance and extensibility.

By keeping an eye on these trends and adopting new technologies, you can further improve development efficiency.

Final Summary

Techniques for handling PDFs with JavaScript are playing an increasingly important role in web applications and business systems. By leveraging the libraries, implementation examples, and advanced techniques introduced in this article, you can build flexible and sophisticated PDF solutions.

Continue exploring new technologies and approaches to create more powerful and efficient PDF workflows.

広告