I want to allow my users to save my page as a PDF. I have created a print stylesheet and I can generate the PDF by using Javascript's print function. Here's my problem:
In Chrome, the browser generates a preview and shows it to the user. The user can then either save it or print it.
However, in IE and FF, print calls up a complex menu, and while it can generate a PDF by "printing" to PDFCreator, it's a complex process that many users won't understand.
What I want to do is to somehow duplicate the Chrome functionality for non-Chrome users. Options I have considered:
Screenshot the HTML page and render that image into a PDF with Javascript. There are libraries that do this, but I want my PDF to have the print layout.
Generate the PDF on the server and send it to the user's browser. This can be done, but it seems difficult to use the same HTML as the standard page.
My server is running PHP and the Zend framework. I can't use NodeJS or any headless browser to render on the server. Do I have any options?
I've done exactly what you want to do before using a library called dompdf (https://github.com/dompdf/dompdf). Here is how I used it:
I dropped the dompdf library into the "library" folder in my ZF project. Then, in my application when I'm ready to render the page I created a new Zend_View() object and set it up with whatever view script variables it needed. Then I called the render() function and stored the rendered output into a variable I then provided to dompdf. The code looks like this:
$html = new Zend_View();
$html->setScriptPath(APPLICATION_PATH . '/views/scripts/action_name/');
$html->assign($data); //$data contains the view variables I wanted to populate.
$bodyText = $html->render('pdf_template.phtml');
require_once(APPLICATION_PATH."/../library/dompdf/dompdf_config.inc.php");
$dompdf = new DOMPDF();
$dompdf->load_html($bodyText);
// Now you can save the rendered pdf to a file or stream to the browser:
$dompdf->stream("sample.pdf");
// Save to file:
$dompdf->render();
$pdf = $dompdf->output();
file_put_contents($filename, $pdf);
Related
I have a json file like this:
{"user":{"email":"user#test.com"},
"screenshot":{"blobFile":"<!DOCTYPE html><html lang=\"en\">...</html>"}}
and I want to take a screenshot, using XMLHttpRequest sending data a PHP file.
In PHP file getting request like:
$data = json_decode(file_get_contents("php://input"), true);
$htmlStr = json_encode($data["screenshot"]["blobFile"]); // <!DOCTYPE html><html lang=\"en\">...
so far everything is ok but how to convert this string to the image file and save a server?
I've tried html2canvas in PHP file but not fire.
any ideas?
I'd try to use PhantomJS. It's headless browser, which allows to interact with web pages many ways including making screenshots. It will require some time to understand how to work with it, but it definitely will get a result. Although, PhantomJS sometimes is a headache if your page is quite complicated structured, written using some frameworks like ReactJS, AngularJS, etc.
What it does it renders HTML page with styles including scripts serverside. If you save not HTML string but exact URL with COOKIE and SESSION data and then reconstruct conditions which user had in an opened page when you did a screenshot, it'll do a job.
See example here Screen Capture on PhantomJS
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();
}
I have a setup where a web page in a local server (localhost:8080) is changed dynamically by sending sockets that load some scripts (d3 code mainly).
In chrome I can inspect the "rendered html status" of the page, i.e., the resulting html code of the d3/javascript loaded codes. Now, I need to save that "full html snapshot" of the rendered web-page to be able to see it later, in a "static" way.
I have tried many solutions in python, which work well to load a web and save its "on-load" d3/javascript processed content, but DO NOT get info about the code generated "after" the load.
I could also use javascript to make this if no python solution is found.
Remember that I need to retrieve the full html rendered code that has been "dynamically" modified in time, in a chosen moment of time.
Here are a list of questions found in stackoverflow that are related but do not answer this question.
Not answered:
How to save dynamically changed HTML?
Answered but not for dynamically changed html:
Using PyQt4 to return Javascript generated HTML
Not Answered:
How to save dynamically added data to update the page (using jQuery)
Not dynamic:
Python to Save Web Pages
The question could be solved using selenium-python (thanks to #Juca suggestion to use selenium).
Once installed (pip install selenium) this code makes the trick:
from selenium import webdriver
# initiate the browser. It will open the url,
# and we can access all its content, and make actions on it.
browser = webdriver.Firefox()
url = 'http://localhost:8080/test.html'
# the page test.html is changing constantly its content by receiving sockets, etc.
#So we need to save its "status" when we decide for further retrieval)
browser.get(url)
# wait until we want to save the content (this could be a buttonUI action, etc.):
raw_input("Press to print web page")
# save the html rendered content in that moment:
html_source = browser.page_source
# display to check:
print html_source
I have a decodification problem.
I have an offline desktop application, where I have to generate a pdf file and save at his open.
To generate the PDF file I use BytescoutPDF library createpdf.js.
This returns a document variable that I have to save.
I tried with:
//this calls the createPDF to BytescoutPDF library
//and returns the variable into 'doc'
var doc = generaStaticPartBolla_2();
//take the stream
var bolla = Ti.Filesystem.getFileStream(billPath);
//open in write mode
bolla.open(Ti.Filesystem.MODE_WRITE);
//write the doc file decodified in Base 64
bolla.write(doc.getBase64Text());
//close the stream
bolla.close();
Now, the file generated is currupted.
I'm not able to open this. How can I do this? The file must be converted in Base 64 or other?
I don't know if you have solved your issue now, but I had the same requirements : offline app, generating pdf from HTML, and in my case, styling the generated pdf with CSS.
After trying many solutions, the main problem was to style with CSS.
Finally I used WkhtmlToPdf (http://wkhtmltopdf.org/). Basically I embed the binaries (for mac os and for windows) in the app, and regarding the platform, I execute them with the Ti.Process method.
WkhtmlToPdf generates a pdf in the specified path, so in this way, you will be able to open this pdf.
(In order to set the path for the pdf, i use openSaveAsDialog (http://tidesdk.multipart.net/docs/user-dev/generated/#!/api/Ti.UI.UserWindow-method-openFileChooserDialog) which allows the user to set the path and the name of the generated pdf).
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.