5

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?

Community
  • 1
  • 1
FThompson
  • 27,043
  • 11
  • 53
  • 89
  • did you try appending some css to the doc (`@font-face` with `e.target.result` as the src property) ? `$('').appendTo($(document))` (won'tprobably work but worth testing i guess) – mikakun Feb 07 '13 at 07:33
  • @mikakun It works, nice call! Please post it as an answer so I can give you the reputation you deserve. – FThompson Feb 07 '13 at 16:52

1 Answers1

1

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]);
        }
     }
FThompson
  • 27,043
  • 11
  • 53
  • 89
mikakun
  • 2,105
  • 2
  • 14
  • 24