How can I Read a Font File That a User Uploads? - javascript

I am working on a web-based project that is fully in Javascript. In it, I want users to be able to format their text exactly as they want. Naturally, I would like them to have the ability to upload their own fonts. However I'm not sure how to read the file they upload. I can take in the file, but I can't utilize their .ttf/.woff/woff2 etc. as an actual font file. I've used the FileReader API and have read in a ttf as a DataUrl, which puts it into base64. However I'm not sure how to turn it back into a file.
I've found this code from another post made on here, but it doesn't exactly do what I need it to do:
//read the file
const reader = new FileReader();
reader.addEventListener('load', (event) => {
<usersSelectedFile>.src = event.target.result;
});
var fontFile = reader.readAsDataURL(file);
With this, I get the file in base64. I know how to use font-face, but I've tried passing this fontFile in a font face style sheet but I got nothing from it.
My ultimate question is: How can I read a file in base64 as if it were a normal file? How should I reference it in font-face?
ALSO: I want to mention that I am trying to have this be stored in localStorage, as I wouldn't want any user-made changes to be global.

This is an interesting problem that I would like to know the definitive solution to. The best I could find by searching around was this solution, that utilizes and API for this specific problem. I have not tested it as of this moment, but it seems reliable.
As for the localStorage issue, have you tried converting the file to a JSON string using JSON.stringify(), and then using localStorage.setItem('name',DATAHERE)? I am not sure if this works with files, but this is what I use for arrays and non-string information when saving to localStorage.
Sorry for not having anything concrete for you. I'm looking forward to working this out further if none of my recommendations helped you.

Related

How do I use a .txt file and read each line as an array?

I'm trying to create a web app where I have some sort of a flash card, but the information of the flash card will be coming from a .txt file I created.
I'd like to be able to read each line as it's own question or array, and then have the answer for that question in another .txt file that will match the same line so I can use the same index value.
I'm sorry if it sounds confusing. I am just getting started on the idea.
Thank you.
Use one of the examples in MDN - Using files from web applications to get the file you want to process. Once you have selected your file, you can use a FileReader.readAsText() to get the full text of the file as a string.
let myArray;
let fileReader = new FileReader();
fileReader.onload = (event) => {
myArray = event.target.result.split('\n');
}
fileReader.readAsText(myFile);
Take a deep read on the first article. It has lots of examples of working with files. It has helped me a lot
PS: if it worked, please, mark this as the solution. I need reputation to be able to comment ^_^

How can I create a PDF in Javascript, then use that data to recreate it in ColdFusion?

Forgive the lack of code but I'm working in a production environment and it's a lot. I can provide more specific examples if needed but I will explain the basic situation here.
I'm using a library called PdfMake (which is excellent btw, great for making pdf's in JS if you need that) to make a dynamic PDF on the fly.
Now I need to get the PDF into an S3 bucket, but our stack currently relies on ColdFusion. Luckily, PdfMake has a handy method to convert the pdf data to Base64 and ColdFusion has a handy function to convert Base64 to binary.
So I sent the base64 to my server, convert it to binary, make a new coldfusion pdf and read it like this (fileData is a base64 encoded string)
public function upload_pdf(string fileName, any fileData){
var myPdf = new pdf();
var binary = ToBinary(arguments.fileData);
myPdf.read( source=binary, name="fileSource");
}
For some reason this action is failing. I usually get an error that says "The Document has no catalog of type dictionary", which is very cryptic and brings up no helpful results when I search it. Sometimes, without changing anything, I get an error that reads "the rebuild document still has no trailer". From googling it seems trailers are something specific to do with PDFs.
Intuitively I would think that this would work, since base64 and binary are versatile types of encoding. However I'm at a loss as to how to even begin to fix or diagnose this. I will probably begin looking for another solution altogether but I am curious to learn more about what is happening here so if anyone has any ideas I am down for some discussion.
FOR ANY CURIOUS READERS I HAVE SOLVED THIS PROBLEM, HERE IS THE WORKING CODE:
public function upload_pdf(string fileName, string fileData){
var myPdf = new pdf();
var binary = decodeBinary(Replace(arguments.fileData, " ", "+", "ALL"));
myPdf.setSource(binary);
}

how print a pdf directly from windows 8 store app (javascript)

I'm making a Windows store app (in Javascript) that generates a PDF. I convert this to base64 and then save that to file (if I want). This works fine.
(the PDF is a one page document (~30kb) with text, vector graphics and a small image)
Now I would like to be able to print this pdf directly from the app without having to open it in a separate application. Of course I've been doing a lot of searching, but the information I've come accross never seems to work. It either is in the wrong language, doesn't do what I'm looking for or just doesn't work. Also the Microsoft documentation is pretty vague and lacks decent examples.
Anyway, from what I've understood you can actually render a pdf page to bitmap and then send that to the printer. I decided to give it a try, so what I'm trying to do first is to save the pdf as an image to file.
Now I've managed to create a pdfPage object, now I'm supposed to do this:
pdfPage.renderToStreamAsync(outputStream).done( /* Your success and error handlers */ );
The outputStream is supposed to be a IRandomAccessStream object, but I can't seem to instance one. It doesn't show in the Streams list and when I type it in manually it doesn't work... Using InMemoryRandomAccessStream instead seems to work though.
var outputStream = new Windows.Storage.Streams.IRandomAccessStream(); //this don't work?
Even if outputStream is good, how do I save it to file? I've saved IBuffer's to file before, can I convert it to an IBuffer somehow? I can't find any information on that.
Also I believe it should be possible to show the outputStream as an image in the app. I can only find C# examples of this. How does this work in JS/HTML?
Okay I figured out how to save it:
Windows.Storage.ApplicationData.current.temporaryFolder.getFileAsync("mydocument.pdf").then(function (file) {
var pdfDocument = Windows.Data.Pdf.PdfDocument;
pdfDocument.loadFromFileAsync(file).then(function (pdf) {
page1 = pdf.getPage(0);
var accessStream = new Windows.Storage.Streams.InMemoryRandomAccessStream();
page1.renderToStreamAsync(accessStream).done(function () {
Windows.Storage.ApplicationData.current.temporaryFolder.createFileAsync("page1image.png", Windows.Storage.CreationCollisionOption.replaceExisting).then(function (file) {
file.openAsync(Windows.Storage.FileAccessMode.readWrite).then(function (filestream) {
Windows.Storage.Streams.RandomAccessStream.copyAndCloseAsync(accessStream.getInputStreamAt(0), filestream.getOutputStreamAt(0)).then(function () { console.log('done') });
});
});
});
});
});
Why do these seeminlgy straightforward things have to be so complicated?
The whole rasterization doesn't work too well. I mean to get a decent resolution (600dpi) the file takes some time to generate. I noticed that even the printer needs a couple of breaks while printing to keep up. This doesn't happen at all when I print the pdf directly. Also you lose the CMYK definition.
But what my real concern is: when I print an image it always adds 2cm margins to the page. The pdf image has margins of its own already so now it's double. 2cm is way too much anyway. I can't find any settings anywhere where I can change this.
So: does anyone know how to change the margins when printing from a Windows store app?

How to send only the text from a text file

What I need to do is:
Let user choose txt file from his disc
Get the text from it to let's say a variable
Send it (the variable value) via AJAX
For the first point I want to know if I should use normal input type (like if I would like to send file via POST) <input type="file">
For the second point I need to know how to get the name of the file user selected and then read text from it. Also I'm not good with javascript so I don't really know how long can a string be there (file will have about 15k lines on average)
For the third I need nothing to know if I can have the data stored in a variable or an array.
Thanks in advance.
P.S. I guess javascript is not a fast language, but (depending on the editor) it sometimes opens on my computer the way that I have all the needed data in first 5 or 6 lines. Is it possible to read only first few lines from the file?
It is possible to get what you want using the File API as #dandavis and other commentors have mentioned (and linked), but there are some things to consider about that solution, namely browser support. Bottom line is the File API is currently a working draft of the w3c. And bottom line is even w3c recommended things aren't always fully supported by all browsers.
What solution is "best" for you really boils down to what browser/versions you want to support. If it were my own personal project or for a "modern" site/audience, I would use the File API. But if this is for something that requires maximum browser support (for older browsers), I would not currently recommend using the File API.
So having said all that, here is a suggested solution that does NOT involve using the FIle API.
supply an input type file in a form for the user to specify file. User will have to select the file (javascript cannot do this)
use form.submit() or set the target attribute to submit the form. There is an iframe trick for submitting a form without refreshing the page.
use server-side language of choice to respond with the file info (name, contents, etc.). For example in php you'd access the posted file with $_FILES
then you can use javascript to parse the response. Normally you'd send it as a json encoded response. Then you can do whatever you want with the file info in javascript.
With Chrome and Firefox you can read the contents of a text file like this:
HTML:
<input type="file" id="in-file" />
JavaScript with jQuery:
var fileInput = $('#in-file');
fileInput.change(function(e) {
var reader = new FileReader();
reader.onload = function(e) {
console.log(reader.result);
}
reader.readAsText(fileInput[0].files[0]);
});
IE doesn't support the FileReader object.

Javascript: Read remote file as binary

I am trying to grab a URL on a page via a Chrome Extension. I then need to read this file as binary data before posting it to an external API. I'm wondering how to accomplish this, and if it is even possible. The file type would be PDF, Word Doc or text file typically. We are working with Resumes'.
I have starting reading about File objects and the FileReader, but my initial tests have returned no luck. Anyone have any examples that I could use as a starting off point?
If you could point me in the right direction I would appreciate it.
You definitely can do this. A FileReader should have the method readAsArrayBuffer, which will give you an ArrayBuffer, which you can then inspect by creating a Uint8Array or a DataView on which you can call methods like getUint32, etc.
you might want to take a look at jBinary

Categories