When working with jsPDF to generate PDFs containing Arabic text, you might encounter issues with character rendering. This post explains how to properly handle Arabic text in jsPDF.
The Challenge
Arabic text in PDFs requires proper UTF-8 encoding and right-to-left (RTL) support. By default, jsPDF might not render Arabic characters correctly, showing them as squares or disconnected letters.
Solution
To properly display Arabic text in jsPDF, we need to Include a font that supports Arabic characters like Amiri font
Here’s a working example:
Setup
First, install the required dependencies:
npm install jspdf jspdf-autotable
Font Preparation
Before implementing the PDF generation, we need to prepare the Arabic font:
- Download the Arabic font (e.g., Amiri-Regular.ttf)
- Go to jsPDF fontconverter
- Upload your .ttf file
- The converter will generate a JavaScript file containing your font as base64
- Save the generated JS file (e.g.,
amiri-normal.js
) - move generated file to the project assets folder (e.g.,
src/assets/fonts/amiri-normal.js
)
Angular Implementation
Font name you can get it from the generated JS file src/assets/fonts/amiri-normal.js
will see it inside the methoddoc.setFont("MyFont");
// pdf.service.ts
import { Injectable } from '@angular/core';
import { jsPDF } from 'jspdf';
// Import the generated font file
import 'src/assets/fonts/amiri-normal.js';
@Injectable({
providedIn: 'root'
})
export class PdfService {
constructor() { }
generateArabicPDF(): void {
const doc = new jsPDF();
// The font is already loaded via the import
doc.setFont('Amiri');
doc.setFontSize(16);
// Add Arabic content
const title = 'عنوان المستند';
doc.text(title, 200, 20, {
align: 'right'
});
doc.save('arabic-document.pdf');
}
}
Component Implementation
Create a component to use the PDF service:
// arabic-pdf.component.ts
import { Component } from '@angular/core';
import { PdfService } from './pdf.service';
@Component({
selector: 'app-arabic-pdf',
template: `
<button (click)="generatePDF()">Generate Arabic PDF</button>
`
})
export class ArabicPdfComponent {
constructor(private pdfService: PdfService) {}
generatePDF(): void {
this.pdfService.generateArabicPDF();
}
}
Important Notes
Font Loading:
- The fontconverter generates a self-contained JS file
- No need for HTTP requests or manual font loading
- Better performance as font is bundled with your application
Multiple Fonts:
- Convert each font variation (normal, bold, etc.) separately
- Import all needed font files in your service
File Size Consideration:
- Generated font files can be large
- Consider using subset fonts if you only need specific characters