Skip to content

Commit

Permalink
Fix fonts loading (#195)
Browse files Browse the repository at this point in the history
  • Loading branch information
diegomura authored Feb 7, 2018
1 parent bae448b commit d1d83d7
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 4 deletions.
Binary file modified examples/text/output.pdf
Binary file not shown.
1 change: 1 addition & 0 deletions packages/react-pdf/src/elements/Document.js
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,7 @@ class Document {
await this.renderChildren();

this.root.end();
Font.reset();
}
}

Expand Down
23 changes: 19 additions & 4 deletions packages/react-pdf/src/font/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ const register = (src, { family, ...otherOptions }) => {
fonts[family] = {
src,
loaded: false,
data: null,
...otherOptions,
};
};
Expand All @@ -17,12 +18,17 @@ const getRegisteredFonts = () => Object.keys(fonts);
const load = async (fontFamily, doc) => {
const font = fonts[fontFamily];

// We cache the font to avoid fetching it many time
if (font && !font.data) {
font.data = isUrl(font.src) ? await fetchFont(font.src) : font.src;
}

// If the font wasn't added to the document yet (aka. loaded), we do.
// This prevents calling `registerFont` many times for the same font.
// Fonts loaded state will be resetted after document is closed.
if (font && !font.loaded) {
font.loaded = true;

const src = isUrl(font.src) ? await fetchFont(font.src) : font.src;

doc.registerFont(fontFamily, src);
doc.registerFont(fontFamily, font.data);
}

if (!font && !standardFonts.includes(fontFamily)) {
Expand All @@ -32,6 +38,14 @@ const load = async (fontFamily, doc) => {
}
};

const reset = () => {
for (const font in fonts) {
if (fonts.hasOwnProperty(font)) {
fonts[font].loaded = false;
}
}
};

const clear = () => {
fonts = {};
};
Expand All @@ -41,4 +55,5 @@ export default {
getRegisteredFonts,
load,
clear,
reset,
};

0 comments on commit d1d83d7

Please sign in to comment.