简体   繁体   中英

Converting Web-service response to PDF file - PHP, Javascript

This is the service to download a document from the server:

$app->get('/docDownload', function () use ($app){

        $path = "/xxx/xxx/works.pdf";
        $res = $app->response();
        $res['Content-Description'] = 'File Transfer';
        $res['Content-Type'] = 'application/pdf';
        $res['Content-Disposition'] ='attachment; filename=' . basename($path);
        $res['Content-Transfer-Encoding'] = 'binary';
        $res['Expires'] = '0';
        $res['Cache-Control'] = 'must-revalidate';
        $res['Pragma'] = 'public';
        $res['Content-Length'] = filesize($path);
        readfile($path);
    });

And here is the answer

%PDF-1.5
%����
1 0 obj
<</Type/Catalog/Pages 2 0 R/Lang(en-GB) /StructTreeRoot 14 0 R/MarkInfo<</Marked true>>>>
endobj
2 0 obj
<</Type/Pages/Count 1/Kids[ 3 0 R] >>
endobj
3 0 obj
<</Type/Page/Parent 2 0 R/Resources<</Font<</F1 5 0 R/F2 8 0 R>>/ExtGState<</GS7 7 0 R>>/ProcSet[/PDF
/Text/ImageB/ImageC/ImageI] >>/MediaBox[ 0 0 595.32 841.92] /Contents 4 0 R/Group<</Type/Group/S/Transparency
/CS/DeviceRGB>>/Tabs/S/StructParents 0>>
endobj
4 0 obj
<</Filter/FlateDecode/Length 224>>
stream
x���Kk�0����9J�����`|�� �@����J�C
M!��$��bA,�ш]T�h�j��V0]���r���0��8R0L.F����70�3�}�8\�08L�V�Q��+�')��g��U;��V
��8�o�����o��Ip�I}�W_�r}��N'mգU��g>Ö�Ӎ���n>�D��.�-����<H`��ABC\ǐ'�=��ٻXwc�z��wx�
endstream
endobj
5 0 obj
<</Type/Font/Subtype/TrueType/Name/F1/BaseFont/ABCDEE+Calibri/Encoding/WinAnsiEncoding/FontDescriptor
 6 0 R/FirstChar 32/LastChar 119/Widths 24 0 R>>
endobj
6 0 obj
<</Type/FontDescriptor/FontName/ABCDEE+Calibri/Flags 32/ItalicAngle 0/Ascent 750/Descent -250/CapHeight
 750/AvgWidth 521/MaxWidth 1743/FontWeight 400/XHeight 250/StemV 52/FontBBox[ -503 -250 1240 750] /FontFile2
 22 0 R>>
endobj
...... continues ........

I would like when the WS is called, automatically return a PDF document, opening in the user screen or with the options to Save or Open.

I got a way to do this in javascript:

var request = new XMLHttpRequest();
    request.open("GET", "/documents/docDownload", true); 
    request.responseType = "blob";
    request.onload = function (e) {
        if (this.status === 200) {
            // `blob` response
            //console.log(this.response);
            // create `objectURL` of `this.response` : `.pdf` as `Blob`
            var file = window.URL.createObjectURL(this.response);
            var a = document.createElement("a");
            a.href = file;
            a.download = this.response.name || "detailPDF";
            document.body.appendChild(a);
            a.click();
            // remove `a` following `Save As` dialog, 
            // `window` regains `focus`
            window.onfocus = function () {                     
              document.body.removeChild(a)
            }
        };
    };
    request.send();

Is there another way to do this in JQuery?

What kind is the WS response?

To me you can do it something like this with jQuery.ajax() :

$.ajax({
  url: "/documents/docDownload",
  type: "GET",
  headers: {
    responseType: "blob"
  },
  success: function(data) {
    var file = window.URL.createObjectURL(data);
    var a = $("<a/>", {
      "href": file,
      "download": data.name || "detailPDF"
    }).appendTo('body');
    a.click();
    $(window).on('focus', function(e) {
      $('a').remove();
    });
  }
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM