1

I want to save some html to pdf file on a button click. The problem is that I get the issue after the ajax call:

%PDF-1.7 %���� 8 0 obj << /Type /Page /Parent 1 0 R /LastModified (D:20190328213806+02'00') /Resources 2 0 R /MediaBox [0.000000 0.000000 595.276000 841.890000] /CropBox [0.000000 0.000000 595.276000 841.890000] /BleedBox [0.000000 0.000000 595.276000 841.890000] /TrimBox [0.000000 0.000000 595.276000 841.890000] /ArtBox [0.000000 0.000000 595.276000 841.890000] /Contents 9 0 R /Rotate 0 /Group << /Type /Group /S /Transparency /CS /DeviceRGB >> /Annots [ 6 0 R 7 0 R ] /PZ 1 >> endobj 9 0 obj <> stream x��ۏ�q��� |�`ɐVU}���e).e�rI66�$^$�d3� �������]EYb�"I��g?ΙKwU���|�gy�s|r��o�߿������G���vqy|�]��H�������ȄQ��F�D�S��F���@�.��'�}���e�8 �B�@����UH��@M�MC�g���P8���g[t���?P�#E���=��@�P��g� KysL�m�.�0qC�{�[�}Tlg�kY�?���������3�K��9��g�%Mq��=���� 0vw��G�}����Obڃ�l�/��WC��|����?��O���y��u;�ݽ����L �_���qŁ�JG�ׇ��~���a?K�^���g��--�,�L3����?-�Z�e��W!1�D���a�I#���s?

I have found the similar issue here - Tcpdf on Laravel 3 controller

But I don't know what the Response::make is? Any ideas how to fix it? Thanks.

Code:

jQuery/Ajax

$(document).on("click", "#testButtonClick", function() {
   savePDF($("#test").html(), "Test1", "Test2");
 });

function savePDF(info, name, data) {
$.ajax({
    type: "post",
    url: "includes/worker",
    data: {"test": info, "name": name, "data": data},
    xhr: function() {
        try {
            if (window.ActiveXObject) {
                return new window.ActiveXObject("Microsoft.XMLHTTP");
            }
        } catch(e) { }

        return new window.XMLHttpRequest();
    },
    success: function(result) {
        console.log(result);
    },
    error: function(response) {
    }
}); 
}

PHP

    require_once("tcpdf.php");
    $pdfData = new TCPDF('P', PDF_UNIT, PDF_PAGE_FORMAT, true, "UTF-8", false);  //
    $pdfData->SetCreator("Test..");  
    $pdfData->SetTitle("Test..");  
    $pdfData->SetHeaderData("", "", PDF_HEADER_TITLE, PDF_HEADER_STRING);  
    $pdfData->setHeaderFont(Array(PDF_FONT_NAME_MAIN, "", PDF_FONT_SIZE_MAIN));  
    $pdfData->setFooterFont(Array(PDF_FONT_NAME_DATA, "", PDF_FONT_SIZE_DATA));  
    $pdfData->SetFooterMargin(PDF_MARGIN_FOOTER);  
    $pdfData->SetMargins(PDF_MARGIN_LEFT, "5", PDF_MARGIN_RIGHT);  
    $pdfData->setPrintHeader(false);  
    $pdfData->setPrintFooter(false);  
    $pdfData->SetAutoPageBreak(true, 10);  
    $pdfData->setFontSubsetting(true);
    $pdfData->AddPage();
    $pdfData->SetFont("freeserif", "", 10);
    $pdfData->writeHTML(iconv("Windows-1251", "UTF-8", "Это тест...."));  
    $pdfData->Output("Test.pdf", "D");
Cobra91151
  • 610
  • 4
  • 14
  • this IS the PDF... – Honk der Hase Mar 28 '19 at 19:56
  • @LarsStegelitz Yes, I know, but it should display dialog to save it, not output as text/html. Any ideas? Thanks. – Cobra91151 Mar 28 '19 at 19:58
  • If the browser should offer an Save-as dialog, you need to set the appropriate headers (Content-Disposition). If you receive the data through AJAX, I'm not sure if that'll work... – Honk der Hase Mar 28 '19 at 20:01
  • @LarsStegelitz I know, but it doesn't work. I tried to add the `contentType` to ajax, also headers to php. I will add code to my post soon. – Cobra91151 Mar 28 '19 at 20:03
  • and you tried the application/force-download mime header? – Lulceltech Mar 28 '19 at 20:10
  • try also the inline output with option "I" – Honk der Hase Mar 28 '19 at 20:20
  • @TimHinz Yes, I tried: `header("Content-type: application/force-download");` But the issue is still present. – Cobra91151 Mar 28 '19 at 20:22
  • @LarsStegelitz Thanks, I tried it, but the same output. I think the problem is with `Ajax` and I should try to create a form and post it using `jQuery`. – Cobra91151 Mar 28 '19 at 20:24
  • I've checked and found another SO thread. Long story short: you can't do that with AJAX, because JS can't write the file (but it contains als a solution!) https://stackoverflow.com/questions/4545311/download-a-file-by-jquery-ajax – Honk der Hase Mar 28 '19 at 20:33
  • @LarsStegelitz Thanks, but my pdf file is not saved anywhere to use `$.fileDownload` or `FileSaver` for download. I checked, `TCPDF` works without `Ajax`, so I think it should work on auto form using `jQuery/JS`. I will add the target="_blank" so, it will submit on another tab. I will check it and reply later. Thanks. – Cobra91151 Mar 28 '19 at 20:43
  • @LarsStegelitz So, I have found the problem, for some reason it breaks the `html` data, which I send through `JS` as `$("#test").html()`. It only prints 45 chars and them breaks before `"`. It's interesting, I will investigate it a little bit more and reply here later. – Cobra91151 Mar 28 '19 at 22:10
  • Sorry, but that is not recognizeable for me through the code snippet you've posted... be aware that PDF is a mixed text/binary format that needs to be rendered specifially.. just echoing the PDF file contents won't give any useful output. – Honk der Hase Mar 28 '19 at 22:14

1 Answers1

0

So, I have fixed it by using auto form JS and escaping characters such as ".

Code:

    var pdfForm = $("<form action=\"includes/worker\" method=\"post\" enctype=\"multipart/form-data\" target=\"_blank\"></form>");
      pdfForm.append("<input type=\"hidden\" name=\"test\" value=\"" + htmlValidation($("#test").html()) + "\">");
      pdfForm.append("<input type=\"hidden\" name=\"name\" value=\"Test1\">");
      pdfForm.append("<input type=\"hidden\" name=\"data\" value=\"Test2\">");
      $("body").append(pdfForm);
      $(pdfForm).submit();

   function htmlValidation(data) {
     return data
       .replace(/&/g, "&amp;")
       .replace(/</g, "&lt;")
       .replace(/>/g, "&gt;")
       .replace(/"/g, "&quot;")
       .replace(/'/g, "&#039;");
   }
Cobra91151
  • 610
  • 4
  • 14
  • Maybe the problem is that you need to convert the response to blob object in your JavaScript code. – pippo Mar 29 '19 at 12:54
  • @pippo Thanks for the hint, I will try it using `Ajax` method and reply later. – Cobra91151 Mar 29 '19 at 12:57
  • @pippo I have tried it: `var pdfBlob = new Blob([result], {type: "application/pdf;charset=utf-8"}); saveAs(pdfBlob, "test.pdf");` but it saves `pdf` as empty (blank) file. Thanks. – Cobra91151 Mar 29 '19 at 14:19
  • I had to do something similar and I found this post https://nehalist.io/downloading-files-from-post-requests/ very helpful :) – pippo Mar 29 '19 at 21:52
  • @pippo Maybe I will try it later. Thanks for the link. – Cobra91151 Mar 30 '19 at 16:21
  • @pippo I have tried it from `GitHub` - https://github.com/nehalist/download-post-requests but it creates the broken `pdf` file, maybe because I use `TCPDF` for creating `unicode` pdf files. I will stick to my working solution. Thanks. – Cobra91151 Mar 30 '19 at 21:24