Use FontSourceBase to load font from google API

Hello,

Is it possible to use FontSourceBase or StreamFontSource to load fonts from internet (google fonts)? Problem is, I don’t really understand how FontSourceBase works :neutral_face:!

My idea is to check font with System or FolderFontSource first, and if not available, check in google fonts.
Google fonts API provides an endpoint who return the list of all availables font with the link to ttf files. So, I can probably easily use it to implement method getAvailableFonts() but there is still some unknow :

https://developers.google.com/fonts/docs/developer_api

@kehrmit You can find an example how to use StreamFontSource for fonts stored in S3 storage here:
https://docs.aspose.com/words/net/integration-in-aws-lambda/#how-to-use-fonts-stored-in-s3-storage-in-aws-lambda
The example is in C#, but the main idea is the same for Java. The same approach can be used for fonts from other external sources.

This method should return an InputStream with fonts data, for example, you can return stream of TTF file read from disk. In the example provided in the suggested article StreamFontSource is returned for each font stored in S# storage.

For StreamFontSource PhysicalFontInfo.getFilePath will return an empty string, since there is no file from where the font is read. PhysicalFontInfo.getFilePath returns a physicals font path when the font is read from file.

Also, when you work with external font sources, it would be useful to cache font search information. Please see the following article for more information:
https://docs.aspose.com/words/net/specifying-truetype-fonts-location/#save-and-load-a-font-search-cache

Thank’s for the quick response with link to example! :heart:

As the class FontSourceBase provides a method getAvailableFonts, I thought that we could manage several fonts with a single instance of StreamFontSource! Google API provides more than 1000 fonts, so, if I have to instantiate 1000 sources, it will surely have an impact on performance, right? And i don’t want to load the whole catalog from google API, just call it if a font is not available locally

As FolderFontSource is able to provide all fonts in a folder, it’s not possible to have the same behavior with the Stream or otherwise with a custom implementation?

@kehrmit StreamFontSource as well as MemoryFontSource can provide access to a single font only. So it is require to create StreamFontSource for each font.
In your case, you can first get the list of all fonts available in the external repository, then use IWarningCallback to check what fonts used in the document are missed, and finally create StreamFontSource for each missed font, if the fonts are available in the external repository.
Note after adding additional font sources it will be required to call Document.updatePageLayout to rebuild document layout using the newly available fonts.