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

Is it possible to dynamically load fonts during code execution? #4330

Open
ghtx280 opened this issue Feb 16, 2025 · 1 comment
Open

Is it possible to dynamically load fonts during code execution? #4330

ghtx280 opened this issue Feb 16, 2025 · 1 comment
Labels

Comments

@ghtx280
Copy link

ghtx280 commented Feb 16, 2025

Hi, I'm trying to make an svg based image generator, I tried many libraries and variants and realized that sharp generates them extremely fast, but I have some problems, for example now I'm dealing with fonts, because I want the user to choose the font he needs, for example from google fonts (I know woff2 is not supported, I'll solve it later, it's not critical), the user will pass its name to URLSearchParams and I don't know how to do it correctly. Can I load the fonts on the fly while the code is running?

import sharp from 'sharp';

export const GET = async (e) => {
	// await sharp({
	// 	text: {
	// 		text: 'test',
	// 		font: 'Montserrat',
	// 		fontfile: './Montserrat.ttf'
	// 	}
	// })
	// 	.webp()
	// 	.toBuffer();

	const svg = `
		<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 300 100">
			<text font-size="39" font-family="Montserrat" transform="translate(23 62)">Lorem ipsum</text>
		</svg>
	`;

	return new Response(await sharp(Buffer.from(svg)).webp().toBuffer(), {
		headers: {
			'Content-Type': 'image/webp'
		}
	});
};

I have the following code, if you execute it like this, you won't get the font you need, if you uncomment and restart it, everything works, the fonts are there. But I tried to wrap it in an if statement like this:

if (e.url.searchParams.has('test')) { 
  await sharp({
    text: {
	text: 'test',
	font: 'Montserrat',
	fontfile: './Montserrat.ttf'
    }
  })
  .webp()
  .toBuffer();
}

then it won't work that way anymore, i.e. it's impossible to set the font while the code is running, right? Or is there a hack? Help me, please!

@lovell
Copy link
Owner

lovell commented Feb 16, 2025

Did you see https://sharp.pixelplumbing.com/install#fonts ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants