none
Sharepoint document library: save a generated pdf RRS feed

  • Question

  • Hi,

    I have requirement to generate PDF file and save it as an attachment to SharePoint list item using JS

    I'm able to generate PDF using JSPDF but after attaching it to list item, I'm not able to open attached PDF

    JSPDF:

     var doc = new jsPDF();

    doc.text(20, 175, "test");

    doc.save("test.pdf"); //I'm able to open this downloaded PDF

    But when I try to convert it to blob file and upload as an attachment it is getting corrupted somehow. Any idea on this? Is there any other way to generate PDF and save as an list item attachment?

    I tried both SharePoint Rest and SP services to attach PDF. It's not working in both cases 

    //converted pdf doc blob to file
    var blob = new Blob();
    blob = doc.output('blob');
    var pdfFile = new File([blob], "test.pdf");
    
     var getFileBuffer = function (file) {
       var deferred = $.Deferred();
       var reader = new FileReader();
       reader.onload = function (e) {                                                
               deferred.resolve(e.target.result);
       }
       reader.onerror = function (e) {                                                
       deferred.reject(e.target.error);
       }
                                                
       reader.readAsArrayBuffer(file);
        return deferred.promise();
      };
    
      getFileBuffer(pdfFile).then(function (buffer) {
           var bytes = new Uint8Array(buffer);
            var content = new SP.Base64EncodedByteArray(); //base64 encoding
            for (var b = 0; b < bytes.length; b++) {                                                
              content.append(bytes[b]);
            }
           $().SPServices({
             operation: "AddAttachment",
             listName: "Certificates",
             listItemID: certItemId,
            fileName: fileName,
            attachment: content.toBase64String()
          });
    });

    Thursday, March 30, 2017 10:59 AM

Answers

  • Hi,

    Try this:

    You need update the list to your list name and the item id which you want to add attachment to.( this code use SharePoint REST api, you could check below link for reference)

    http://sympmarc.com/2016/04/20/uploading-attachments-to-sharepoint-lists-using-rest/

    function uploadAttachment() {
                var doc = new jsPDF();
                doc.text(20, 175, "test");
                var blob = doc.output('blob');            
    
                var arrayBuffer;
                var fileReader = new FileReader();
                fileReader.onload = function () {
                    arrayBuffer = this.result;
                    $.ajax({
                        url: _spPageContextInfo.webAbsoluteUrl +
                         "/_api/web/lists/getbytitle('Employee')/items('1')/AttachmentFiles/add(FileName='test.pdf')",
                        type: 'POST',
                        data: arrayBuffer,
                        processData: false,
                        headers: {
                            "Accept": "application/json; odata=verbose",
                            "content-type": "application/json; odata=verbose",
                            "X-RequestDigest": $('#__REQUESTDIGEST').val(),
                            "content-length": arrayBuffer.byteLength
                        },
                        success: successHandler,
                        error: errorHandler
                    })
                };
                fileReader.readAsArrayBuffer(blob);                       
            }
            function successHandler(data, textStatus, jqXHR) {
                alert("successHandler " + "textstatus:" + textStatus + "data: " + data);
            }
    
            function errorHandler(xhr, ajaxOptions, thrownError) {
                alert('Request failed: ' + xhr.status + '\n' + thrownError + '\n' + xhr.responseText);
            }

    Best Regards,

    Lee


    Please remember to mark the replies as answers if they help.
    If you have feedback for TechNet Subscriber Support, contact tnmff@microsoft.com

    Friday, March 31, 2017 3:47 AM

All replies

  • Hi,

    Try this:

    You need update the list to your list name and the item id which you want to add attachment to.( this code use SharePoint REST api, you could check below link for reference)

    http://sympmarc.com/2016/04/20/uploading-attachments-to-sharepoint-lists-using-rest/

    function uploadAttachment() {
                var doc = new jsPDF();
                doc.text(20, 175, "test");
                var blob = doc.output('blob');            
    
                var arrayBuffer;
                var fileReader = new FileReader();
                fileReader.onload = function () {
                    arrayBuffer = this.result;
                    $.ajax({
                        url: _spPageContextInfo.webAbsoluteUrl +
                         "/_api/web/lists/getbytitle('Employee')/items('1')/AttachmentFiles/add(FileName='test.pdf')",
                        type: 'POST',
                        data: arrayBuffer,
                        processData: false,
                        headers: {
                            "Accept": "application/json; odata=verbose",
                            "content-type": "application/json; odata=verbose",
                            "X-RequestDigest": $('#__REQUESTDIGEST').val(),
                            "content-length": arrayBuffer.byteLength
                        },
                        success: successHandler,
                        error: errorHandler
                    })
                };
                fileReader.readAsArrayBuffer(blob);                       
            }
            function successHandler(data, textStatus, jqXHR) {
                alert("successHandler " + "textstatus:" + textStatus + "data: " + data);
            }
    
            function errorHandler(xhr, ajaxOptions, thrownError) {
                alert('Request failed: ' + xhr.status + '\n' + thrownError + '\n' + xhr.responseText);
            }

    Best Regards,

    Lee


    Please remember to mark the replies as answers if they help.
    If you have feedback for TechNet Subscriber Support, contact tnmff@microsoft.com

    Friday, March 31, 2017 3:47 AM
  • Thank you Lee, above code worked
    Friday, March 31, 2017 5:58 AM