What is the best way to customize fonts for PDFMake in Angular projects?

Recently, I delved into the PDFMake documentation in hopes of creating a document for my Angular application. Along the way, I stumbled upon queries like this one, but unfortunately, found no answers.

I am curious if anyone can offer insight or provide a clear example on how to import custom fonts for PDFMake within an Angular project. I have downloaded the files for the "Lato" font, but I am unsure of the next steps.

As per the documentation, I did successfully import the library:

import pdfMake from 'pdfmake/build/pdfmake';
import pdfFonts from 'pdfmake/build/vfs_fonts';
pdfMake.vfs = pdfFonts.pdfMake.vfs;

Additionally, I came across an example that included the following declaration:

pdfMake.fonts = {
  Lato: {
    normal: 'assets/fonts/Lato-Regular.ttf'
  }
};

This snippet provided information on naming the font, specifying its weight, and indicating the file's location, but I remain uncertain on how to instruct PDFMake to utilize this font.

Any guidance on this matter would be greatly appreciated, as I have been mulling over this for quite some time.

UPDATE: After adhering to the guidelines outlined in the documentation, I managed to implement the Lato font by directly adjusting the files within the pdfmake node_modules directory. While this approach worked, I wish to refrain from modifying node_modules as it may lead to difficulties tracking changes or accessing them on different machines while running the project.

Answer №1

Update for Angular Version 15

I recently upgraded my Angular project to the latest version 15, which also involved updating pdfMake from 0.1.68 to 0.2.7.

The new version makes it much simpler to upload custom fonts using a URL.

If you followed the steps below on a previous version and then upgraded pdfMake, these changes should work for you as they did for me.

In the component where you are utilizing pdfMake, the import statement used to look like this:

import pdfMake from 'pdfmake/build/pdfmake.min';
pdfMake.fonts = FONTS;

You need to switch to the default Typescript implementation:

import * as pdfMake from "pdfmake/build/pdfmake";

When calling CreatePdf, now pass in three parameters, one of which is the fonts object containing font definitions for normal, bold, italics, and bolditalics styles.

pdfMake.createPdf(docDefinition, null, FONTS);

This worked for me.

=======================================================

I have just spent time figuring out how to achieve the same. The documentation is lacking, but I managed to solve it.

  1. To begin, you must clone the PdfMake repository locally.

https://github.com/bpampuch/pdfmake

  1. Once downloaded, open it in your code or Sublime text editor, navigate to the examples directory within the hierarchy, and then find the fonts subdirectory.

I found the Roboto font in mine along with a sample image, but since I do not use Roboto, I deleted it.

  1. Place all the TTF fonts you wish to use into the fonts directory. I only used one to keep the file size down.

3a) If Gulp is not installed, install it.

3b) Optionally, rename the file vfs_fonts.js in the /build directory to vfs_fonts.js.old or something similar.

  1. Run the following gulp command from your Terminal or Powershell...

    gulp buildFonts

A new vfs_fonts.js will be generated in the pdfMake/build folder.

4a) This step is optional but may be necessary. After running the gulp command, you might need to modify the newly created vfs_fonts.js for successful compilation.

  1. Next, copy the updated vfs_fonts.js to your project's destination where PdfMake is being used, typically under /assets/js.
  2. Adjust the path in the import declaration within your Angular component if needed. For example: Before -
    // import pdfFonts from 'pdfmake/build/vfs_fonts';
    , After -
    import pdfFonts from '../../assets/js/vfs_fonts';
    .
  3. Create a new font definition in pdfMake, specifying the TTF file for each style (normal, bold, italics, bolditalics).

Lastly, include your new font in the pdfDefinition within your project:

defaultStyle: {
  font: 'Baloo2'
},

There may be alternative methods to achieve this, but I hope these instructions help you get started.

Answer №2

An alternative method has been introduced to load fonts since version 0.1.66, which was released only 18 days after the original answer. Now, you can easily load fonts via URL and implement it in Angular like this:

pdfMake.fonts = {
    DDIN: {
        normal: `${window.location.origin}/assets/D-DIN.ttf`,
        bold: `${window.location.origin}/assets/D-DIN-Bold.ttf`,
        italics: `${window.location.origin}/assets/D-DIN-Italic.ttf`,
    }
};

Answer №3

Challenge: The default font family in pdfmake is Roboto, but I prefer to use Arial as my font.

Encountering this issue in my Angular Project led me to the following solution:

1/ Install the "pdfmake-font-generator" package globally

npm i -g pdfmake-font-generator

2/ Download the necessary font files, such as Arial, from the link below

3/ Save these files somewhere, for example in the assets/fonts folder

4/ Generate a custom font file using the installed package

pdfmakefg assets/fonts assets/custom-fonts.js

This command requires two parameters: the location of the existing font files and the desired output location and filename (the custom-fonts.js file doesn't need to exist beforehand)

5/ In your pdfmake implementation, comment out the default font import line and use your custom fonts instead

// import pdfFonts from 'pdfmake/build/vfs_fonts';

import pdfFonts from "./../assets/custom-fonts";

6/ Utilize your custom font by specifying it in the document definition

pdfMake.fonts = {
 'Arial' : {
   normal: 'ARIAL.TTF',
   bold: 'ARIALBD.TTF',
   italics: 'ARIALI.TTF',
   bolditalics: 'ARIALBI.TTF'
 }
}
const documentDefinition = {
 content: '',
 defaultStyle: {
  font: 'Arial'
 }
}
pdfMake.createPdf(documentDefinition).open();

Answer №4

Struggling with setting up Gulp on my Windows system, I decided to take a different approach that didn't involve using Gulp at all. I shared my solution in a Q&A format here: How can custom fonts be utilized in pdfmake without relying on Gulp?

This workaround was specifically tailored for Angular development.

Answer №5

When incorporating a typing script, make sure to follow these steps:

import * as pdfMake from 'pdf maker / create / pdfmaker';
import * as documentation from 'pdf creator / build / vfs_files';

Answer №6

import pdfMake from "pdfmake/build/pdfmake";
import pdfFonts from "pdfmake/build/vfs_fonts";

pdfMake.vfs = {
  ...pdfFonts.pdfMake.vfs,
  'Custom-font-normal.ttf': 'Custom font in base64 format'
};

// include custom font in font collection for PDF generation
pdfMake.fonts = {
  CustomFont: {
    normal: 'Custom-font-normal.ttf',
  },
};

const docDefinition = {
  defaultStyle: {
    font: 'CustomFont', // replace with your custom font name
  },
  content: [...]
}

Answer №7

If you're utilizing Webpack, this solution proved effective for me:

const fontFile = require('./fonts/Roboto-Regular.ttf');

pdfMake.fonts = {
  myFont: {
    normal: `${window.location.origin}/${fontFile}`
  }
};

const documentDefinition = { 
  defaultStyle: {
   font: 'myFont'
  }
};

pdfMake.createPdf(documentDefinition).download(`pdf_with_table_of_content.pdf`);

Answer №8

In my current situation (where I am attempting to add new fonts for pdfMake) within the framework of an angular project, I am encountering the issue where pdfMake.fonts is throwing an error message stating "Cannot assign to 'fonts' because it is a read-only property.ts(2540)"...

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

Modifying Font Style in Angular 4 Material

Is there a way to change the font in Angular 4 Material material.angular.io using the styles file in .CSS format instead of SASS? While the documentation offers an example for SASS at: https://github.com/angular/material2/blob/master/guides/typography.md ...

Setting style based on the condition of the router URL

I am currently facing an issue with a global script in Angular 10 that is supposed to evaluate the current path and apply a style to the navigation bar conditionally. However, it seems to fail at times when using router links. I am wondering if there is a ...

Components loading in Angular result in lat long being undefined in google map integration

I am currently utilizing Ionic-angular AGM. I am facing an issue where I am unable to retrieve my current location when the component loads, as it seems like the component is being fired before the latitude and longitude are ready. How can I make this proc ...

Implementing Basic Authentication for HTTP Requests in Angular 7

Currently, I am working with angular 7 along with Spring Boot and Spring Security. Within the Back End, I have successfully implemented basic authentication. However, while attempting to send a request from Angular with an Http Header that includes User n ...

Using the TypeScript compiler API to determine the location in the generated code of a particular AST node

I am aiming to retrieve the specific TypeScript AST node's location (start and end) in the emitted JavaScript file. Consider this code snippet: const program = ts.createProgram(tsconfig.fileNames, tsconfig.options); const aNode = program.getSourceFi ...

Clicking the "X" close button on a mat-list removes an item from the user interface

Recently, I utilized the mat-list component to display items on the UI. Each item is accompanied by a close(X) button located on the right-hand side. https://i.stack.imgur.com/1E2ZG.png Html Code <mat-list > <ng-container *ngFor='le ...

Failure parsing occurred when attempting to make an HTTP POST request from Angular to a PHP server

When I try to consume the PHP endpoint from Postman, everything works fine. But when I attempt to do the same from an Angular post request, I encounter an error - Http failure during parsing for. Even though I have double-checked my code and it all seems c ...

Guidelines for Organizing Angular Interface Files and Implementing Custom Type Guards

In my Angular 2 project, I am utilizing Interfaces and have implemented User Defined Type Guards: grid-metadata.ts export interface GridMetadata { activity: string; createdAt: object; totalReps: number; updatedAt: object; } grid.service.ts ... ...

Retrieve the canvas coordinates for the images starting at lx and ending at rx on the x-axis, and

Currently, I am working on a project where I need to implement a drag and drop feature for an image within a PDF document. The goal is to retrieve the coordinates of the dragged image and use them later for document signing. The situation I am dealing wit ...

I'm experiencing issues with my Ionic application Dockerize not properly functioning in the browser

I'm currently working on an Ionic study app in order to familiarize myself with Docker. I have completed all the necessary steps to create the image: 1. First, I created the Dockerfile with the following scripts: FROM node:18.10.0-alpine3.15 WORKDIR ...

Compiling TypeScript: Using the `as` operator to convert and then destructure an array results in a compilation error, requiring an

I am currently utilizing TypeScript version 2.9.2. There is a static method in a third-party library called URI.js, which is declared as follows: joinPaths(...paths: (string | URI)[]): URI; I have a variable named urlPaths that is defined as urlPaths: s ...

Search for records in MySQL using Typeorm with the condition "column like %var%" to retrieve results containing the specified

Looking for a way to search in MySql using typeorm with the "column like" functionality. async findAll({ page, count, ...where }: CategorySelectFilter): Promise<Category[]> { return this.categoryRepository.find({ where, ...

Integrating Typescript into function parameters

I am attempting to make my function flexible by allowing it to accept either a string or a custom type onPress: (value: string | CustomType)=>void But when I try to assign a string or CustomType, the compiler gives an error saying is not assignable to ...

What is the best method to adjust the width of the PrimeNG ConfirmDialog widget from a logic perspective

Currently utilizing "primeng": "^11.2.0" and implementing the ConfirmDialog code below this.confirm.confirm({ header: 'Announcement', message: this.userCompany.announcement.promptMsg, acceptLabel: this.userCompany.announcement ...

We are unable to create a 'Worker' as Module scripts are not yet supported on DedicatedWorkers in Angular 8

Error An error has occurred in the following files: node_modules/typescript/lib/lib.dom.d.ts and node_modules/typescript/lib/lib.webworker.d.ts. Definitions of various identifiers conflict with those in other files, leading to modifier conflicts and dup ...

Efficiently setting up a common service constructor in Angular 2 Ionic 2 to streamline the initialization process for multiple services

Here is the organizational structure of my ionic 2 app.. I have created a few services that utilize my baseService class to handle header injection and other tasks for each http request. Within the constructor of the baseService, I make use of NativeStor ...

What is the best way to insert a chart into a div using *ngIf in Angular?

I just started using chart.js and successfully created the desired chart. However, when attempting to implement two tab buttons - one for displaying tables and the other for showing the chart - using *ngIf command, I encountered an error: Chart.js:9369 F ...

What is the reason behind having to press the Tab button twice for it to work?

Currently, I am implementing a Tabbed Form with jQuery Functionality in Angular 4. The Tabbed Form itself is functioning, but I've noticed that I have to click the Tab Button twice for it to respond. See the code snippet below: TS declare var jquery ...

Combining Multiple TypeScript Declaration Files into an NPM Package for Seamless Importing with index.d.ts

I have a unique package structure that includes: myPackage/ |- types/ | |- type1.d.ts | |- type2.d.ts |- src/ | |- someUtilities.ts |- index.ts |- package.json |- tsconfig.json In my package, the index.ts file is handling imports and exports for all th ...

Surprising Media Component Found in URL Parameters within the design

Exploring the page structure of my Next.js project: events/[eventId] Within the events directory, I have a layout that is shared between both the main events page and the individual event pages(events/[eventId]). The layout includes a simple video backgro ...