Guide on utilizing "setFont" in jsPDF with UTF-8 encoding?

Currently working on a project using Angular 7

I am trying to incorporate a custom font (UTF-8) into my PDF generation service using jsPDF. Despite researching various examples, none seem to work for me. The documentation on the jsPDF GitHub page mentions utilizing UTF-8 / TTF fonts: https://github.com/MrRio/jsPDF

This indicates that it is possible to achieve this. Therefore, I created a file named 'font Roboto-regular.tff'. My question now is: where should I upload this file and how can I utilize it effectively in my project?

Answer №1

Here is a simple guide to create your own PDF:

  1. To start, you need to create a function called somePDFCreator. Inside this function, check the available fonts using console.log():
     import jsPDF from 'jspdf';

     function somePDFCreator() {
          const doc = new jsPDF();
          console.log(doc.getFontList());
        }
  1. The next step is to add a custom font file named font Roboto-regular.tff, which can be generated from this website: . Then, insert an IIFE js code block into the somePDFCreator function. Make sure to verify that your font is added successfully by checking the log.
    import jsPDF from 'jspdf';   

    function somePDFCreator() {
       (function (jsPDFAPI) { var font = 'AAEAAAAQAQAABAAAR......';
       var callAddFont = function () {
         this.addFileToVFS('Roboto-regular.tff', font);
         this.addFont('Roboto-regular.tff', 'Roboto-Regular', 'normal');
       };
       jsPDFAPI.events.push(['addFonts', callAddFont])
       })(jsPDF.API);


       const doc = new jsPDF();
       console.log(doc.getFontList());
    }
  1. Finally, utilize your imported font by setting it with
    doc.setFont('Roboto-Regular', 'normal');
    :
    import jsPDF from 'jspdf';   

    function somePDFCreator() {
       (function (jsPDFAPI) { var font = 'AAEAAAAQAQAABAAAR......';
       var callAddFont = function () {
         this.addFileToVFS('Roboto-regular.tff', font);
         this.addFont('Roboto-regular.tff', 'Roboto-Regular', 'normal');
       };
       jsPDFAPI.events.push(['addFonts', callAddFont])
       })(jsPDF.API);


       const doc = new jsPDF();
       console.log(doc.getFontList());

       doc.setFont('Roboto-Regular', 'normal');
       doc.setFontSize(8);

       doc.text("Example text Lorem ipsum", 40, 25);
       return doc.save('myPdfFileName.pdf');
    }

Answer №2

Upon reviewing the documentation thoroughly, it specifies that you need to process your ttf file and incorporate the resulting js file into your application code.

The PDF's 14 standard fonts are restricted to the ASCII-codepage. To utilize UTF-8 characters, a custom font containing the required glyphs must be integrated. jsPDF supports .ttf files. Therefore, if you intend to include Chinese text in your PDF, ensure that your font includes the necessary Chinese glyphs; otherwise, it will display blank spaces instead of text.

To integrate the font into jsPDF, use our fontconverter located at /fontconverter/fontconverter.html. This tool will generate a js file with the content of the provided ttf file encoded as base64 strings, along with additional code for jsPDF. Simply add this generated js file to your project. Subsequently, you can employ the setFont method in your code to write UTF-8 encoded text seamlessly.

Reference: https://github.com/MrRio/jsPDF#use-of-utf-8--ttf

Trust this resolves any concerns you may have!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Arranging an array of arrays based on the mm/dd/yyyy date field

Currently, I am facing an issue while attempting to sort data obtained from an API by date in the client-side view. Here is an example of the data being received: address: "1212 Test Ave" address2: "" checkNumber : "" city: "La Grange" country: "" email: ...

Tips for Successfully Transmitting Information via Mat-Dialog

Having trouble passing data from a dialog back to the parent component. Specifically, I'm struggling with updating the value of an array in the `afterClosed` function. I've tried using `patchValue` and `setValue`, but it doesn't seem to be w ...

Top Recommendations: Comparing Standalone Components and Modules in Angular Version 14

I'm in need of some clarification on the most effective practices when it comes to utilizing standalone components and modules within Angular 14. With the introduction of standalone components as a new concept in Angular, I am seeking factual guidance ...

Error encountered with structured array of objects in React Typescript

What is the reason for typescript warning me about this specific line of code? <TimeSlots hours={[{ dayIndex: 1, day: 'monday', }]}/> Can you please explain how I can define a type in JSX? ...

The test failed to execute due to disconnection (0 occurrences) as no message was received within the 30000 ms timeframe

Currently, I am facing an issue with my Angular application. When I execute the "ng test" command, it displays an error message stating 'Disconnected (0 times), because no message in 30000 ms.' I have tried updating both karma and jasmine package ...

Angular 2's ng-bootstrap datepicker popup feature allows users to easily select

Greetings! I have been exploring the ng-bootstrap datepicker and managed to implement it successfully in my application after studying the demo code. However, when attempting to add more than one datepicker input tags, only one seems to be functioning pro ...

Angular auto suggest feature

I am working with a dropdown in Angular that contains JSON data. The data is stored in a List named options and I need to display the name field in the dropdown list. My current task involves implementing an autocomplete search feature for this dropdown. ...

The submit button is getting disrupted by the background image being set

Implement the following CSS code to set a background image on a single-page app (Angular). .page::before { content: ''; position: absolute; background-size: cover; width: 100%; height: 100%; background-image: url("../../assets/weird. ...

Tips for customizing the appearance of a specific mat-button component in an Angular project

In my Angular application, I have set up a scenario where users are presented with multiple choices through buttons. When a user clicks on a button, a specific component is displayed based on their choice. I am currently working on enhancing the styling of ...

Verifying whether the filter query will produce any matches

I'm currently working with a *ngIf statement and I need to show a specific message when the condition is not met. However, I'm facing difficulties in finding a way to achieve the opposite of the filtered result. Essentially, I want to display a m ...

Guide on executing a function exclusively when the state of a service variable changes within an Angular4 component

In my InfoFormService, I have a variable called isInValidating that is initially set to false. This variable becomes true when the component calls the validateEmail(email) function as shown below. @Injectable() export class InfoFormService { private ...

The method JSON.stringify is not properly converting the entire object to a string

JSON.stringify(this.workout) is not properly stringifying the entire object. The workout variable is an instance of the Workout class, defined as follows: export class Workout { id: string; name: string; exercises: Exercise[]; routine: Ro ...

What is the proper method for utilizing an object as a dependency when using useEffect?

Currently, I am in the process of developing a react hook that takes in a query object. export function useMyQuery(query: QueryObjectType) { React.useEffect(executeQuery, [ query ]); // ... } Unfortunately, whenever my hook is called during a re- ...

Utilizing Typescript to extract type information from both keys and values of an object

I have a unique challenge of mapping two sets of string values from one constant object to another. The goal is to generate two distinct types: one for keys and one for values. const KeyToVal = { MyKey1: 'myValue1', MyKey2: 'myValue ...

What causes Node.js to crash with the Headers already sent Error while managing errors in Express?

My current project involves using Express to set up an API endpoint for user registration. However, I've encountered a problem where sending a request that triggers an error to this API endpoint causes my node.js server to crash. The specific message ...

Dynamically change or reassign object types in TypeScript

Check out the example you can copy and test in TypeScript Playground: class GreetMessage { message: {}; constructor(msg: string) { let newTyping: { textMsg: string }; // reassign necessary this.message = newTyping; this.message.textMsg = msg; ...

Troubleshooting tip: The request body is missing and needs to be added to resolve the issue

I am encountering an issue while trying to update a boolean column in my database for approving customer accounts using an angular front-end button. Whenever I send the request, my controller throws an error stating Resolved [org.springframework.http.conve ...

How can I resolve the issue of "Errors detected in your package-lock.json" in NGRX?

I encountered some problems while trying to set up my Angular project in an NX workspace with NGRX and running it through Jenkins. After running npm install, I started getting errors. Has anyone else experienced errors like these after executing: nx updat ...

Trouble viewing Three.js content in Index.html

My current project involves building a website using three.js with typescript. However, I am facing an issue where only the header from my index.html file is displayed when I try to load the website onto a local server. The main problem arises when I atte ...

An object in typescript has the potential to be undefined

Just starting out with Typescript and hitting a snag. Can't seem to resolve this error and struggling to find the right solution useAudio.tsx import { useEffect, useRef } from 'react'; type Options = { volume: number; playbackRate: num ...