opentypejs / opentype.js

Read and write OpenType fonts using JavaScript.
https://opentype.js.org/
MIT License
4.38k stars 468 forks source link

Save created font on server. #394

Closed kajetansom closed 5 years ago

kajetansom commented 5 years ago

Hi, I am creating a font with opentype.js and after i wrote the font into a (i guess) opentype font object, i can download it via font.download(). For my project i want the font also to be saved as a font file on the server for later use. I looked into the download function but i guess my knowlege is just too limited to understand whats happening. Can someone explain to me how this works?

Jolg42 commented 5 years ago

Hi @kajetansom ! So on a Node.js env, you could use font.download(filepath) as well.

Something like this should work:

const path = require('path');
// Font is defined somewhere
const filepath = path.join(__dirname, '/myfont.otf'); // will output in current directory.
font.download(filepath)

See how this works on Node.js here https://github.com/opentypejs/opentype.js/blob/master/dist/opentype.js#L13502 The font will first be converted to a Buffer and will be written on disk with fs.writeFileSync()

kajetansom commented 5 years ago

Hi @Jolg42
Thanks for your reply. Unfortunately I am not using node. Can I also pass the file somehow to php? I think i have to use the arrayBuffer for this but i am not quite sure how that works with a font-file.

Jolg42 commented 5 years ago

So yes you could send the Buffer to your server and save it as a file there.

Like this maybe

var arrayBuffer = font.toArrayBuffer()
var dataView = new DataView(arrayBuffer);
var blob = new Blob([dataView], {type: 'font/opentype'});

// example from here https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Sending_and_Receiving_Binary_Data#Sending_binary_data

var oReq = new XMLHttpRequest();
oReq.open("POST", serverUrl, true);
oReq.onload = function (oEvent) {
  // Uploaded.
};

oReq.send(blob);

By the way there is a library for PHP, https://github.com/PhenX/php-font-lib (I didn't try it) and more resources on my dedicated repository https://github.com/Jolg42/awesome-typography

kajetansom commented 5 years ago

Thank you again! I will try this out and also check the links :)