1

I have generated a PDF document using PDFSharp. It looks fine when opened locally, or when opened in a web browser via a URL linking directly to the document. However, when I stream the document to my client code via a WebAPI method, and display it using FileSaver.js (in the context of an Angular 2 application) the image in the downloaded document is a black box (though the text displays just fine). I have done a lot of Googling on this, but nothing has worked. Can anyone tell me what I'm doing wrong?

My server side code:

public HttpResponseMessage GetAssignmentAssessmentPdf(int id)
    {
        string pdfDocPath = HttpContext.Current.Server.MapPath("~/App_Data/LastAssignmentAssessment.pdf");
        var stream = new MemoryStream(File.ReadAllBytes(pdfDocPath), 0, 0, true, true);
        stream.Position = 0;
        var result = new HttpResponseMessage(HttpStatusCode.OK)
        {
            Content = new ByteArrayContent(stream.GetBuffer())
        };

        result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
        result.Content.Headers.ContentDisposition.FileName = "LastAssignmentAssessment.pdf";
        result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");

        return result;
    }

The TypeScript code in my Angular 2 application (leveraging FileSaver.js):

// let user get PDF 
downloadAssignmentAssessmentPDF() {
    let self = this;
    self._dataService.getDocument("FileDownload/GetAssignmentAssessmentPdf/", 0).subscribe(
        (pdf: any) => self.download('LastAssignmentAssessment.pdf', pdf),
        (error: any) => self._errorService.handleServerErrorResponse(error)
    );
}

// see http://stackoverflow.com/questions/2897619/using-html5-javascript-to-generate-and-save-a-file
download(filename: string, content: any) {
    let blob = new Blob([content], { type: "application/pdf" });
    saveAs(blob, filename);
}
JRS
  • 569
  • 9
  • 26
  • Note that MediaTypeHeaderValue("application/octet-stream") was previously MediaTypeHeaderValue("application/pdf") - I changed it just to experiment, but it made no difference either way. – JRS Dec 10 '16 at 18:57
  • In Firefox, there is no black box, but no image either - it's just missing (though space reserved for the image in the PDF is preserved). – JRS Dec 10 '16 at 19:03
  • Additionally, if I call the Web API method directly from the browser, it downloads the document perfectly, with the image visible. So the problem appears to be in the processing of the return data by the javascript. But that's as far as I have been able to get. – JRS Dec 10 '16 at 19:06

0 Answers0