Skip to content

Commit

Permalink
Fix font paths
Browse files Browse the repository at this point in the history
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
  • Loading branch information
slifty committed Apr 30, 2021
1 parent 656fb8c commit a7a3b55
Showing 1 changed file with 10 additions and 5 deletions.
15 changes: 10 additions & 5 deletions services/api/mw2pdf/classes/PdfGenerator.js
Original file line number Diff line number Diff line change
@@ -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'
Expand All @@ -9,6 +11,9 @@ import {
} from 'pdf-lib'
import { Pdf } from './Pdf.js'

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

export class PdfGenerator {
constructor(directory = '') {
Object.assign(
Expand Down Expand Up @@ -115,13 +120,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?
Expand Down

0 comments on commit a7a3b55

Please sign in to comment.