How to download pdf in javascript using soap webservices? - javascript

I have a list of bills in my table and each row has it's own unique bill (different date, amount etc...). I have successfully managed to make php call via Soap:Wrapper in Laravel 5 and when i type in browser "path to that procedure" i get my pdf. But i would like to open it using Javascript.
My code of server side
$pdfData= $soap->racun($data);
header("Content-type: application/pdf");
header("Content-Length:" . strlen($pdfData));
//this line if i want to preview my pdf in browser
header("Content-Disposition: inline; filename=pdf.pdf");
//this line if i want to download my pdf
header('Content-Disposition: attachment; filename="pdf.pdf"');
print $pdfData;
My code of client side is
$.ajax({
type:"GET",
url:"/path",
data:"param1=" + par1+"&param2="+ par2+ "&param3="+par3,
success:function(msg){
//alert(msg);
//here needs to show that pdf but don't know how
document.write(msg);
},
fail:function(){
alert('Error with pdf');
}
});
So when a user click on a link to get his bill i send AJAX call and get that pdf using SOAP WebService. The problem is that i can preview it or download it if i write /path in my browser, but don't know how to do it inside Javascript. What am i doing wrong?

Well, you're sending a GET request, so you can simply do this:
window.location = "/path?" + "param1=" + par1+ "&param2=" + par2 + "&param3=" + par3;
You might also want to check this answer.

Related

pdf (mpdf) file gets corrupted in javascript

I have a web app, where pdfs need to be generated dynamically. Data is gathered in javascript and send with a post request to the server. Here mpdf is used to generate a pdf. If I save the file locally: php $mpdf->Output($filename, \Mpdf\Output\Destination::FILE); it works.
But if I send it to the browser php $mpdf->Output($filename, \Mpdf\Output\Destination::DOWNLOAD); and take the output in the jquery callback to do the following (borrowed from https://nehalist.io/downloading-files-from-post-requests/):
jQuery.post(my_axax_url, data, function(data) {
var blob = new Blob([data], { type: 'application/pdf' });
var l = document.createElement('a');
l.href = window.URL.createObjectURL(blob);
l.download = 'test.pdf';
document.body.appendChild(l);
l.click();
});
The downloaded pdf is empty (blank page), and has corrupted author information (that makes it look, like an encoding problem). I ran https://www.datalogics.com/products/pdftools/pdf-checker/, which only gave me it the javascript generated pdf is a "Damaged document".
I hope, that this is an easy problem. I am used to php and text documents, not pdf.
Thanks!
Try adding the following to the start of your php script, it may be some sort of encoding issue:
ob_clean();
header('Content-type: application/pdf');
header('Content-Disposition: inline; filename="test.pdf"');
header('Content-Transfer-Encoding: binary');
header('Accept-Ranges: bytes');

Issue saving file with PHP script

I'm making a PHP script for a JavaScipt site I've made.
The goal is to save the contents of a string as an HTML file when I click a button.
I'm using jQuery to make a Post request.
I'm using an Ubuntu OS with an Apache 2 server. The folder I'm writing to has permissions 777 (for testing only, will repeal this).
A requirement is the PHP must live in another file.
The issue is whenever I make the request, the file saves blank.
A requirement is each filename must be a timestamp. The file has the correct file name, but not contents.
So far, here is my code:
<?php
$fileName = $_GET['fileNameData'];
$htmlImport = $_GET['htmlToSaveData'];
$htmlToSave = (string)$htmlImport;
$myFile = fopen($fileName, "w") or die('You do not have write permissions');
//fwrite($myFile, $htmlToSave);
file_put_contents($myFile, $htmlToSave);
fclose($myFile);
?>
I've tried the frwite function that I've commented out, same effect.
I have tested this in terminal by passing in arguments ($argv[1] and $argv[2]). That works fine.
The JS I've made to run my site looks like:
var newURL = 'saveHTML.php/?fileNameData=' + fileName + '&htmlToSaveData=' + htmlToSave
$.post(newURL)
.done(function(){
alert('Your file saved as ...' + htmlToSave)
})
I've also tried this code, with the same result:
$.post('saveHTML.php/', {
fileNameData : fileName,
htmlToSaveData : htmlToSave
})
Both the fileName and htmlToSave are strings, although htmlToSave is rather long and is actually html text that I've converted to a string.
Does anyone have ideas about what's going on here? I'm not a PHP developer at all.
I'm using a callback so I can be sure I've collected all my html before I pass the string to PHP.
I've read and tested the recommendations on this question here and this has been fruitless.
EDIT Don't be alarmed about the code, I realise it's a security issue but this is a learning project and this will not be in production.
I can see right off the bat that you have
$myFile = fopen($fileName, "w") or die('You do not have write permissions');
//fwrite($myFile, $htmlToSave);
file_put_contents($myFile, $htmlToSave);
fclose($myFile);
file_put_contents takes a file name, not a handle. So you would only need
file_put_contents($fileName, $htmlToSave);
Edit: I also feel like I should point out that you should not allow your users to name your files. They could potentially do some nasty stuff to your machine.

download file in a specific folder

i have a link that allows me to downlowd a text file in my web page but the problem is that i want the user to be able to chose where to save the file i mean when he clicks the link a window should be opened so he can save the file wherever he likes can any one tell me how to do that? thx .
here is a part of my code:
$fichierres=fopen('res.txt','a');
ftruncate($fichierres,0);
...
fputs($fichierres, $t."\r\n");
...
fclose($fichierres);
echo' <div style="text-align:center"><br> <button id="download" width="100px" class="styled-button-8"><b>Download</b></button></div><br>';
Most browsers will auto-open any file that they can read - exactly how they should work. This includes .txt files, there's nothing that you can do to prevent this.
What you can do is provide the link as an anchor (Download) and provide a message next to the link telling the user to "Right click / Save link as..." to download - this will allow them to save the file rather than download.
The exact option in the right click menu will differ between browsers but it's always something along the lines of "Save Link As...".
http://www.w3.org/Protocols/rfc2616/rfc2616-sec19.html
19.5.1 Content-Disposition
The Content-Disposition response-header field has been proposed as a
means for the origin server to suggest a default filename if the user
requests that the content is saved to a file. This usage is derived
from the definition of Content-Disposition in RFC 1806 [35].
content-disposition = "Content-Disposition" ":"
disposition-type *( ";" disposition-parm )
disposition-type = "attachment" | disp-extension-token
disposition-parm = filename-parm | disp-extension-parm
filename-parm = "filename" "=" quoted-string
disp-extension-token = token
disp-extension-parm = token "=" ( token | quoted-string )
An example is
Content-Disposition: attachment; filename="fname.ext"
In PHP, you would use header function to send this header. Note that this must be called before any data is sent.
header('Content-Disposition: attachment; filename="fname.ext"');

downloading image in code format

i m trying to make a button that downloads the image and what i did is, made a function like this:
function download_image(){
$file = $_POST['file'];
header('Content-Description: File Transfer');
header("Content-type: application/octet-stream");//notice this content-type, it will force a download since browsers think that's what they should do with .exe files
header("Content-disposition: attachment; filename= ".$file."");
readfile($file);
}
and when download button is clicked i performed this js:
$.ajax({
type:"POST",
url:'..address to../download_image',
data:{
file:imgElem
},
success:function(){
alert('image downloaded');
}
});
Now the problem is i don't have image name but is coded image like this:
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAABBgAAAEtCAYAAACibtPQAAAgAElEQVR4nO3dX28c150mYH+c+S57s5d7uVcFGMEGuQiwgW+ycCEAsdl4gQjGJqsyYIyCYEbwEDXKZD1KNLHVtjMZDeM/kmmWLJmOrSiOzViOJDJiHNtnLoLqLRarm8VDFfsU63mBBzabzWZ12/rp1MtTzSdCCKEoipBlWciyLFRVFbpSVdX8PlmWhTzPO+8nIiIiIiIiItPLE7PZLJRlGUIIoSzLUBRF5x3rgkFEREREREREpJ0nmh8oGEREREREREQkJvOCIc/z+U6GrrQvkVh2XxERERERERGZVo61g6H+nN0MIiIiIiIiItLME+0b+hYHy94QUkRERERERESmlSfKsgyz2SyEEMJsNjvw2yHyPO/c0WAHg4iIiIiIiIg080QIi39NZbNgaL8HQ11KiIiIiIiIiIgcukRCREREREREROS4UTCIiIiI...PHWSgveiOXekFY/8Rr2ZBZ9hO1+vu2t8Mt+7r2Frr2X0JH3Z7n+aECob3Ntvn1zeNoP+/2cXY9FwWDSNqZwtzsWqDX861rV8NRBUP99V3zc9G8zfN8/vXtOdr1NUct1tvPXUTis2iXQAiH3xCwvTOrOQOan2+v15pf03WSuuj71DOjXYC014Lt+3Z97xC6d2097ufSTvuyjeZusaMe9yQFQ/Pxu55L83gf5/OVdKNgkDORRdvRRESkO6c1N+tLMeos2sorIiIi44+CQUadrsZZREQW57TnZv0TKDsCREREzn4UDCIiIiIiIiJy4igYREREREREROTEUTCIiIiIiIiIyImjYBARERERERGRE0fBICIiIiIiIiInjoJBRERERERERE4cBYOIiIiIiIiInDgKBhERERERERE5cRQMIiIiIiIiInLiKBhERERERERE5MRRMIiIiIiIiIjIiaNgEBEREREREZET5z8AyGKspBK3ENIAAAAASUVORK5CYII=">
so the problem is how should i download the image??? Please help:(
Just set the window.location to the encoded URI, eg
window.location.href = 'data:image/png;base64,iVBORw0KGgo...
or you can also open a popup window
http://jsfiddle.net/vaibviad/VE8Qn
If you want to have file name and extension then you can also try this
<a download="FILENAME.EXT" href="data:image/png;base64,asdasd...">Download</a>
Below link is demo with download attribute with filename and ext
http://jsfiddle.net/vaibviad/VE8Qn/3/
NOTE: Download attribute is not widely supported
JavaScript cannot save a file, so in this situation you need to return a url from your API then in your success function you'll use the window.location = ....returned value... this will download the file.
If a DEMO is needed please let me know.

Can we save canvas image in system also like direct download image when we click save

Hello I have done project in that i can save image like downloading in to div then right click on that it displays save as image,I don't want to do like that. I want download image directly not like the above at the same time i want to save image path in database using SQL server and mvc3 web application.How to save in database I need to use any server side code.
I Google it but couldn't find any relevant answer.
Is it possible what i asked if so can any one guide me.
Thanks in advance.
below code is for saving image and i need to change it.
function downloadCanvas() {
var canvas = stage.children[0].canvas;
var oImgPNG = Canvas2Image.saveAsPNG(canvas, true);
document.body.appendChild(oImgPNG);
}
When I search in Google every one is using php code.
how to use php code in html5.
Via Ajax send data to server and then save as image,
var canvasData = canvas.toDataURL("image/png");
var ajax = new XMLHttpRequest();
ajax.open("POST",'save.php',false);
ajax.setRequestHeader('Content-Type', 'application/upload');
ajax.send(canvasData);
PHP,
<?php
if (isset($GLOBALS["HTTP_RAW_POST_DATA"]))
{
// Get the data
$imageData=$GLOBALS['HTTP_RAW_POST_DATA'];
$filteredData=substr($imageData, strpos($imageData, ",")+1);
$unencodedData=base64_decode($filteredData);
$random_digit=md5(uniqid(mt_rand(), true));
$fp = fopen( 'yourfolder/new'.$random_digit.'.png', 'wb' );
fwrite( $fp, $unencodedData);
fclose( $fp );
//Now save the path in database!
}
?>
The image will be saved at "yourfolder/new'.$random_digit.'.png'".
Link to same question,
Sending photo from javascript to server
You have to send the image data to the server with an ajax call to the web server, like the following :
http://www.dotnetfunda.com/articles/article1662-saving-html-5-canvas-as-image-on-the-server-using-aspnet.aspx
Then, depending on the image size, store the URL of the image into SQL Server (if small image) OR store the data. Read this to help you make your choice : Save image url or save image file in sql database?

Categories