Search code examples
javascriptphppdfdownloadphp-curl

How to save PDF file in JS (from ajax)


I use PHP to get it, because I need to download a PDF file from another server. To download this file I need to be logged in and the client shouldn't have to log in there.

The problem is that the PDF file the user gets is just a white page. On my server there is still content inside when i write it in a file (file_put_contents("test.pdf",$content);)

I tried to base64 encode it before I send it and recognized that the delivered data is still correct. So it fails at the decoding (atob(data)) or in the download function. (I also tried utf8 encodings)

In the downloaded pdf file, many characters are exchanged with these boxes or question marks(��).

$result = curl_exec($ch);
file_put_contents("test.pdf",$result); //test.pdf contains correct document
echo base64_encode($result);
download(atob(data),"My.pdf") //data is answer of ajax request

function download(data, filename, type) {
    var file = new Blob([data], {
        type: type
    });
    if (window.navigator.msSaveOrOpenBlob) // IE10+
        window.navigator.msSaveOrOpenBlob(file, filename);
    else { // Others
        var a = document.createElement("a"),
            url = URL.createObjectURL(file);
        a.href = url;
        a.download = filename;
        document.body.appendChild(a);
        a.click();
        setTimeout(function () {
            document.body.removeChild(a);
            window.URL.revokeObjectURL(url);
        }, 0);
    }
}

Solution

  • The problem is the implicit UTF8 encoding in the BLOB constructor. More information here.