I'm trying to do an API for downloading PDF, what I did is like so:
HttpResponseMessage result = new HttpResponseMessage();
MemoryStream stream = new MemoryStream();
try {
var base64 = "...";
byte[] pdfBytes = Convert.FromBase64String(base64);
stream = new MemoryStream(pdfBytes);
var resultPDF = Encoding.UTF8.GetString(stream.ToArray());
result.StatusCode = HttpStatusCode.OK;
result.Content = new StringContent(resultPDF);
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = "BuildingDetail.pdf" };
} catch (Exception e) {
stream.Close();
result.StatusCode = HttpStatusCode.InternalServerError;
result.ReasonPhrase = e.Message;// "Error occured while exporting csv file!";
} finally {
stream.Close();
}
When I trying to test the API out, it able to download, but PDF is empty.
I also tried to copy the base64
string and decode it by other free source decode and download
website it seems working fine, so makes the base64
is not the issue.
Any advice to this will be appreciated. Thanks.
Try to use ByteArrayContent:
HttpResponseMessage result = new HttpResponseMessage();
try
{
byte[] pdfBytes = System.IO.File.ReadAllBytes(pdfLocation);
result.StatusCode = HttpStatusCode.OK;
result.Content = new ByteArrayContent(pdfBytes );
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = "BuildingDetail.pdf" };
}
catch (Exception e)
{
result.StatusCode = HttpStatusCode.InternalServerError;
result.ReasonPhrase = e.Message;// "Error occured while exporting csv file!";
}