Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow the setting of a default font #445

Open
wants to merge 4 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 14 additions & 5 deletions lib/Recipe.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,15 @@ const streams = require("memory-streams");
* @param {string} [options.author] - The author
* @param {string} [options.title] - The title
* @param {string} [options.subject] - The subject
* @param {string} [options.colorspace] - The default colorspace: rgb, cmyk, gray
* @param {string} [options.colorspace] - The default colorspace: rgb, cmyk, gray, separation
* @param {string} [options.defaultFontSize=14] - The default font size
* @param {string} [options.defaultFontFamily=helvetica] - The default font: 'arial', 'courier new', 'georgia', 'helvetica', 'roboto'
* @param {string|string[]} [options.fontSrcPath] - directory location(s) of additional fonts
* @param {string[]} [options.keywords] - The array of keywords
* @param {string} [options.password] - permission password
* @param {string} [options.userPassword] - this 'view' password also enables encryption
* @param {string} [options.ownerPassword] - this allows owner to 'edit' file
* @param {string} [options.userProtectionFlag] - encryption security level (see permissions)
* @param {string|string[]} [options.fontSrcPath] - directory location(s) of additional fonts
*/
class Recipe {
constructor(src, output, options = {}) {
Expand All @@ -34,7 +36,9 @@ class Recipe {
this.encryptOptions = this._getEncryptOptions(options, this.isNewPDF);
this.options = Object.assign({}, options, this.encryptOptions);
this.current = {};
this.current.defaultFontSize = 14;
this.current.defaultFontSize = options.defaultFontSize ?? 14;
this.current.defaultFontFamily =
options.defaultFontFamily?.toLowerCase() ?? "helvetica";

if (this.isBufferSrc) {
this.outStream = new streams.WritableStream();
Expand Down Expand Up @@ -69,9 +73,14 @@ class Recipe {

this._loadFonts(path.join(__dirname, "../fonts"));

if (options.fontSrcPath) {
this._loadFonts(options.fontSrcPath);
if (options.fontSrcPath) this._loadFonts(options.fontSrcPath);

if (!(this.current.defaultFontFamily in this.fonts)) {
throw `Cannot find font family '${this.current.defaultFontFamily}'`;
} else if (!this.fonts[this.current.defaultFontFamily]["r"]) {
throw `Default family '${this.current.defaultFontFamily}' must have a regular type, only found '${Object.keys(this.fonts[this.current.defaultFontFamily])}'`;
}

this._createWriter();
}

Expand Down
79 changes: 41 additions & 38 deletions lib/recipe/font.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,32 +22,38 @@ exports._loadFonts = function _loadFonts(fontSrcPath) {
const fontPaths =
typeof fontSrcPath === "string" ? [fontSrcPath] : fontSrcPath;

const registerFontFile = (file) => {
let fontName = path.basename(file, path.extname(file)).toLowerCase();
// simple heuristics to make sure library fonts behave as expected
const hasBold = fontName.indexOf("bold") !== -1;
const hasItalic = fontName.indexOf("italic") !== -1;
let type = "r";
if (hasBold && hasItalic) {
fontName = fontName.replace(/-*bold/, "");
fontName = fontName.replace(/-*italic/, "");
type = "bi";
} else if (hasBold) {
fontName = fontName.replace(/-*bold/, "");
type = "b";
} else if (hasItalic) {
fontName = fontName.replace(/-*italic/, "");
type = "i";
}
return this._registerFont(fontName, file, type);
};

for (let fpath of fontPaths) {
if (fs.existsSync(fpath)) {
// only process when directory exists
if (!fs.existsSync(fpath)) throw `Cannot load font file '${fpath}'`;
if (fs.statSync(fpath).isFile()) {
if (!fontTypes.includes(path.extname(fpath).toLowerCase())) {
throw `Invalid font file '${fpath}', allowed extensions ${fontTypes}`;
}
registerFontFile(fpath);
} else {
fs.readdirSync(fpath)
.filter((file) => {
return fontTypes.includes(path.extname(file).toLowerCase());
})
.forEach((file) => {
let fontName = path.basename(file, path.extname(file)).toLowerCase();
// simple heuristics to make sure library fonts behave as expected
const hasBold = fontName.indexOf("bold") !== -1;
const hasItalic = fontName.indexOf("italic") !== -1;
let type = "r";
if (hasBold && hasItalic) {
fontName = fontName.replace(/-*bold/, "");
fontName = fontName.replace(/-*italic/, "");
type = "bi";
} else if (hasBold) {
fontName = fontName.replace(/-*bold/, "");
type = "b";
} else if (hasItalic) {
fontName = fontName.replace(/-*italic/, "");
type = "i";
}
return this._registerFont(fontName, path.join(fpath, file), type);
});
.filter((file) => fontTypes.includes(path.extname(file).toLowerCase()))
.map((file) => path.join(fpath, file))
.forEach(registerFontFile);
}
}
};
Expand All @@ -61,6 +67,10 @@ exports._registerFont = function _registerFont(
let family = fontName.toLowerCase();
let font = this.fonts[family] || {};

if (!fs.existsSync(fontSrcPath)) {
throw `Cannot load font file '${fontSrcPath}'`;
}

switch (type) {
default:
font.r = fontSrcPath;
Expand All @@ -84,7 +94,8 @@ exports._registerFont = function _registerFont(
};

function _getFontFile(self, options = {}) {
let fontFile;
const font = options.font?.toLowerCase() ?? self.current.defaultFontFamily;

// Need to choose appropriate file based on bold/italic considerations
// Note, if this is not done explicitly, the font dimensions will be incorrect.
let type =
Expand All @@ -96,22 +107,14 @@ function _getFontFile(self, options = {}) {
? "b"
: "r";

if (options.font) {
const fontFamily = self.fonts[options.font.toLowerCase()];
if (fontFamily) {
fontFile = fontFamily[type];
}
}

// when file inaccessible ...
if (!fontFile || !fs.existsSync(fontFile)) {
fontFile = self.fonts["helvetica"][type]; // use default font when otherwise unavailable.
}
const fontFile =
self.fonts[font]?.[type] ??
self.fonts[self.current.defaultFontFamily][type] ??
self.fonts[self.current.defaultFontFamily]["r"];

if (!fontFile) {
fontFile = self.fonts["helvetica"]["r"]; // use default font when otherwise unavailable.
throw `Unknown font-type pair '${font ?? self.current.defaultFontFamily}', '${type}'`;
}

return fontFile;
}

Expand Down
2 changes: 1 addition & 1 deletion lib/recipe/page.js
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,7 @@ exports.editPage = function editPage(pageNumber) {
const startX = mediaBox[0];
const startY = mediaBox[1];
const textOptions = {
font: this.writer.getFontForFile(this.fonts["helvetica-bold"]),
font: this._getFont({ bold: true }),
size: 50,
colorspace: "gray",
color: 0x00,
Expand Down
28 changes: 20 additions & 8 deletions muhammara.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -336,16 +336,18 @@ declare module "muhammara" {
export const eRangeTypeSpecific = 1;
export type eRangeType = 0 | 1;

export interface PDFWriterOptions {
version?: EPDFVersion;
log?: string;
compress?: boolean;

export interface EncryptionOptions {
userPassword?: string;
ownerPassword?: string;
userProtectionFlag?: number;
}

export interface PDFWriterOptions extends EncryptionOptions {
version?: EPDFVersion;
log?: string;
compress?: boolean;
}

type FormXObjectId = number;

export interface FormXObject {
Expand Down Expand Up @@ -869,11 +871,21 @@ declare module "muhammara" {
| "Paragraph"
| "Insert";

interface RecipeOptions {
interface RecipeOptions extends EncryptionOptions {
version?: number;
author?: string;
title?: string;
subject?: string;
colorspace?: "rbg" | "cmyk" | "gray" | "separation";
defaultFontSize?: number;
defaultFontFamily?:
| "arial"
| "courier new"
| "georgia"
| "helvetica"
| "roboto"
| string;
fontSrcPath?: string;
keywords?: string[];
}

Expand Down Expand Up @@ -1117,8 +1129,8 @@ declare module "muhammara" {

text(
text: string,
x: number,
y: number,
x?: number,
y?: number,
options?: Recipe.TextOptions,
): Recipe;

Expand Down
16 changes: 16 additions & 0 deletions tests/recipe/font.js
Original file line number Diff line number Diff line change
Expand Up @@ -36,4 +36,20 @@ describe("Font", () => {
.endPage()
.endPDF(done);
});

it("Override the default font family", (done) => {
const output = path.join(
__dirname,
"../output/Override the default font family.pdf",
);
const recipe = new HummusRecipe("new", output, {
defaultFontFamily: "arial",
defaultFontSize: 20,
});
recipe
.createPage("letter")
.text("This is Arial", 0, 0)
.endPage()
.endPDF(done);
});
});
Loading