Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Emojis in jspdf doesnt works

Tags:

jspdf

I'm trying to display emojis like: ✨test✨ in my pdf. But it doesnt works.

I already tryed adding a custom font with:

const font = "data:font/ttf;base64,AAEAAAANAIAAAwBQRkZU...."
doc.addFileToVFS("unifont-15.0.01.ttf", font);
doc.addFont("unifont-15.0.01.ttf", "Unifont", "normal");
doc.setFont("Unifont"); // set font
like image 344
KingMarcel Avatar asked Oct 17 '25 02:10

KingMarcel


1 Answers

Alright I found a way to achieve that. It is not clean but it is working.

jsPDF don't support emoji but it does support image. Especially it can import a HTML canvas element. We can write text into a canvas. We can write emoji into a canvas. So we can create the pipeline emoji to canvas to image to jsPDF.

Here is a working demo

// https://stackoverflow.com/a/28074297/1248177
const mm2px = (mm) => mm * 11.81;

const appendEmoji = (doc, emoji) => {
  const canvas = document.createElement("canvas");
  canvas.width = mm2px(210);
  canvas.height = mm2px(297);
  const context = canvas.getContext("2d");

  context.font = "bold 960pt Arial";
  context.textAlign = "center";
  context.textBaseline = "middle";
  context.fillText(emoji, canvas.width / 2, canvas.height / 2);
  doc.addImage(canvas, "PNG", 0, 0, 210, 297);
};

will print enter image description here

source https://parallax.github.io/jsPDF/docs/module-addImage.html#~addImage

like image 83
aloisdg Avatar answered Oct 20 '25 11:10

aloisdg