Robbie Milejczak
Robbie Milejczak

Reputation: 5770

Upload a javascript generated PDF file to server

Please note I am uploading a file generated at runtime, NOT a user submitted file. This is where my problem lies, taking that file and sending it along has proven itself to be truly a challenge.

I'm using PDFMake to generate a pdf file. It took me A LONG time to get this code working, tl;dr of it is I convert the pdf doc info to a buffer, make a new File object with that buffer, attach that file object to a formdata object, and send it to my server.

Here is the code:

    var pdfGen = pdfMake.createPdf(docDef);

    pdfGen.getBuffer(function(buffer){
        var pdf = new File(buffer, "testpdf.pdf", {type: "application/pdf"});
        var data = new FormData();
        data.append('upload', pdf);
        data.append('content-type', 'application/pdf');

        $.ajax({
            method: "POST",
            url: "/index.cfm?action=admin:service.upload_pdf",
            data: data,
            processData: false,
            contentType: false,
            success: function(msg){
                console.log(msg);
            },
            error: function(msg){
                console.log(msg);
            }
        })
    })

The problem is that the file I get on my server isn't a valid PDF. The application type is listed as application/octet-stream. The function I'm pushing the File object to SHOULD be rejecting everything except pdf's, so I'm not sure where the error is exactly.

I've been at this for two days now and I'm at a loss so any help is GREATLY appreciated.

Upvotes: 1

Views: 5315

Answers (1)

Luca Polito
Luca Polito

Reputation: 2882

Have you tried converting your generated PDF into Base64 and then sending the result to your server? Here's what I mean:

var pdfGen = pdfMake.createPdf(docDef);
pdfGen.getBase64((data) => {
    PostToServer(data);
});

Source: https://github.com/bpampuch/pdfmake

Upvotes: 2

Related Questions