Rectangle 27 26

This is because you define your "doc" variable outside of your click event. The first time you click the button the doc variable contains a new jsPDF object. But when you click for a second time, this variable can't be used in the same way anymore. As it is already defined and used the previous time.

$(function () {

    var specialElementHandlers = {
        '#editor': function (element,renderer) {
            return true;
        }
    };
 $('#cmd').click(function () {
        var doc = new jsPDF();
        doc.fromHTML(
            $('#target').html(), 15, 15, 
            { 'width': 170, 'elementHandlers': specialElementHandlers }, 
            function(){ doc.save('sample-file.pdf'); }
        );

    });  
});

Thank you Kristof Feys, but when I click on the button I can see 2 windows. one is save to PDF window and one more new window is opening with pdf view, How can I remove PDf view in new window...

Hmmm... when i tested this in jsFiddle i only received the "save to pdf" window. My guess would be that these 2 windows are browser / plugin related...

Yes, In jsFiddle it is getting only SaveTo PDF window, but in Main Application It is getting one more window opened when user click,How can i remove that new window.

As I am unable to reproduce your issue, i can't really debug it either. You could probably try to remove all your javascript plugins used (except jquery & jspdf) and see if it works then. Afterwards you can re add them one by one to see which one produces the error (if my guess is correct and one of these are producing the issue of course) ... Or if you could reproduce the issue on jsFiddle that could help as well :)

$(document).ready(function) and $(function) are identical; learn.jquery.com/using-jquery-core/document-ready just says, "If you are writing code that people who aren't experienced with jQuery may see, it's best to use the long form."

jquery - Export HTML page to PDF on user click using JavaScript - Stac...

javascript jquery jspdf
Rectangle 27 476

You can do this in native JavaScript. You'll have to parse your data into correct CSV format as so (assuming you are using an array of arrays for your data as you have described in the question):

const rows = [["name1", "city1", "some other info"], ["name2", "city2", "more info"]];
let csvContent = "data:text/csv;charset=utf-8,";
rows.forEach(function(rowArray){
   let row = rowArray.join(",");
   csvContent += row + "\r\n"; // add carriage return
});
var data = [["name1", "city1", "some other info"], ["name2", "city2", "more info"]];
var csvContent = "data:text/csv;charset=utf-8,";
data.forEach(function(infoArray, index){

   dataString = infoArray.join(",");
   csvContent += index < data.length ? dataString+ "\n" : dataString;

});

Then you can use JavaScript's window.open and encodeURI functions to download the CSV file like so:

var encodedUri = encodeURI(csvContent);
window.open(encodedUri);
window.open
<a>
download
var encodedUri = encodeURI(csvContent);
var link = document.createElement("a");
link.setAttribute("href", encodedUri);
link.setAttribute("download", "my_data.csv");
document.body.appendChild(link); // Required for FF

link.click(); // This will download the data file named "my_data.csv".

Note: as of this edit, support for the download attribute is limited to Chrome only. I believe FF is in the process of implementing it, and IE always lags behind them both.

From what I know, there isn't a way to do that using window.open. However, you can create a hidden link that has a download attribute set to the file name you desire. Then "clicking" this link will download the file in the name you desire, I will add it to my answer.

document.body.appendChild(link);
data = [["Hello, world"]]

try writing it into a blob and then getting a blob url.

This works fine for like ~7000 rows. But starts giving this error : NETWORK_INVALID_REQUEST. Is any body else facing this issue too? Is there any upper limit of data on encodeURIComponent() function or something? I am using Chrome as the browser.

@Sam007: works in Firefox too.

Sign up for our newsletter and get our top new questions delivered to your inbox (see an example).

How to export JavaScript array info to csv (on client side)? - Stack O...

javascript csv dojo export client-side
Rectangle 27 475

You can do this in native JavaScript. You'll have to parse your data into correct CSV format as so (assuming you are using an array of arrays for your data as you have described in the question):

const rows = [["name1", "city1", "some other info"], ["name2", "city2", "more info"]];
let csvContent = "data:text/csv;charset=utf-8,";
rows.forEach(function(rowArray){
   let row = rowArray.join(",");
   csvContent += row + "\n";
});

Then you can use JavaScript's window.open and encodeURI functions to download the CSV file like so:

var encodedUri = encodeURI(csvContent);
window.open(encodedUri);
window.open
<a>
download
var encodedUri = encodeURI(csvContent);
var link = document.createElement("a");
link.setAttribute("href", encodedUri);
link.setAttribute("download", "my_data.csv");
document.body.appendChild(link); // Required for FF

link.click(); // This will download the data file named "my_data.csv".

From what I know, there isn't a way to do that using window.open. However, you can create a hidden link that has a download attribute set to the file name you desire. Then "clicking" this link will download the file in the name you desire, I will add it to my answer.

document.body.appendChild(link);
data = [["Hello, world"]]

This works fine for like ~7000 rows. But starts giving this error : NETWORK_INVALID_REQUEST. Is any body else facing this issue too? Is there any upper limit of data on encodeURIComponent() function or something? I am using Chrome as the browser.

Sign up for our newsletter and get our top new questions delivered to your inbox (see an example).

How to export JavaScript array info to csv (on client side)? - Stack O...

javascript csv dojo export client-side
Rectangle 27 475

You can do this in native JavaScript. You'll have to parse your data into correct CSV format as so (assuming you are using an array of arrays for your data as you have described in the question):

const rows = [["name1", "city1", "some other info"], ["name2", "city2", "more info"]];
let csvContent = "data:text/csv;charset=utf-8,";
rows.forEach(function(rowArray){
   let row = rowArray.join(",");
   csvContent += row + "\n";
});

Then you can use JavaScript's window.open and encodeURI functions to download the CSV file like so:

var encodedUri = encodeURI(csvContent);
window.open(encodedUri);
window.open
<a>
download
var encodedUri = encodeURI(csvContent);
var link = document.createElement("a");
link.setAttribute("href", encodedUri);
link.setAttribute("download", "my_data.csv");
document.body.appendChild(link); // Required for FF

link.click(); // This will download the data file named "my_data.csv".

From what I know, there isn't a way to do that using window.open. However, you can create a hidden link that has a download attribute set to the file name you desire. Then "clicking" this link will download the file in the name you desire, I will add it to my answer.

document.body.appendChild(link);
data = [["Hello, world"]]

This works fine for like ~7000 rows. But starts giving this error : NETWORK_INVALID_REQUEST. Is any body else facing this issue too? Is there any upper limit of data on encodeURIComponent() function or something? I am using Chrome as the browser.

How to export JavaScript array info to csv (on client side)? - Stack O...

javascript csv dojo export client-side
Rectangle 27 65

iText has more than one way of doing this. The PdfStamper class is one option. But I find the easiest method is to create a new PDF document then import individual pages from the existing document into the new PDF.

// Create output PDF
Document document = new Document(PageSize.A4);
PdfWriter writer = PdfWriter.getInstance(document, outputStream);
document.open();
PdfContentByte cb = writer.getDirectContent();

// Load existing PDF
PdfReader reader = new PdfReader(templateInputStream);
PdfImportedPage page = writer.getImportedPage(reader, 1); 

// Copy first page of existing PDF into output PDF
document.newPage();
cb.addTemplate(page, 0, 0);

// Add your new data / text here
// for example...
document.add(new Paragraph("my timestamp")); 

document.close();

This will read in a PDF from templateInputStream and write it out to outputStream. These might be file streams or memory streams or whatever suits your application.

When I used this method the PDF came out all misaligned. Therefore I went with Mark Storer's answer and used PdfStamper.

This is working Fine , But pages with acrofields are not copying with them in cb.addTemplate(page,0,0). Acrofields are not available in output pdf

java - iText - add content to existing PDF file - Stack Overflow

java pdf itext
Rectangle 27 51

You should add the UTF-8 BOM at the start of the text, like:

var csvContent = "data:text/csv;charset=utf-8,%EF%BB%BF";

It worked for me with Excel 2013.

can you provide a full working example in jsFiddle or something?

This worked for me, using FileSaver.js. Instead of URL-encoding, I did this: var blob = new Blob(['\ufeff' + csvString], {type: 'text/csv;charset=utf-8'});

Javascript to csv export encoding issue - Stack Overflow

javascript csv export-to-csv
Rectangle 27 959

JavaScript can read the DOM and render a fairly accurate representation of that using canvas. I have been working on a script which converts html into an canvas image. Decided today to make an implementation of it into sending feedbacks like you described.

The script allows you to create feedback forms which include a screenshot, created on the clients browser, along with the form. The screenshot is based on the DOM and as such may not be 100% accurate to the real representation as it does not make an actual screenshot, but builds the screenshot based on the information available on the page.

It does not require any rendering from the server, as the whole image is created on the clients browser. The HTML2Canvas script itself is still in a very experimental state, as it does not parse nearly as much of the CSS3 attributes I would want it to, nor does it have any support to load CORS images even if a proxy was available.

edit The html2canvas script is now available separately here and some examples here.

edit 2 Another confirmation that Google uses a very similar method, (in fact based on the documentation the only major difference is their async method of traversing/drawing) can be found in this presentation by Elliott Sprehn from the Google Feedback team: http://www.elliottsprehn.com/preso/fluentconf/

Very cool, Sikuli or Selenium might be good for going to different sites, comparing a shot of the site from the testing tool to your html2canvas.js rendered image in terms of pixel similarity! Wonder if you could automatically traverse parts of the DOM with a very simple formula solver to find how to parse alternate data sources for browsers where getBoundingClientRect isn't available. I'd probably use this if it was open source, was considering toying with it myself. Nice work Niklas!

@Luke Stanley I will most likely throw the source up on github this weekend,still some minor clean ups and changes I want to do before then, as well as get rid of the unnecessary jQuery dependancy it currently has.

The source code is now available at github.com/niklasvh/html2canvas, some examples of the script in use html2canvas.hertzen.com there. Still lot of bugs to fix, so I wouldn't recommend using the script in a live environment yet.

any solution to make it work for SVG will be a great help. It does not work with highcharts.com

Using HTML5/Canvas/JavaScript to take in-browser screenshots - Stack O...

javascript html5 canvas screenshot
Rectangle 27 947

JavaScript can read the DOM and render a fairly accurate representation of that using canvas. I have been working on a script which converts html into an canvas image. Decided today to make an implementation of it into sending feedbacks like you described.

The script allows you to create feedback forms which include a screenshot, created on the clients browser, along with the form. The screenshot is based on the DOM and as such may not be 100% accurate to the real representation as it does not make an actual screenshot, but builds the screenshot based on the information available on the page.

It does not require any rendering from the server, as the whole image is created on the clients browser. The HTML2Canvas script itself is still in a very experimental state, as it does not parse nearly as much of the CSS3 attributes I would want it to, nor does it have any support to load CORS images even if a proxy was available.

edit The html2canvas script is now available separately here and some examples here.

edit 2 Another confirmation that Google uses a very similar method, (in fact based on the documentation the only major difference is their async method of traversing/drawing) can be found in this presentation by Elliott Sprehn from the Google Feedback team: http://www.elliottsprehn.com/preso/fluentconf/

Very cool, Sikuli or Selenium might be good for going to different sites, comparing a shot of the site from the testing tool to your html2canvas.js rendered image in terms of pixel similarity! Wonder if you could automatically traverse parts of the DOM with a very simple formula solver to find how to parse alternate data sources for browsers where getBoundingClientRect isn't available. I'd probably use this if it was open source, was considering toying with it myself. Nice work Niklas!

@Luke Stanley I will most likely throw the source up on github this weekend,still some minor clean ups and changes I want to do before then, as well as get rid of the unnecessary jQuery dependancy it currently has.

The source code is now available at github.com/niklasvh/html2canvas, some examples of the script in use html2canvas.hertzen.com there. Still lot of bugs to fix, so I wouldn't recommend using the script in a live environment yet.

any solution to make it work for SVG will be a great help. It does not work with highcharts.com

Using HTML5/Canvas/JavaScript to take in-browser screenshots - Stack O...

javascript html5 canvas screenshot
Rectangle 27 35

The DPI doesn't matter at all when dealing with images. Images are measured in pixels so this is what you need to adjust. You can safely disregard DPI as it has no sense in this context.

Scaling won't help you here - remember you are working with a pixel device, not vectors, so the canvas need to be already in the size you want to use for print etc. or you will have reduced quality due to interpolation when scaling it.

You need to pre-calulate your canvas size in pixels in relation to what size you want in the final stage.

Lets say you want to print a 15 x 10 cm image (or about 6 x 4 inches) @ 300DPI output. You then calculate the pixels:

Width : 10 cm * 300 / 2.54 = 1181 pixels
Height: 15 cm * 300 / 2.54 = 1772 pixels
Width : 4 in * 300 = 1200 pixels
Height: 6 in * 300 = 1800 pixels
26.45 cm * 300 DPI / 2.54 inches = 3124 pixels.

To display that canvas in a smaller area on screen you use CSS to display the element, for example -

<canvas width="3124" height="3124" style="width:600px;height:600px;"></canvas>

You can now draw to the canvas at its actual pixel position and it will show up scaled down on screen (but retain all information on the canvas itself). If you use mouse coordinates you just scale the mouse position proportionally (canvas pos = mouse coord * 3124px / 600px).

For zooming etc it becomes a tad more complicated, but the principle remains: the final size of your image must be that of the final result.

About DPI: if this image was 72 DPI or 300 DPI the numbers of pixels would be the exact same. The reason as already mentioned is that images are measured in pixels.

DPI is an arbitrary value when it comes to pixel devices (bitmaps, monitors, cameras etc.) and is only used for a DTP software to get a hint on dimension for final print which will use this information only to pre-scale the image in relation to the page you using to set the print with.

@K3N: I followed your suggestion, but I am stuck on a problem, the texts which are being placed are very small.please look at the fiddle jsfiddle.net/Q3TMA/1042

@Abhinav the font size must be scaled up in advance before drawn. You can use scale() for this or try with the font height directly. The latter is not always linear due to how font are made, but you should be able to get close.

But still the sized controls are appearing small, and what can be done for images?

@Abhinav I suggest you open this as a new question. My answer here only covers the underlying principle.

php - What is the best practice to export canvas with high quality ima...

php canvas html5-canvas fabricjs imagick
Rectangle 27 40

Gutch's code is close, but it'll only work right if:

  • The page size happens to be A.4 (decent odds, but it won't work on any ol' PDF you happen to come across)
  • You don't mind losing all the original document metadata (producer, creation date, possibly author/title/keywords), and maybe the document ID. You can't copy the creation date and doc ID unless you do some pretty deep hackery on iText itself).

The Approved Method is to do it the other way around. Open the existing document with a PdfStamper, and use the returned PdfContentByte from getOverContent() to write text (and whatever else you might need) directly to the page. No second document needed.

And you can use a ColumnText to handle layout and such for you... no need to get down and dirty with beginText(),setFontAndSize(),drawText(),drawText()...,endText().

All excellent points... that's a good way to determine whether the PdfStamper or the addTemplate method is better for your scenario. In my case the addTemplate is clearly better because of your points: I get give a source template by a graphic designer that was generated in Adobe Illustrator, has lots of junk and metadata and weighs in at 1MB. If I used PdfStamper the generated documents would be 1MB+ and have the name of a contract graphic designer in them; by using addDocument they documents are 50kB and have no personal information embedded.

Wow. That's a HUGE size change. Metadata isn't that large... what's taking up the rest of the space?!

I think those big PDFs would have had the 'Preserve Illustrator Editing Capabilities' box checked, which saves all the Adobe Illustrator info in the file to allow further editing. It's a bit like creating a PDF from a document and embedding the source DOC file in it.

Example of using CT on existing Stamper: over = PdfStamper.getOverContent(1); ct = new ColumnText( over ); ct.setSimpleColumn(120,48,200,500); p = new Paragraph(24, new Chunk("some multi line") ); ct.addElement( p ); ct.go();

java - iText - add content to existing PDF file - Stack Overflow

java pdf itext
Rectangle 27 10

I guess first off, we'll go through what's wrong with your code I guess. First of all, rather than setTimeout, the "pdf-ing" code should be inside onRendered as potentially, you might find that the code runs before the canvas could be rendered.

data:application/pdf;base64,
data:image/PNG;base64,BASE64DATAHERE...
data:application/pdf:base64,
data:application/pdf:base64,data:image/PNG;base64,BASE64DATAHERE...
PNG
jpeg
//datauri is an image with a datauri of a png
prefixJpg.src="data:image/jpeg;base64,"+datauri.src
replaceJpg.src="data:image/jpeg;base64,"+datauri.src.substring(22) 
//remove the first 22 characters

The prefixing one cannot be rendered as it's not a valid base64 image data.

Continuing on, looking at the output, we note that, the image with the jpeg datauri, has transparent background. JPEG can't have transparent background. So in essence, the data is still PNG, and only because lenient renderer that the browser accepts that though it says it's jpeg it's actually still png, and still show it.

This brings us to the final problem with your code. As far as I know, in most cases, you can't actually convert something by just changing the datauri. I tried testing this by manually changing an image datauri to a datauri with pdf prefix. Chrome loaded it's builtin pdf plugin but it "failed to load".

Looking around there's actually a pdf writer written in javascript:

It has a pdf rendered that you can use and has all sorts of methods that you can look at. As an example, you can create a pdf from a datauri with the .addImage() method. I updated your code to use jsPDF.

html2canvas(document.body, {
  onrendered: function(canvas) {
    var pdf = new jsPDF();
    var marginLeft=20;
    var marginRight=20
    pdf.addImage(canvas.toDataURL("image/jpeg"),"jpeg",marginLeft,marginRight)
    window.location=pdf.output("datauristring")
  }
});

And it seems to work well.

Thank you for the detailed explanation. Unfortunately pdfJS doesnt seem to be a good solution for my specific problem. When using the .fromHTML function pdfJS seems to ignore all styling attributes, as you can see here. So although it does generate the pdf like I want, it loses alot in its conversion process.

There's probably a way to use the .fromHTMLbut I guess for quick fix and in answering you question, jsPDF (sorry I misnamed the thing) has an addImage(). I'll update my answer

Thanks @mfirdaus that seemed to do the trick.

javascript - Html to Canvas to Base64 to PDF - Stack Overflow

javascript html5 pdf canvas html2canvas
Rectangle 27 129

Based on the answers above I created this function that I have tested on IE 11, Chrome 36 and Firefox 29

function exportToCsv(filename, rows) {
        var processRow = function (row) {
            var finalVal = '';
            for (var j = 0; j < row.length; j++) {
                var innerValue = row[j] === null ? '' : row[j].toString();
                if (row[j] instanceof Date) {
                    innerValue = row[j].toLocaleString();
                };
                var result = innerValue.replace(/"/g, '""');
                if (result.search(/("|,|\n)/g) >= 0)
                    result = '"' + result + '"';
                if (j > 0)
                    finalVal += ',';
                finalVal += result;
            }
            return finalVal + '\n';
        };

        var csvFile = '';
        for (var i = 0; i < rows.length; i++) {
            csvFile += processRow(rows[i]);
        }

        var blob = new Blob([csvFile], { type: 'text/csv;charset=utf-8;' });
        if (navigator.msSaveBlob) { // IE 10+
            navigator.msSaveBlob(blob, filename);
        } else {
            var link = document.createElement("a");
            if (link.download !== undefined) { // feature detection
                // Browsers that support HTML5 download attribute
                var url = URL.createObjectURL(blob);
                link.setAttribute("href", url);
                link.setAttribute("download", filename);
                link.style.visibility = 'hidden';
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
            }
        }
    }
window.open
else
link.download !== undefined

In Safari link.download and setting link.style do not work. It works when juggling a few lines around restrict the link.download checking by these lines: if (link.download !== undefined) { link.setAttribute("download", filename);} else { link.setAttribute("target", "_blank");} link.setAttribute("style", "visibility:hidden");

This is a nice piece of code. Any chance you'd be willing to license this under something more liberal than the SO default of CC-BY-SA? For example, CC0, MIT, BSD, Apache, X11 . . . meta.stackexchange.com/questions/12527/

I have been using this method to implement Excel export in quite some web applications. But Chrome 43+ now has moved DOM attributes to the prototype chain. An exception is thrown at link.style.visibility='hidden'. B/c the DOM attribute is readonly. More details can be find in updates.html5rocks.com/2015/04/ under the section "Writing to read-only properties in strict mode will throw an error"

Does not work on iPad

How to export JavaScript array info to csv (on client side)? - Stack O...

javascript csv dojo export client-side
Rectangle 27 129

Based on the answers above I created this function that I have tested on IE 11, Chrome 36 and Firefox 29

function exportToCsv(filename, rows) {
        var processRow = function (row) {
            var finalVal = '';
            for (var j = 0; j < row.length; j++) {
                var innerValue = row[j] === null ? '' : row[j].toString();
                if (row[j] instanceof Date) {
                    innerValue = row[j].toLocaleString();
                };
                var result = innerValue.replace(/"/g, '""');
                if (result.search(/("|,|\n)/g) >= 0)
                    result = '"' + result + '"';
                if (j > 0)
                    finalVal += ',';
                finalVal += result;
            }
            return finalVal + '\n';
        };

        var csvFile = '';
        for (var i = 0; i < rows.length; i++) {
            csvFile += processRow(rows[i]);
        }

        var blob = new Blob([csvFile], { type: 'text/csv;charset=utf-8;' });
        if (navigator.msSaveBlob) { // IE 10+
            navigator.msSaveBlob(blob, filename);
        } else {
            var link = document.createElement("a");
            if (link.download !== undefined) { // feature detection
                // Browsers that support HTML5 download attribute
                var url = URL.createObjectURL(blob);
                link.setAttribute("href", url);
                link.setAttribute("download", filename);
                link.style.visibility = 'hidden';
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
            }
        }
    }
window.open
else
link.download !== undefined

In Safari link.download and setting link.style do not work. It works when juggling a few lines around restrict the link.download checking by these lines: if (link.download !== undefined) { link.setAttribute("download", filename);} else { link.setAttribute("target", "_blank");} link.setAttribute("style", "visibility:hidden");

This is a nice piece of code. Any chance you'd be willing to license this under something more liberal than the SO default of CC-BY-SA? For example, CC0, MIT, BSD, Apache, X11 . . . meta.stackexchange.com/questions/12527/

I have been using this method to implement Excel export in quite some web applications. But Chrome 43+ now has moved DOM attributes to the prototype chain. An exception is thrown at link.style.visibility='hidden'. B/c the DOM attribute is readonly. More details can be find in updates.html5rocks.com/2015/04/ under the section "Writing to read-only properties in strict mode will throw an error"

Does not work on iPad

How to export JavaScript array info to csv (on client side)? - Stack O...

javascript csv dojo export client-side
Rectangle 27 129

Based on the answers above I created this function that I have tested on IE 11, Chrome 36 and Firefox 29

function exportToCsv(filename, rows) {
        var processRow = function (row) {
            var finalVal = '';
            for (var j = 0; j < row.length; j++) {
                var innerValue = row[j] === null ? '' : row[j].toString();
                if (row[j] instanceof Date) {
                    innerValue = row[j].toLocaleString();
                };
                var result = innerValue.replace(/"/g, '""');
                if (result.search(/("|,|\n)/g) >= 0)
                    result = '"' + result + '"';
                if (j > 0)
                    finalVal += ',';
                finalVal += result;
            }
            return finalVal + '\n';
        };

        var csvFile = '';
        for (var i = 0; i < rows.length; i++) {
            csvFile += processRow(rows[i]);
        }

        var blob = new Blob([csvFile], { type: 'text/csv;charset=utf-8;' });
        if (navigator.msSaveBlob) { // IE 10+
            navigator.msSaveBlob(blob, filename);
        } else {
            var link = document.createElement("a");
            if (link.download !== undefined) { // feature detection
                // Browsers that support HTML5 download attribute
                var url = URL.createObjectURL(blob);
                link.setAttribute("href", url);
                link.setAttribute("download", filename);
                link.style.visibility = 'hidden';
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
            }
        }
    }
window.open
else
link.download !== undefined

In Safari link.download and setting link.style do not work. It works when juggling a few lines around restrict the link.download checking by these lines: if (link.download !== undefined) { link.setAttribute("download", filename);} else { link.setAttribute("target", "_blank");} link.setAttribute("style", "visibility:hidden");

This is a nice piece of code. Any chance you'd be willing to license this under something more liberal than the SO default of CC-BY-SA? For example, CC0, MIT, BSD, Apache, X11 . . . meta.stackexchange.com/questions/12527/

I have been using this method to implement Excel export in quite some web applications. But Chrome 43+ now has moved DOM attributes to the prototype chain. An exception is thrown at link.style.visibility='hidden'. B/c the DOM attribute is readonly. More details can be find in updates.html5rocks.com/2015/04/ under the section "Writing to read-only properties in strict mode will throw an error"

Does not work on iPad

How to export JavaScript array info to csv (on client side)? - Stack O...

javascript csv dojo export client-side
Rectangle 27 27

You can add the BOM at first, use this code and try

var BOM = "\uFEFF"; 
var csvContent = BOM + csvContent;

and then crate the file headers with the data: "text/csv;charset=utf-8"

THIS! Took forever to find something that would work. Thanks!

var downloadLink = document.createElement("a");     downloadLink.download = fileNameToSaveAs;     downloadLink.href = window.URL.createObjectURL(textFileAsBlob);     downloadLink.onclick = function (e) { document.body.removeChild(e.target); };     downloadLink.style.display = "none";     document.body.appendChild(downloadLink);     downloadLink.click();

                                                                                                                                            

Javascript to csv export encoding issue - Stack Overflow

javascript csv export-to-csv
Rectangle 27 14

The PDF operations are asynchronous at all stages. This means you also need to catch the promise at the last render as well. If you not catch it you will only get a blank canvas as the rendering isn't finished before the loop continues to the next page.

Tip: I would also recommend that you use something else than getImageData as this will store uncompressed bitmap, for example the data-uri instead which is compressed data.

Here is a slightly different approach eliminating the for-loop and uses the promises better for this purpose:

var canvas = document.createElement('canvas'), // single off-screen canvas
    ctx = canvas.getContext('2d'),             // to render to
    pages = [],
    currentPage = 1,
    url = 'path/to/document.pdf';              // specify a valid url

PDFJS.getDocument(url).then(iterate);   // load PDF document

/* To avoid too many levels, which easily happen when using chained promises,
   the function is separated and just referenced in the first promise callback
*/

function iterate(pdf) {

    // init parsing of first page
    if (currentPage <= pdf.numPages) getPage();

    // main entry point/function for loop
    function getPage() {

        // when promise is returned do as usual
        pdf.getPage(currentPage).then(function(page) {

            var scale = 1.5;
            var viewport = page.getViewport(scale);

            canvas.height = viewport.height;
            canvas.width = viewport.width;

            var renderContext = {
                canvasContext: ctx,
                viewport: viewport
            };

            // now, tap into the returned promise from render:
            page.render(renderContext).then(function() {

                // store compressed image data in array
                pages.push(canvas.toDataURL());

                if (currentPage < pdf.numPages) {
                    currentPage++;
                    getPage();        // get next page
                }
                else {
                    done();           // call done() when all pages are parsed
                }
            });
        });
    }

}

When you then need to retrieve a page you simply create an image element and set the data-uri as source:

function drawPage(index, callback) {
    var img = new Image;
    img.onload = function() {
        /* this will draw the image loaded onto canvas at position 0,0
           at the optional width and height of the canvas.
           'this' is current image loaded 
        */
        ctx.drawImage(this, 0, 0, ctx.canvas.width, ctx.canvas.height);
        callback();          // invoke callback when we're done
    }
    img.src = pages[index];  // start loading the data-uri as source
}

Due to the image loading it will be asynchronous in nature as well which is why we need the callback. If you don't want the asynchronous nature then you could also do this step (creating and setting the image element) in the render promise above storing image elements instead of data-uris.

@yltang52 I added a fiddle/demo. The url must be specified first with a valid relative or absolute url. I added more comment/info in the answer but perhaps the demo is even more clear as it shows what goes on.

@yltang52 1) it's a CORS issue. The file need to be on the same server or allow CORS usage. I use a CORS proxy for the other file to work, I did the same with your file here: jsfiddle.net/epistemex/LUNaJ/3. This is a security mechanism in the browsers. 2) It's all about formatting, CSS, parent containers etc. 3) Works in Chrome/Opera as well, and a little bit faster too :) Hope this helps! I would open new questions though for the details in 2).

@MichaelKupietz it's due to cors and the cors-proxy being used. Updated with a different cors-proxy so until that goes down. See if the new update works.. In real-world you would of course use links that are either within your page's origin or at least which allows cors usage from your origin.

Ah, thanks! This looks to be a big help for a project I'm working on.

javascript - Render .pdf to single Canvas using pdf.js and ImageData -...

javascript html5-canvas getimagedata pdf.js putimagedata
Rectangle 27 151

There's always the HTML5 download attribute :

This attribute, if present, indicates that the author intends the hyperlink to be used for downloading a resource so that when the user clicks on the link they will be prompted to save it as a local file.

If the attribute has a value, the value will be used as the pre-filled file name in the Save prompt that opens when the user clicks on the link.

Tested in Chrome and Firefox, works fine in the newest versions (as of July 2013). Works in Opera as well, but does not set the filename (as of July 2013). Does not seem to work in IE9 (big suprise) (as of July 2013).

An overview over what browsers support the download attribute can be found Here For non-supporting browsers, one has to set the appropriate headers on the serverside.

download
var A = [['n','sqrt(n)']];

for(var j=1; j<10; ++j){ 
    A.push([j, Math.sqrt(j)]);
}

var csvRows = [];

for(var i=0, l=A.length; i<l; ++i){
    csvRows.push(A[i].join(','));
}

var csvString = csvRows.join("%0A");

if (window.navigator.msSaveOrOpenBlob) {
    var blob = new Blob([csvString]);
    window.navigator.msSaveOrOpenBlob(blob, 'myFile.csv');
} else {
    var a         = document.createElement('a');
    a.href        = 'data:attachment/csv,' +  encodeURIComponent(csvString);
    a.target      = '_blank';
    a.download    = 'myFile.csv';
    document.body.appendChild(a);
    a.click();
}

Couldn't figure out how to set a filename, but I'm sure it's possible somehow. It's usually attachment;filename=somefile.csv but that doesn't seem to work for csv strings ?

I suspect they might get converted back in the actual file... but not sure

and doesn't work in IE 11 either

Export javascript data to CSV file without server interaction - Stack ...

javascript export-to-csv
Rectangle 27 20

or you can try like below

<?php
$file="demo.xls";
$test="<table  ><tr><td>Cell 1</td><td>Cell 2</td></tr></table>";
header("Content-type: application/vnd.ms-excel");
header("Content-Disposition: attachment; filename=$file");
echo $test;
?>
Content-type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet

Just an FYI: saving html as an xls file works fine for Excel 2003, but just be aware that the current version of Excel which most people have these days gives a warning when opening the file, and this is not ideal if the download is for a client. Changing the filename and mimetype for xlsx doesn't work at all (I tried!). Like the others, I recommend PHPExcel.

How to export html table to excel or pdf in php - Stack Overflow

php
Rectangle 27 16

Creating font in Jaspersoft Studio

You should use the Font Extensions mechanism.

You should create a new font with Window -> Preferences dialog:

You should create a new style with help of context menu:

After that you can set font for this style:

And after that you can use this new style:

<?xml version="1.0" encoding="UTF-8"?>
<!-- Created with Jaspersoft Studio version last-->
<jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="test_courier" language="groovy" pageWidth="595" pageHeight="842" columnWidth="555" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20" uuid="2010b76c-0fe5-4a27-9c86-6846a6f9cc6a">
    <property name="com.jaspersoft.studio.data.defaultdataadapter" value="Sample DB"/>
    <style name="CustomFont" fontName="Courier New"/>
    <queryString>
        <![CDATA[select task from tasks]]>
    </queryString>
    <field name="TASK" class="java.lang.String"/>
    <title>
        <band height="79" splitType="Stretch">
            <staticText>
                <reportElement uuid="9205f787-f3b4-4b21-b2d9-19f52824e187" style="CustomFont" x="280" y="36" width="70" height="20"/>
                <textElement/>
                <text><![CDATA[Title]]></text>
            </staticText>
        </band>
    </title>
    <detail>
        <band height="20" splitType="Stretch">
            <textField>
                <reportElement uuid="f23e8674-c45d-4dc7-92f3-93e5d0b41c16" style="CustomFont" x="0" y="0" width="70" height="20"/>
                <textElement/>
                <textFieldExpression><![CDATA[$F{TASK}]]></textFieldExpression>
            </textField>
        </band>
    </detail>
</jasperReport>

The report's design in Studio:

And the result will be (pdf file generated by Jaspersoft Studion and opened in Adobe Reader):

When export a report to PDF change the font - Stack Overflow

fonts jasper-reports export-to-pdf jaspersoft-studio
Rectangle 27 13

The best solution would be to encode your CSV in the default Excel encoding: windows-1252 (also called ANSI, which is basically a subset of ISO-8859-1).

The 2 main parts are stringencoding (to encode the content of your CSV in windows-1252) and FileSaver.js (to download the generated Blob).

var csvContent = '; a; 12\n@; ; 13',
    textEncoder = new TextEncoder('windows-1252');


var csvContentEncoded = textEncoder.encode([csvContent]);
var blob = new Blob([csvContentEncoded], {type: 'text/csv;charset=windows-1252;'});
saveAs(blob, 'some-data.csv');

Amazing, thanks! Went through reams of SO pages and docs looking for something to solve an issue with an excel destroying CSVs after opening and saving them back out on OSX. This was the only thing that worked.

Javascript to csv export encoding issue - Stack Overflow

javascript csv export-to-csv