Use cpprest (Casablanca) to return PDF response

427 Views Asked by At

I am using cpprest in a server on Ubuntu Linux. So far I am able to process requests, and reply with JSON responses.

One of the requests that I accept needs to respond with a PDF file. I see that the http_request class has a reply() method that accepts an asynchronous stream. For the life of me, I can't figure out how to associate this stream with my PDF file on disk.

utility::string_t pdfFilename = getPdfFilename();
concurrency::streams::istream stream; // how do associate my pdfFilename?
request.reply(web::http::status_codes::OK, stream, "application/pdf");
1

There are 1 best solutions below

0
On

I hope you already figured it out. Here's how I reply with local pdf files

void replyPdf(web::http::http_request message, string_t file_name)
{
    concurrency::streams::fstream::open_istream(file_name, std::ios::in)
        .then([=](concurrency::streams::istream is)
        {
            web::http::http_response response(web::http::status_codes::OK);

            response.headers().add(L"Content-Disposition", U("inline; filename = \"") + file_name + U("\""));
            response.set_body(std::move(is), U("application/pdf"));

            message.reply(response).then([](pplx::task<void> t) {});
        });
}