Storing generated PDF files on the server

前端 未结 5 2089
别跟我提以往
别跟我提以往 2020-12-05 05:34

Using the jsPDF plugin, I am creating a .pdf file and generating a download based on a button click. I would like to save the file onto my server i

相关标签:
5条回答
  • 2020-12-05 06:21

    If your PDF contains binary data, you can get into problems if you try to transfer the PDF via string. I used the blob output format of jsPDF with success.

    var doc = new jsPDF();
    // ... generate pdf here ...
    
    // output as blob
    var pdf = doc.output('blob');
    
    var data = new FormData();
    data.append('data' , pdf);
    
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function() {
      if (this.readyState == 4) {
        if (this.status !== 200) {
          // handle error
        }
      }
    }
    
    xhr.open('POST', 'upload.php', true);
    xhr.send(data);
    

    Your upload.php can then use the $_FILES array in PHP

    <?php
    if(!empty($_FILES['data'])) {
        // PDF is located at $_FILES['data']['tmp_name']
        // rename(...) it or send via email etc.
        $content = file_get_contents($_FILES['data']['tmp_name']);
    } else {
        throw new Exception("no data");
    }
    ?>
    
    0 讨论(0)
  • 2020-12-05 06:23

    Using Asp.net/C# and jQuery: Based on @mahmoud hemdan answer, i did for my requirement. I did like below:

    Javascript:

    function createPDF(){
      var doc = new jsPDF('landscape');
      var u = $("#myCanvas").toDataURL("image/png", 1.0);
      doc.addImage(u, 'JPEG', 20, 20, 250, 150);
      var base64pdf = btoa(doc.output());
      $.ajax({
          url: 'ChartPDF.aspx?pdfinput=1',
          type: 'post',
          async: false,
          contentType: 'application/json; charset=utf-8',
          data: base64pdf,
          dataType: 'json'
      });
    }
    

    ChartPDF.aspx.cs code:

    protected void Page_Load(object sender, EventArgs e)
        {
            var pdfinput= Request.QueryString["pdfinput"];
            if (pdfinput!= null)
            {
                var jsonString = string.Empty;
                HttpContext.Current.Request.InputStream.Position = 0;
                using (var inputStream = new StreamReader(Request.InputStream))
                {
                    jsonString = inputStream.ReadToEnd();
                }
                var byteArray = Convert.FromBase64String(jsonString);
                //Get your desired path for saving file
                File.WriteAllBytes(@"C:\ReportPDFs\Test.pdf", byteArray);
            }
        }
    

    I called up the page without any querystring parameter and the page creates the graph(Code not given for drawing the graph as it is not part of the qs.) and after that it calles createPDF() function which result in reloading the page and saving the graph as pdf file on server. Later i use the file from path.

    0 讨论(0)
  • 2020-12-05 06:27

    javascript

    doc = new jsPDF({
             unit: 'px',
             format: 'a4'
         });
        doc.addImage(img, 'JPEG', 20, 20);
        var data = {};
        var base64pdf = btoa(doc.output());
        $.ajax({
            url: 'WS/FileUploadHandler.ashx',
            type: 'post',
            async: false,
            contentType: 'application/json; charset=utf-8',
            data: base64pdf,
            dataType: 'json'
        });
    

    FileUploadHandler.ashx

    public void ProcessRequest(HttpContext context)
        {
            var jsonString = String.Empty;
            context.Request.InputStream.Position = 0;
            using (var inputStream = new StreamReader(context.Request.InputStream))
            {
                jsonString = inputStream.ReadToEnd();
            }
            var byteArray = Convert.FromBase64String(jsonString);
            File.WriteAllBytes(@"C:\Users\mahmoud.hemdan\Downloads\testtest.pdf", byteArray);
        }
    
    0 讨论(0)
  • 2020-12-05 06:29

    I managed to fix this using FormData(), here's how I did it:

    $(document).on("click", "#PDF", function () {
        var table = document.getElementById("result");
        var cols = [],
            data = [];
    
        function html() {
            var doc = new jsPDF('p', 'pt');
            var res = doc.autoTableHtmlToJson(table, true);
            doc.autoTable(res.columns, res.data);
            var pdf =doc.output(); //returns raw body of resulting PDF returned as a string as per the plugin documentation.
            var data = new FormData();
            data.append("data" , pdf);
            var xhr = new XMLHttpRequest();
            xhr.open( 'post', 'upload.php', true ); //Post to php Script to save to server
            xhr.send(data);
    
        }
        html();
    });
    

    upload.php

    if(!empty($_POST['data'])){
        $data = $_POST['data'];
        $fname = "test.pdf"; // name the file
        $file = fopen("testa/pdf/" .$fname, 'w'); // open the file path
        fwrite($file, $data); //save data
        fclose($file);
    } else {
        echo "No Data Sent";
    }
    

    The key part being var pdf =doc.output(); where you want to get the raw pdf data.

    0 讨论(0)
  • 2020-12-05 06:29

    I have successfully save jspdf file in server using jspdf, javascript and php with png image

    here is the javascript

    var doc = btoa(pdf.output());
    var data = new FormData();
    data.append("data", doc);
    var xhr = new XMLHttpRequest();
    xhr.open( 'post', 'data/test.php?name=' +name, true );
    alert(data);
    xhr.send(data);
    

    And the php file

    if(!empty($_POST['data'])){ 
     $data = base64_decode($_POST['data']);
     //$data = $_POST['data'];
    $name = $_GET['name'];
     $fname = $name."_bell_quote.pdf"; // name the file
     $file = fopen("../quote/" .$fname, 'w'); // open the file path
     fwrite($file, $data); //save data
     fclose($file);
     echo "Bell Quote saved";   
    }
    else {
     echo "No Data Sent";
    }
    
    0 讨论(0)
提交回复
热议问题