EzDevInfo.com

FileSaver.js

An HTML5 saveAs() FileSaver implementation Saving generated files on the client-side — Eli Grey

filesaver.js not working iPad Chrome

I'm trying out Eli Grey's awesome filesaver implementation to download canvases as a PNG image.

It's working well on most platforms, but I've hit a snag on Chrome on the iPad - it just opens a new tab that remains blank.

I do have a fallback for browsers that can't handle blobs, so I'm hoping there's some feature detection I can do to recognise when I might need to use the fallback.

Any suggestions?


Source: (StackOverflow)

How can I make a file generated on a web page available to the user as a download?

This question is related to one I asked here on "How can I prompt the user for a save location from a Sharepoint page?"

What I need to do is, after generating a PDF thus:

        private void GeneratePDF(List<ListColumns> listOfListItems)
        {
            . . .
            //Create a stream that we can write to, in this case a MemoryStream
            StringBuilder sb = new StringBuilder();
            using (var ms = new MemoryStream())
            {
                using (var doc = new Document(PageSize.A4, 25, 25, 10, 10)) 
                {
                    //Create a writer that's bound to our PDF abstraction and our stream
                    using (var writer = PdfWriter.GetInstance(doc, ms))
                    {

                        //Open the document for writing
                        doc.Open();

                        Paragraph docTitle = new Paragraph("UCSC - Direct Payment Form", timesBold16UCSCBlue);
                        doc.Add(docTitle);

                        Paragraph subTitle = new Paragraph("(Not to be used for reimbursement of services)", timesRoman9Font);
                        subTitle.IndentationLeft = 20;
                        doc.Add(subTitle);

                        . . . // tons of iTextSharp PDF-generation code elided for brevity

                        String htmlToRenderAsPDF = sb.ToString();

                        //XMLWorker also reads from a TextReader and not directly from a string
                        using (var srHtml = new StringReader(htmlToRenderAsPDF))
                        {
                            XMLWorkerHelper.GetInstance().ParseXHtml(writer, doc, srHtml);
                        }

                        doc.Close();
                    }
                }
                try
                {
                    var bytes = ms.ToArray();
                    // This is currently saved to a location on the server such as C:\Users\TEMP.SP.005\Desktop\iTextSharpTest.pdf (but the number (such as 
"005" irregularly increments))
                    String pdfFileID = GetYYYYMMDDAndUserNameAndAmount();
                    String pdfFileName = String.Format("DirectPayDynamic_{0}.pdf", pdfFileID);
                    String fileFullpath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory), pdfFileName);
                    String fileLinkBase = "Generated PDF: <a rel='nofollow' href=\"{0}\">{1}</a>";
                    String filelink = String.Format(fileLinkBase, fileFullpath, pdfFileName);
                    File.WriteAllBytes(fileFullpath, bytes);

                    var pdflink = new Label
                    {
                        CssClass = "finaff-webform-field-label",
                        Text = filelink
                    };
                    this.Controls.Add(pdflink);
                }
                catch (DocumentException dex)
                {
                    throw (dex);
                }
                catch (IOException ioex)
                {
                    throw (ioex);
                }
                catch (Exception ex)
                {
                    throw (ex);
                }
            }
        } // GeneratePDF

...afford the user the opportunity to save that file to their local machine (currently, it is being saved on the server).

IOW, what I basically want to do is replace this line:

String fileFullpath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory), pdfFileName);

...with something like:

String fileFullpath = "Hey, bloke (or blokette), where do you want to save this?"

This is obviously possible, and even somewhat common, as many websites will generate files for you and then allow you to save those

generated files to either a location you select or a default location, such as your downloads folder.

Either a server-side (C#) or a client-side (jQuery) solution is acceptable, although I prefer server-side, as that is where the PDF is being generated.


Source: (StackOverflow)

Advertisements

FileSaver does nothing

What is wrong with the following code that it does not download/save?

https://jsfiddle.net/36nuqrqm/

function save_file()
{
	var blob = new Blob(["Hello, world!"], {type: "text/plain;charset=utf-8"});
	saveAs(blob, "hello world.txt");
}
<script src="https://raw.githubusercontent.com/eligrey/FileSaver.js/master/FileSaver.js"></script>

aaa
<button id="b" onclick="save_file()">export to CSV</button>
bbb

I am using file saver library

And here is example of its working code


Source: (StackOverflow)

FileSaver.js works for text files but not binaries

I have an server API and a javascript frontend that downloads files from the server. Im using FileSaver (https://github.com/eligrey/FileSaver.js) to save the downloaded document data to the local filesystem. The solution works well for text files but not for the binaries. I've verified that in both cases the server sends the correct content. It's FileSaver that seems unable to save my binary content correctly. What gets saved is more or less trash, with the wrong file size.

Javascript:

    $http({
        method: 'GET',
        cache: false,
        url: <URL>,            
        headers: {
            'Content-Type': 'application/octet-stream',
            'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
            'accept-encoding': 'identity',
        }
    }).success(function (data, status, headers, config) {
        console.log(headers());
        console.log(headers('Content-Disposition'));
        var res = headers('Content-Disposition').split('=');
        console.log(res);
        var fileName = res[1];
        console.log(fileName);
        var blob = new Blob([data]);
        saveAs(blob, fileName);
     }

The server side:

@GET
@Produces(MediaType.APPLICATION_OCTET_STREAM)
public Response downloadDocument(@PathParam("documentId") UUID theid) {
    doc = <retrieve document>
    StreamingOutput stream = new StreamingOutput() {

        public void write(OutputStream output) throws IOException, WebApplicationException {
            try {                                      
               InputStream istream = new ByteArrayInputStream(doc.getData());
               System.out.println(doc.getData().length);
               IOUtils.copy(istream, output);

            } catch (Exception e) {
                throw new WebApplicationException(e);
            }
        }
    };

    return Response.ok(stream).header("Content-Disposition", "attachment; filename=" + doc.getName()).build();
}

Source: (StackOverflow)

image slicing, only saves (via Filesaver.js) last slice in sequence

Hi I'm writing a function to break up a large image into individual smaller tiles, and save the tiles locally via Filesaver.js. However, for some reason, the for-loop keeps writing only the last tile in. For example, if I have a image and break it up into 4 blocks, and only decide to write out two blocks in the first row, both saved image tiles display the 2nd image tile.

I also write out the block number into the image name (TestImage_0.jpg & TestImage_1.jpg), but both tile image names are TestImage_1.jpg. I have no clue why!, even tried context.clearRect, but no success. Can someone please help me out here with this silly problem? Here is my function:

var canvas = document.createElement('canvas');

var TileWidthpx = parseInt(document.getElementById("HorizPPT").value);
var TileHeightpx = parseInt(document.getElementById("VertPPT").value);
canvas.setAttribute('width', TileWidthpx);
canvas.setAttribute('height', TileHeightpx);

for(var i = 0; i < 2; i++)
{   
    var context = canvas.getContext('2d');
    context.clearRect(0,0,canvas.width,canvas.height);
    context.drawImage(CoverageImg,i*TileWidthpx,0,TileWidthpx,TileHeightpx,0,0,TileWidthpx,TileHeightpx); 

    canvas.toBlob(function(blob){saveAs(blob,'TestImage_'+i+'.jpg');}, "image/jpg");

    alert('done: '+i);
}

Even though the alert displays the correct 'i' value of the loop... Please, anybody, is it some javascript async-problem that I'm missing (also converted the algorithm to a Promise, but that didn't solve anything)


Source: (StackOverflow)

Download pdf file automaticaly using Angular Js

I Have an API made using WEB API which gives a pdf file using type as HttpResponseMessage.

This API is being called from a web application, which uses Angular Js.

My problem is, i am not able to download the file when this API is called. It gives me corrupted file.

Here is my WebAPI code

            HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
            byte[] fileBytes = System.IO.File.ReadAllBytes(outputFilePath);
            response.Content = new ByteArrayContent(fileBytes);
            response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
            //response.Content.Headers.ContentDisposition.FileName = "Certificate#" + ideaModel.IdeaNumber + ".pdf";
            response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");

            return new CertificateModel { file = response, fileName = "Certificate#" + ideaModel.IdeaNumber.ToString()+".pdf" };

In angular JS i am calling URL, and trying to save file using FileSaver.js

  $http.post(getUrl('api/Reward/DeliverGift'),
        {
            IdeaNumber: '4',
            SubmittedBy: 'Self',
        },{responseType: 'arraybuffer'}
    ).then(function (response) {            
        var certificateFile = new Blob([response.data.file], { type: 'application/pdf' });
        saveAs(certificateFile, response.data.fileName );

    }, function (errors) {         
    });

My original file is of 195Kb, however above code gives me a file of 9 bytes

Any Help will be appriciated


Source: (StackOverflow)

Saving file to specific local directory or folder using jspdf

I am using Filesave.js to save file generated from JSPDF library, and want to save it to a specific folder like C:\PDF\Test.pdf

I am using below code but it is not working.

var filename = "C:/Test.pdf"
pdf.save(filename);

Source: (StackOverflow)

Send file from nodejs server to angularjs client

I want to send file from node.js server to client on agular. I'm use fileSaver.js on client.

Server:

res.download('123.txt', function(err){
    if(err){
        console.log('error');
    }
})

Cliet:

$http.post('/downloadFile').success(function(res){
   var file = new Blob([res]);
   saveAs(file, '123.txt');
}

But it works only with .txt files. How to do this with other formats?


Source: (StackOverflow)

AngularJs, FileSaver Export To Excel with Turkish Chars?

I can export to Excel with FileSaver in my solution. Here my sources:

tapuController.cs:

   [Route("Tapu/tcKimlikNoIleToEcel")]
    public void tcKimlikNoIleToEcel(string tcKimlikNo)
    {

        List<TapuZeminModel> zeminler = new List<TapuZeminModel>();
        zeminler = TapuModule.GetZeminListFromTcNo(tcKimlikNo);
        List<TapuZeminViewModel> zeminList = new List<TapuZeminViewModel>();

        foreach (var zemin in zeminler)
        {
            foreach (var hisse in zemin.Hisseler)
            {
                TapuZeminViewModel ze = new TapuZeminViewModel();
                ze.Ad = hisse.Kisi.Ad;
                ze.AdaNo = zemin.AdaNo;
                if (zemin.KatMulkiyeti != null)
                {
                    ze.ArsaPay = zemin.KatMulkiyeti.ArsaPay;
                    ze.ArsaPayda = zemin.KatMulkiyeti.ArsaPayda;
                    ze.BagimsizBolumNo = zemin.KatMulkiyeti.BagimsizBolumNo;
                    ze.Blok = zemin.KatMulkiyeti.Blok;
                    ze.Giris = zemin.KatMulkiyeti.Giris;
                }
                ze.Cilt = zemin.CiltNo;
                ze.EdinmeSebep = hisse.EdinmeSebep;
                ze.HisseId = hisse.TapuKod;
                ze.HissePay = hisse.HissePay;
                ze.HissePayda = hisse.HissePayda;
                ze.Il = zemin.Il.Ad;
                ze.Ilce = zemin.Ilce.Ad;
                ze.KisiId = hisse.Kisi.TapuKod;
                ze.ParselNo = zemin.ParselNo;
                ze.Sayfa = zemin.SayfaNo;
                ze.Kurum = zemin.Kurum.Ad;
                ze.ZeminId = zemin.TapuKod;
                ze.ZeminTip = zemin.ZeminTip.Ad;
                ze.Mahalle = zemin.Mahalle.Ad;
                ze.Nitelik = zemin.AnaTasinmaz.Nitelik;
                ze.Mevkii = zemin.AnaTasinmaz.Mevkii;
                if (hisse.Kisi.GercekKisi != null)
                {
                    ze.SoyAd = hisse.Kisi.GercekKisi.SoyAd;
                    ze.TcKimlikNo = hisse.Kisi.GercekKisi.TcKimlikNo;
                }
                if (hisse.Kisi.TuzelKisi != null)
                {
                    ze.TuzelKisiAd = hisse.Kisi.TuzelKisi.Ad;
                    ze.VergiNo = hisse.Kisi.TuzelKisi.VergiNo;
                    ze.SicilNo = hisse.Kisi.TuzelKisi.SicilNo;
                }

                zeminList.Add(ze);
            }
        }


        StringBuilder dosyaAdi = new StringBuilder();
        dosyaAdi.Append(DateTime.Now.ToString("dd.MM.yyyy HH.mm"));
        dosyaAdi.Append("-" + tcKimlikNo);
        dosyaAdi.Append(".xls");

        GridView gv = new GridView();
        gv.DataSource = zeminList;
        gv.DataBind();
        Response.ClearContent();
        Response.Buffer = true;
        Response.AddHeader("content-disposition", "attachment; filename=" + dosyaAdi.ToString());
        Response.ContentType = "application/ms-excel=utf-8";
        Response.ContentEncoding = System.Text.Encoding.Unicode;
        Response.BinaryWrite(System.Text.Encoding.Unicode.GetPreamble());
        StringWriter sw = new StringWriter();
        HtmlTextWriter htw = new HtmlTextWriter(sw);
        gv.RenderControl(htw);
        Response.Output.Write(sw.ToString());
        Response.Flush();
        Response.End();

    }

tapuControllerService.js:

angular.module('TapuAppModule')
.factory('TapuControllerService', function TapuIlApiFactory($http) {
    return {
        adaParselSorguToExcel: function (zeminArg) {
            return $http({ method: "GET", url: "Tapu/ExportToExcel", params: { ada: zeminArg.Ada, ilceId: zeminArg.IlceId, mahId: zeminArg.MahalleId, parsel: zeminArg.Parsel } });
        },
        tcKimlikNoIleToEcel: function (manuelTcKimlikNo) {
            return $http({ method: "GET", url: "Tapu/tcKimlikNoIleToEcel", params: { tcKimlikNo: manuelTcKimlikNo } });
        },
        kurumIdIleToEcel: function (manuelKurumId) {
            return $http({ method: "GET", url: "Tapu/kurumIdIleToEcel", params: { kurumId: manuelKurumId } });
        }
    }
});

tapuController.js:

 $scope.exportToExcel = function () {
        $scope.ZeminArg = {
            Ada: $scope.selectedAdaNo,
            Parsel: $scope.selectedParselNo,
            MahalleId: $scope.selectedMahalle,
            IlceId: $scope.selectedIlce
        };

        if (document.getElementById('adaparsel').className == "tab-pane fade active in") {
            var fileName = "MahalleId-" + $scope.ZeminArg.MahalleId + "_IlceId-" + $scope.ZeminArg.IlceId + "_AdaNo-" + $scope.ZeminArg.Ada + "_ParselNo-" + $scope.ZeminArg.Parsel;
            TapuControllerService.adaParselSorguToExcel($scope.ZeminArg)
            .success(function (data) {
                var blob = new Blob([data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=iso-8859-9', encoding: 'Windows-1254' });
                saveAs(blob, datetime + '-' + fileName + '.xls');
            }).error(function () {
                //Some error log
            });
        }

        if (document.getElementById("tckimlikno").className == "tab-pane fade active in") {
            var fileName = "TcNo-" + $scope.manuelTcKimlikNo;
            TapuControllerService.tcKimlikNoIleToEcel($scope.manuelTcKimlikNo)
            .success(function (data) {
                var blob = new Blob([data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=iso-8859-9', encoding: 'Windows-1254' });
                saveAs(blob, datetime + '-' + fileName + '.xls');
            }).error(function () {
                //Some error log
            });
        }

        if (document.getElementById("kurum").className == "tab-pane fade active in") {
            var fileName = "kurum-" + $scope.manuelKurumId;
            TapuControllerService.kurumIdIleToEcel($scope.manuelKurumId)
            .success(function (data) {
                var blob = new Blob([data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=iso-8859-9', encoding: 'Windows-1254' });
                saveAs(blob, datetime + '-' + fileName + '.xls');
            }).error(function () {
                //Some error log
            });
        }

    };

And i'm using FileSaver. Here filesaver Url Everything is ok. It's working. But i can't use Turkish chars. I tried some encoding but not worked. Here is my error's pic:

enter image description here

For example first SoyAd is : FERİKOĞLU Second row Ad is : ALATTİN

etc. What should i do for output Excel with Turkish Chars??


Source: (StackOverflow)

List items adding unnecessary rows to an xls export

The 'formatted' filter outputs html markup for an unordered list with several list items. The 'ng-bind-html' then displays the list within the datafield. This works as expected within the web application, making the feedback more readable but on exporting to an .xls file, using the Filesaver.js library, a separate row is created for each list item.

This ultimately causes issues within Excel when trying to filter, for example, filtering on the date '01/01/01' would display only the 'first list item'.

Is there a better way of achieving the export, and/or the initial presentation of the content?

page.html

<table id="feedbackTbl">
    <tr>        
        <th>Date</th>
        <th>Feedback Content</th>
    </tr>

    <tr ng-repeat="feedback in feedbackData">    
        <td>{{feedback.Date}}</td>   
        <td ng-bind-html="feedback.FeedbackContent | formatted"></td>
    </tr>
</table>

controller.js

app.filter("formatted", function () {
    return function (text) {
        var obj = JSON.parse(text);
        var output = "<ul>";
        $.each(obj, function (key, value) {
            output += "<li>" + key + ": " + value + "</li>";
        });
        return output += "</ul>";
    }
});

function exportExcel() {
    var blob = new Blob([$('#feedbackTbl').html()], {
        type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8"
    });
    saveAs(blob, "Report.xls");
}

Report.xls

Row   Date      |    FeedbackContent

 1 |    01/01/01 |  first list item
 2 |             |  second list item
 3 |             |  third list item
 4 |    12/09/01 |  first list item
 5 |             |  second list item
 6 |             |  third list item

Source: (StackOverflow)

How to display in a browser window a client-side pdf generated by jsPDF with images?

I'm generating a pdf file at client side with jsPDF: my HTML structure is as follows:

<script src="js/libs/zlib.js"></script>
<script src="js/libs/png.js"></script>
<script src="js/libs/Blob.js"></script>
<script src="js/libs/FileSaver.js"></script>
<script src="js/libs/jspdf.js"></script>
<script src="js/libs/standard_fonts_metrics.js"></script>
<script src="js/libs/split_text_to_size.js"></script>
<script src="js/libs/png_support.js"></script>
<script src="js/libs/addimage.js"></script>

This is my code to generate the PDF:

function createPDF (docTitle, fileName) {
    var doc = new jsPDF("p", "mm", "a4");
    var scale = 10;
    var img = new Image();
    img.onload = function() {
        doc.addImage(this, 'png', 5, 5, img.width / scale, img.height / scale);
    }
    img.src = "img/logo.png";
    if(img.complete) img.onload();
    var canvas = document.getElementById('cv');
    var context = canvas.getContext('2d');
    var imgData = canvas.toDataURL("image/jpeg", 1.0);
    doc.setFontSize(30);
    doc.text(35, 35, docTitle);
    doc.addImage(imgData, 'JPEG', 15, 40, 180, 180);
    return doc;
};

To open the file in another browser window i'm using:

var doc = createPDF(docTitle, fileName);
doc.output("save", fileName);

This works well in the majority of browser i tested except Safari for Windows and Android KitKat legacy browser. For example, When i try to open the generated PDF in Safari 5.1.7 for Windows, the "Do you want to open or save this file?" dialog is displayed and i see the "data.applcation/pdf;base64,JVBER...." fallback for BLOBs of Filesaver.js.

In most of the tested browsers also my function createPDF is not working wery well with images: in some browsers the PNG is not displayed, in some other the jpeg is not displayed. Moreover, also the examples on jsPDF website are not fully functional with Safari for Windows, although the statement is: "jsPDF will work in IE6+*, Firefox 3+, Chrome, Safari 3+, Opera".

BTW, the great FileSaver.js demo on http://eligrey.com is working well in all browser i tested, also for BLOBs. Sadly, there isn't a demo with a PDF content type.

Here a short list of tests:

  • Ipad - Safari 5.1.1 Works, Chrome works
  • Windows Safari 5.1.7 (last Windows version) won't work
  • ... in the middle: most works, some not
  • Mac Yosemite Safari 8.0.3 Works
  • iPhone Safari 8.04 Works, (Chrome: won't work)
  • Android 4 Kitkat Legacy Browser: won't work, Chrome Yes Firefox Yes

I know this is an old thread in SO, and jsPDF and Filesaver are great piece of software and we cannot be thankful enough to to the authors and contributors, but and i'm wonder if nobody there was able after so many years and threads, to find a "stable" solution.

What i'm doing wrong with images?

Which is the right way to open a PDF generated fully client-side by jsPDF in a separate browser window - without to use an additional round-trip to the server, and that is working well also in most browsers?


Source: (StackOverflow)

Implementing FileSaver.js saveAs() function into HTML script

Right now I am attempting to save information from an HTML page that I am creating to a text document, using javascript and the FileSaver.js package. I am not very well versed in HTML and am completely new to javascript, so odds are that I am making some egregious mistake. At the moment, I have eligrey's FileSaver.js file in the same directory as the HTML file that I am working from, so I should be able to call it simply as "FileSaver.js" in HTML.

Right now I am working from something like this:

//some irrelevant text

<script src="FileSaver.js">
  function download(){
    
    //alert("hello world");
    //this alert line was to test the function call
    //the alert actually appears when the <script> tag
    // has no src field labeled. Just an observation.
    
    var blob = new Blob(["Hello World"],{type:"text/plain;charset=utf-8"});
    saveAs(blob,"helloworld.txt");
   }
</script>

//some more irrelevant text

<input type="button" value="download" onclick="download();"/>
/*from this button I want to gather information from input text fields on the page.
 I already know how to do that, the problem is creating and, subsequently, 
downloading the text file I am trying to create. For simplicity's sake, the text I am 
capturing in this example is hardcoded as "hello world"*/

//last of irrelevant text
//oh, and don't try to run this snippet :P

I also have eligrey's Blob.js file available in my immediate working directory as well, just in case.

As of now, the button does nothing. I am fairly sure that I am calling the function correctly considering I could receive the javascript alert text, at least when the script tag had no src. If I do add a src, absolutely nothing happens. The browser that I am testing from is the latest Google Chrome stable build (43.0 I think) on Windows XP. Please inform me of anything that I am missing and/or doing wrong. Thanks in advance


Source: (StackOverflow)