Search code examples
javascriptangulartypescriptpdf-generationjspdf

How to set custom font for PDF, which generated from html? jsPDF library [HTML; no using text method]


I added custom font (Poppins) in my html code and in jsPDF, using methods. Unfortunately, It doesn't work if I want generate PDF using only HTML code. There is no problem if I'm using text method to add text to pdf.

  • the newest jsPDF.

I tried find some clue but really, cant find any thing which help. Only answers with text methods.

My code:

  1. Poppins.js
import { jsPDF } from "jspdf"
var font = 'FONT_IN_BASE64'
var callAddFont = function () {
    this.addFileToVFS('Poppins-Regular-normal.ttf', font);
    this.addFont('Poppins-Regular-normal.ttf', 'Poppins', 'normal');
};
jsPDF.API.events.push(['addFonts', callAddFont])

  1. app.component.ts
import { Component, ElementRef, OnInit, ViewChild } from '@angular/core';
import { jsPDF } from "jspdf";
import '../assets/font/Poppins-Regular-normal.js'

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {

  @ViewChild('print', {static: false}) el!: ElementRef;


  generatePDF() {
    const doc = new jsPDF(
      'portrait',
      'pt',
      [595, 842],
      true
      );

    const source = window.document.getElementById('print');
    console.log(doc.getFontList()) //got Poppins in list
    
    doc.html(
      this.el.nativeElement, {
        callback: (doc) => {
          //doc.setLanguage("pl");
          doc.setFont('Poppins', 'normal');
          //doc.setTextColor('#ff99cc');
          //doc.text('Hello world! ŻÓŁĆ', 50, 100);
          doc.output('dataurlnewwindow');
        },
        width: 595,
        windowWidth: source!.offsetWidth
      }
    );
  }
}

Expected (HTML): expected result

Result (PDF): wrong result


Solution

  • The problem was assign font-family to wrong place. I had it on html tag but i should assign to printed div.

    from

    <div id="print" #print>
    

    to

    <div id="print" #print style="font-family: 'Poppins', sans-serif;">