Calling x.php file from a Javascript file - javascript

I am working on a quite big eWeb tool which includes lots of .js & .php files and this tool is developed by someone else that I can not reach.
Assume that a customer buys some stuff and at the end, as a seller, I am supposed to confirm the customer's shopping by clicking the 'confirm order' button in some table. Now, I want to print a PDF file (which is either located in my local disk or on the server of the eWeb tool depends on the difficulty) when I click the confirm button. I can reach the printer and print the PDF file by following PHP code in my localhost when I directly call it:
<?php
$printer ="HP Officejet Pro X476dw MFP PCL 6 (Network)";
$path = "C:/Test_PDF/TestPDF.pdf";
$fileName = "TestPDF.pdf";`
if($ph = printer_open($printer)) {
$filecontents = file_get_contents($path);
printer_set_option($ph, PRINTER_MODE, "RAW");
printer_write($ph, $filecontents);
printer_close($ph);
}
?>
Now, what I want is to print the PDF file also from the web tool when I click the 'confirm order' button! I do not want to load the PDF file in a hidden iframe or embed it somewhere because, as I said before, the tool is quite big and I do not want to cause any problem somewhere else for now.
Can anybody give me some ideas about the solutions please?

Assuming that PHP is a server-side language, as some people said before, you can't send a print request to a client. The request is originated in the server, so...
What you can do:
1.- Load the pdf in the webpage.
2.- Handle the body onLoad as follows:
<body onload="window.print();">
That way the client will use it's printer if any.
I know that you don't want to load the pdf in a webpage but... This seems like the only solution.
P.D.: I'm not sure if you want to print the receipt for the customer or the seller. Explain yourself better and I will try to help you :)

Related

How to make a link to download a server file on the browser?

I am trying to create a simple download link
The file I want to download is a .pdf that the user can upload, and now I want to make it possible to download. With the pop-up box, you know, or just on the chrome download bar
I've tried what every answer says:
Download PDF
But that leads to "Failed - no file", even though when I check
if(file_exists($GUIDELINES_PDF_DIR . $projectId . '.pdf'))
it returns true!
Some other notes:
I'm pretty shaky on server things, so maybe the same link doesn't work on PHP and on HTML? In that case, how can I find the file?
This link is within a <form>, so I don't really want to create another <form> inside it, or do anything that compromises the info that the user has inputed
Thank so much :)
$GUIDELINES_PDF_DIR is a directory on your server's hard disk.
The resulting path you are creating is relative to the root of your server's hard disk and not to the DocumentRoot of your web server.
You need to account for that difference when generating your URL.
Use a right headers:
header("Content-type:application/pdf");
header("Content-Disposition:attachment;filename='downloaded.pdf'");

Restrict number of pages on a PDF shown in browser

I'd like to be able to output a pdf in browser (which is all fine and dandy) but limit the number of pages shown. Ie. the reader can see the content of what's he's trying to buy is accurate but at the same time I`m not handing the file for free. I can batch edit the files to create new 3-5 paged pdf's for my purpose, but that's a hassle and I'd also have to upload the 'landing page' pdf's to the server, keeping in mind the category of the product and whatnot.
A simplified version of what I'm asking,
user -> download link -> pdf opens with the first 5 pages -> adds a 'buy now' on the 6th pdf page;
I am happy to do this through a third-party script. The only thing required would be for the user to not be able to access the entire pdf doc (like if the trigger-link would be <a href="link.tld/name" id="trigger"> the user shouldn`t be able to fetch the url of the full-doc.
You can actually do it by adding another copy of the pdf file on your webserver and using tcpdf php class, you can actually restrict pages, by deleting remaining pages.
require_once('tcpdf_include.php');
$pdf->deletePage(6,100);//Deletes pages from 6-100
You can have a good read about the complete tcpdf here
This is my choice for any pdf handlers on my site.
The only possible way I think is to create another copy of PDF and it will have only first five pages only...and then from 6th page the message will be there to Buy this Book ans How to Buy and what is amount etc.....
So , just create another preview like version
Thanks again to #user2768665 for the best answer to my troubles. This is my gameplan:
Since I have the files named as in the link, I first grab the WP link of the product using GET, then store that in a variable, preg_replace it to erase the rest of the link (with regex), store that result in a new var, let's say $link2p .
Then I add the call to the product (Download) to open up the processing php script, use tcpdf (user2768665's answer) to delete anything that goes after page 5, add the page with the company's logo as being page 6, and at the end of it add the
Click <a href="http://domain.ltd/saleProcessPage/<?php echo $link2p;?>"here</a> to download <?php echo $link2p;?> FULL PDF
Or, in my case (since I have the a 3rd party paying platform -and you might have the same-), we first run a database check on the product(based on its name) to retrieve the link to our product in our paying platform and then we do the same as above.
Then, we modify the the original's pdf name and output it differently;
$pdf->Output($link2p.'.pdf', 'Insert w/e random string generator.pdf');
It's a great solution as it keeps original pdf files out of any "Inspect Element" user, it runs in the backend and hey, random name si given out.
// Other things I`m thinking about:
Since I haven't read the full documentation for tcpdf, can't be sure on this but I haven't seen any page count ability (which is needed in order to do this fully automatically for the files: i.e. $pdf->deletePage(6,100); becomes $pdf->deletePage(6,endofpdf); For that purpose, I add what I've read before placing the question : Count the number of pages in a PDF in only PHP . So we store that into a $count variable (to see how many files the pdf has) so that we can use $pdf->deletePage(6,$count); Again, haven't read the tcpdf full documentation, so this may be useless.
I'm going to do a full code workup on this after I get some sleep and post the example in its final form. Hopefully this will help others stuck in the same place.
A great thank you again to #user2768665 and #Monts_mind_hacker for the interest in the topic. Awesome guys.
You can use FPDI to create a preview of the first 5 pages:
$pdf = new FPDI();
$pageCount = $pdf->setSoruceFile('your.pdf');
$pageCount = min($pageCount, 5);
for ($pageNo = 1; $pageNo <= $pageCount; $pageNo++) {
$tplIdx = $pdf->importPage($pageNo);
$s = $this->getTemplatesize($tplIdx);
$this->AddPage($s['w'] > $s['h'] ? 'L' : 'P', array($s['w'], $s['h']));
$this->useTemplate($tplIdx);
}
$pdf->AddPage();
// add the link to the shopping cart on the last page...
$pdf->Output('5-pages.pdf', 'D');

File download html with error handling FileNotFound

I want to download a file when I click on a link. The file is served dynamically.
Download!
But I need to be able to display error to the user if /server/myfunc?id=XXX link does not provide a file. I can return a boolean false or any http code through this link if file isn't present.
What should be the most appropriate method for this implementation. Note that I do not wish to alter the current state of page in any manner, just trigger the file download without affecting the page. And display error if file is not to be downloaded.
You can't do that only with html as far as it is a static language. I would suggest you to use a 'if/else' clause written in php or java. Here you have some documentation, and a concrete sample here. Anyway here you are a sample that could fit exactly on your case (taking into account you are inserting the php on the html).
<?php
var = url
if (isset($var) && ($var === true){ ?>
Download!
<?php } else { ?>
<p>Hey, there is no URL!</p>
<?php } ?>
I know I am replying very late, But it maybe useful for someone facing this kind of issue.
When using Synchronous HTTP calls, Its very difficult to show error Message as it would replace whole web page instead which we dont want.
So, Its better to use AJAX
Click here JohnCulviner Blog for more details - how to use AJAX for downloads
Also, Go through following SO link Download a file by query Ajax

Print a local file with javascript

Today I have a hard challenge with php+javascript+html+css:
I'm creating an application to "authorization+print it": the app must run in a local apache(under windows preferably), and need a conection to a DB in the cloud. That's easy. With the user authenticated, a list of authorized files must be shown, another easy task too. It's working. But now comes the crazy: I want to print them without let the user select and see any print option, only a button "Print". The print configuration comes in a .txt file and I need to configure the printing, sending the file and the configuration to the printer.
I searched a lot, but I only see the "print this page" buttons or shell solutions (gsview and gsprint for windows, but I cannot use that because I cannot configure the print options). I need anything more complex. Could you help me? (Im trying now fpdf, but...omg, I cannot understand If this could be used to do that I want.
Non-free/installed solutions could be in help too.
In addition, I need to print multiple files, but that's optional (I can do anything like "while")
PD: sorry for my english level.
Print from client-side = form the browser via javascript
It's not possible to do this from client-side (= from inside the Browser).
There are hackish solutions out there, which might work for IE, like the one here: HTML / Javascript One Click Print (no dialogs), but in general "if you try to print, the dialog will pop up" = default behaviour of "window.print()".
Print from server-side
Basically you use the server-side (PHP) to print the document, instead of the client.
So you might use an Ajax request (user clicks on the print button) handing the filename or the content to print over to the "print.php" file on the server, which does the job of pushing the content to the printer.
Of course, you'd have to know which printer the user wants the content to be printed at...
There are several ways to print from PHP.
One option would be to use the php_printer extension:
$handle = printer_open();
printer_set_option($handle, PRINTER_MODE, "raw");
printer_write($handle,$myfile);
printer_close($handle);
Or just copyor print to the printer:
exec('copy C:\file.txt com1');
exec('copy C:\file.txt lpt1');
exec('print /d:LPT1: C:\file.txt');
If you have network printer, you could try to send your content to the network address.
There are some PHP utils around to work with LPR: https://github.com/Craswer/PhpNetworkLprPrinter
Referencing: https://stackoverflow.com/a/5695181/1163786
Question from comment: How can i set printer options from PHP on Windows?
This very easy on Linux because lpr accepts options lpr <options> - but that's not the case on Windows. So, here are some Windows specific tricks to configure the printer:
Windows7 has PRINTUI.EXE - a shorthand for RUNDLL32 PRINTUI.DLL,PrintUIEntry
Please see PrintUI Reference for examples.
You can configure your printer manually, for instance activate duplex mode,
then save the settings file and re-use it, when printing from PHP.
This allows to work with multiple printer configuration files.
The easiest way is to configure the printer in your env and then access it by name,
"Printer-HP-XY-DuplexOn-2PagesOn1". In other words: it's configured outside and not from within PHP, only accessed from there.

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.

Categories