Save PDF from window.print in Javascript - javascript

Good day,
I'm able to print a page using javascript. Using this codes:
var win = window.open('', 'print', 'height=720,width=300');
...
win.document.write(document.getElementById("myDivToPrint").innerHTML);
win.document.close();
win.focus();
win.print();
But my problem is, is there a way to save this on my server api?
I tried this,
var myPdf = win.output(); // Doesn't work, not found
I want to get at least the encoding of the pdf to be able to save it on my server. Is it possible? if yes, please help me how.

You can't use print if you want to save the PDF as print uses the browser print function.
if you use jQuery check this previous post Generate pdf from HTML in div using Javascript
You'll need to convert the HTML in PDF and then send a request to your server to save the file

Related

Print pdf file using c#, code behind and send value to javascript to generate print popup

I am working on a c# asp.net project in which, I have to print a PDF file from a directory where there are dozens of files.
I can pick the file from directory but I am not able to print that file by generating a pop up.
Does any one knows how to pass that file from back end code to java script so that It can show popup and ask for print?
P.S:I can not post code here due to PHI issue.
Thanks in advance.
open your PDF to window, get that window form Javascript,
call javascript function,
OpenPrintPopUP(){
var display_setting="toolbar=no,location=no,directories=no,menubar=no, scrollbars=no,width=650, height=850, left=100, top=25"
var prntWindow = window.open("","",display_setting);
prntWindow.document.write(printContent);
prntWindow.document.close();
prntWindow.focus();
prntWindow.print();
prntWindow.close();
}

How can I *locally* save an .html file generated by javascript (running on a *local* .html page)?

So I've been researching this for a couple days and haven't come up with anything conclusive. I'm trying to create a (very) rudimentary liveblogging setup because I don't want to pay for something like CoverItLive. My process is: Local HTML file > Cloud storage (Dropbox/Drive/etc) > iframe on content page. All that works, and with some CSS even looks pretty nice despite the less-than-awesome approach. But here's the thing: the liveblog itself is made up of an HTML table, and I have to manually copy/paste the code for a new row, fill in the timestamp, write the new message, and save the document (which then syncs with the cloud and shows up in the iframe). To simplify the process I've made another HTML file which I intend to run locally and use to add entries to the table automatically. At the moment it's just a bunch of input boxes and some javascript to automate the timestamp and write the table row from the input data.
Code, as it stands now: http://jsfiddle.net/LukeLC/999bH/
What I'm looking to do from here is find a way to somehow export the generated table data to another .html file on my hard drive. So far I've managed to get this code...
if(document.documentElement && document.documentElement.innerHTML){
var a=document.getElementById("tblive").innerHTML;
a=a.replace(/</g,'<');
var w=window.open();
w.document.open();
w.document.write('<pre><tblive>\n'+a+'\n</tblive></pre>');
w.document.close();
}
}
...to open just the generated table code in a new window, and sure, I can save the source from there, but the whole point is to eliminate steps like that from the process.
How can I tell the page to save the generated code to a separate .html file when I click on the 'submit' button? Again, all of this happens locally, not on a server.
I'm not very good with javascript--and maybe a different language will be necessary--but any help is much appreciated.
I suppose you could do something like this:
var myHTMLDoc = "<html><head><title>mydoc</title></head><body>This is a test page</body></html>";
var uri = "data:application/octet-stream;base64,"+btoa(myHTMLDoc);
document.location = uri;
BTW, btoa might not be cross-browser, I think modern browsers all have it, but older versions of IE don't. AFAIK base64 isn't even needed. you might be able to get away with
var uri = "data:application/octet-stream,"+myHTMLDoc;
Drawbacks with this is that you can't set the filename when it gets saved
You cant do this with javascript but you can have a HTML5 link to open save dialogue:
<a href="pageToDownload.html" download>Download</a>
You could add some smarts to automate it on the processed page after the POST.
fiddle : http://jsfiddle.net/ghQ9M/
Simple answer, you can't.
JavaScript is restricted to perform such operations due to security reasons.
The best way to accomplish that, would be, to call a server page that would write
the new file on the server. Then from javascript perform a POST request to the
server page passing the data you want to write to the new file.
If you want the user to save the page to it's file system, this is a different
problem and the best approach to accomplish that, would be to, notify the user/ask him
to save the page, that page could be your new window like you are doing w.open().
Let me do some demonstration for you:
//assuming you know jquery or are willing to use it :)
var html = $("#tblive").html().replace(/</g, '<');
//generating your download button
$.post('generate_page.php', { content: html })
.done(function( data ) {
var filename = data;
//inject some html to allow user to navigate to the new page (example)
$('#tblive').parent().append(
'Check your Dynamic Page!');
// you data here, is the response from the server so you can return
// your new dynamic page file name here.
// and maybe to some window.location="new page";
});
On the server side, something like this:
<?php
if($_REQUEST["content"]){
$pagename = uniqid("page_", true) . '.html';
file_put_contents($pagename, $_REQUEST["content"]);
echo $pagename;
}
?>
Some notes, I haven't tested the example, but it works in theory.
I assume that with this the effort to implement it should be minimal, assuming this solves your problem.
A server based solution:
You'll need to set up a server (or your PC) to serve your HTML page with headers that tell your browser to download the page instead of processing the HTML markup. If you want to do this on your local machine, you can use software such as WAMP (or MAMP for Mac or LAMP for Linux) that is basically a web server in a .exe. It's a lot of hassle but it'll work.

How can I print a PDF fetched via an ajax request?

I'm having a form that once submitted, the PHP generates a PDF file and sends it to the client. Everything works fine so far. What I'm having trouble with is that I need to trigger window.print() on the window containing the received pdf. Is there a way to make the printing wizard appear for the received pdf file?
Here is the code I have
//The #options is a form that once submitted is sends the requested PDF to the browser
$('#options').on('submit', function(e){
if($(this).find('[name="action"]').val() == 'print')
{
var url = $(this).attr('action') || document.URL;
e.preventDefault();
$.post(url, $(this).serializeArray(),function(pdf){
// Open the printing wizard for the requested document
});
}
else
{
// The PDF is displayed normally
return true;
}
});
I'm not even sure if what I want to do is possible. Is is possible for example to open the PDF in a new tab and call window.print() there?
One easy approach for this is to put the PDF file in a new iFrame.
Then you can print the complete content inside the iframe using window.print(); function.
<html>
<head>
<title>Print Test Page</title>
<script>
function printPDF() {
window.frames["print_frame"].window.focus();
window.frames["print_frame"].window.print();
}
</script>
</head>
<body>
Some content here
<iframe name=print_frame width=0 height=0 frameborder=0 src=about:blank>
Your PDF is loaded here
</iframe>
Some more content here
</body>
</html>
Now call window.print(); function when you want to print your pdf.
To open PDF in new window, you need to essentially generate an GET request (so that window can be open via URL) - one of the simple way is to code your server side code to accept the input parameters via query string. Better way is to use POST request (as you are currently doing) to generate the PDF at the server side and cache it in temp location, then return some token/ticket (e.g. it can be as simple as temp file name) to the browser. This token would be used in GET request to get the PDF file - GET request would go to server that would simply read the file off temp location and return it back as inline ((i.e. header content-disposition: inline;). Then you may try window.print() to print it. Similar ways can be used with iframe (with contentWindow.print()).
However, you may find that these solutions may not work - for example, there is no PDF plugin to display the PDF inline (or user has chosen always open file externally). Or it may not work across browser. So yet another (and IMO better) way is to embed java-script within PDF it self to instruct for print as soon as the file is opened.
For example, see this PHP code example that would embed java-script in PDF generation for auto printing - the example is using FPDF for PDF generation.

how to generate a PDF in your HTML code (javascript: jspdf, downloadify??)

I looked around and came up on http://code.google.com/p/jspdf
This is exactly what I need for a web app I am creating in jquery mobile, where users will be filling out a form from an iPad or whatnot (mobile), and be able to save as a PDF and I am able to pass in some variable that is a format of all the form fields, to make it look pretty and presentable as a document PDF that can be signed.
Now I was having problems with my phone testing jspdf, and apparently there is a workaround they provide and some people use saying to use jsPdf with downloadify. heres a link.
https://github.com/MrRio/jsPDF/wiki/Jspdf-using-downloadify
however when I use that link, it seems like I can only save it as a .txt ... am I missing something? How can i save it as a PDF? Just changing filename.txt to filename.pdf doesnt work because it says 'file type is not supported.' how is this using jspdf at all, it seems like it is only using downloadify and sending whatever contents to a TXT, not a pdf... anyone idea on how to successfully create a PDF using this method (with downloadify) because it seems using downloadify I can actually download the file to my mobile device. Without the downloadify method, no download is done.
You can embed the document in the HTML. Use js library at http://jspdf.com and the following code to embed a PDF on mobile devices, where #preview-pane is an iframe in your html.
var doc = new jsPDF();
doc.text(20, 20, 'Example PDF');
var string = doc.output('datauristring');
$('#preview-pane').attr('src', string);
I ended up not being able to do a clientside version, since I couldnt save the PDFs on the ipad. I ended up doing a serverside with PHP / FPDF.

How to save $(document).html() to a .xml file in jQuery or JavaScript?

I'm trying to push a form button and save all the html in the document to a xml file. Also If I have 3 frames or iFrames, I want to also save everything from my 2nd iframe id 'iframe2' (except the iframe itself) into a file, but have a dialog box pop up that says are you sure you want to save this file?
I'm not sure if this is possible, but if it is it would save me a step of writing xml to a file as well as displaying it in the browser. If its not possible in html4.01 is it possible in html5?
I can look at the html using $('#iframe2').html(); but not sure how to save it.
Thanks
There are 3 ways to do this as far as I know:
You could use Flash or Java or another browser plugin to make a save file dialog (check out Downloadify)
You could use data URIs (check out this answer. You'll want to change the mime type to application/xml)
You could use the server to trigger an attachement download with the contents you want. That content could be transmitted through AJAX (check out this question).
You can probably use a backend language like PHP to accept the string as POST data and write it to an XML file in one swoop.
if (window.confirm('Are you sure you want to save this file?')) {
$.post('/save.php', { 'html': $('#iframe2').html() }, function (_dta) {
window.alert(_dta);
});
}
and on PHP
<?php
$html = $_POST['html'];
file_put_contents('./iframe2.xml', $html);
echo 'saved!';
?>

Categories