From e13f4907a58fc8ef9f1b7f35943bfe8d3dc7a7c5 Mon Sep 17 00:00:00 2001
From: Dan Schultz <slifty@gmail.com>
Date: Fri, 30 Apr 2021 13:57:17 -0400
Subject: [PATCH] Fix font paths

Fonts were being loaded in a way that would only work if the script was
being called from the mw2pdf root (the folder containing the embedded
fonts).

This adds some (ugly) logic to identify the `__dirname` of the utility
script and access fonts relative to the utility itself as opposed to the
calling path.  This logic is necessary because unfortunately NodeJS
doesn't populate __dirname when module mode is enabled.

See: https://stackoverflow.com/questions/32705219/nodejs-accessing-file-with-relative-path/32707530#32707530

As discussed in #24 we will eventually want to remove fonts from the
project altogether, instead trying to have a generic default settings
and allowing font configuration to be configurable for anybody who would
like to override that generic option.

Issue #24
---
 services/api/mw2pdf/classes/PdfGenerator.js | 17 ++++++++++++-----
 1 file changed, 12 insertions(+), 5 deletions(-)

diff --git a/services/api/mw2pdf/classes/PdfGenerator.js b/services/api/mw2pdf/classes/PdfGenerator.js
index 6cf0ffdd..ecc3fbea 100644
--- a/services/api/mw2pdf/classes/PdfGenerator.js
+++ b/services/api/mw2pdf/classes/PdfGenerator.js
@@ -1,3 +1,5 @@
+import { fileURLToPath } from 'url'
+import path from 'path'
 import fs from 'fs'
 import { v4 as uuidv4 } from 'uuid'
 import PdfMerger from 'pdf-merger-js'
@@ -9,6 +11,11 @@ import {
 } from 'pdf-lib'
 import { Pdf } from './Pdf.js'
 
+// The below two lines are from
+// https://stackoverflow.com/questions/32705219/nodejs-accessing-file-with-relative-path/32707530#32707530
+const __filename = fileURLToPath(import.meta.url);
+const __dirname = path.dirname(__filename);
+
 export class PdfGenerator {
   constructor(directory = '') {
     Object.assign(
@@ -115,13 +122,13 @@ export class PdfGenerator {
   async generatePdfFromScaffold(scaffold, outPdf = this.generatePdfObject()) {
     const printer = new PdfPrinter({
       Roboto: {
-        normal: 'fonts/Roboto-Regular.ttf',
-        bold: 'fonts/Roboto-Medium.ttf',
-        italics: 'fonts/Roboto-Italic.ttf',
-        bolditalics: 'fonts/Roboto-MediumItalic.ttf',
+        normal: path.join(__dirname, '../fonts/Roboto-Regular.ttf'),
+        bold: path.join(__dirname, '../fonts/Roboto-Medium.ttf'),
+        italics: path.join(__dirname, '../fonts/Roboto-Italic.ttf'),
+        bolditalics: path.join(__dirname, '../fonts/Roboto-MediumItalic.ttf'),
       },
       SourceCodePro: {
-        normal: 'fonts/SourceCodePro-Regular.ttf',
+        normal: path.join(__dirname, '../fonts/SourceCodePro-Regular.ttf'),
       }
     })
     // TODO: what is .end doing in this block -- is it sync? does it have to be called?