Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preview a font before it is uploaded

I wish to preview a font file once it is chosen in an <input type="file"> input.

I've tried an approach similar to that used to preview images (similar to this answer), but using a Font object instead of an Image object. However, the font fails to load after the src is set, because it searches for the font installed on the system, but by a temp name.

How can I do this?

like image 993
FThompson Avatar asked Nov 12 '22 12:11

FThompson


1 Answers

So there it is (although it was more a guess than an educated/tested answer) :

preview a font before it is uploaded (in modern browser) by using the fileReader class & appending to the document the read file object result property in a new @font-face css definition:

  function previewfonts(input) {
        if (input.files && input.files[0]) {
            var reader = new FileReader();

            reader.onload = function (e) {
                $('<style>'+
                     '@font-face{'+
                         'font-family: preview;'+
                         'src: url('+e.target.result+');'+
                      '}'+
                      '.preview {font-family: preview;}'+
                  '</style>'+
                  '<div class="preview">lorem ipsum...</div>').appendTo($(document));

            }

           reader.readAsDataURL(input.files[0]);
        }
     }
like image 143
mikakun Avatar answered Nov 15 '22 05:11

mikakun