angular - Display PDF file from C# to Angular2 view -
i'm trying display pdf uploaded server. pdf resides inside app_data folder. want fetch using c# web api 2 , display in angular 2 frontend view.
c# code:
httpresponsemessage response = request.createresponse(httpstatuscode.badrequest); string filename = "somefilename.pdf"; byte[] buffer = new byte[0]; memorystream memstream = new memorystream(); if (filename != "") { pdfreader reader = new pdfreader(path.combine(httpcontext.current.request.physicalapplicationpath) + "/app_data/uploads/pdfs/" + filename); pdfstamper stamper = new pdfstamper(reader, memstream); response = request.createresponse(httpstatuscode.ok); buffer = memstream.toarray(); response.content = new streamcontent(new memorystream(buffer)); response.content.headers.contenttype = new mediatypeheadervalue("application/pdf"); response.content.headers.contentlength = buffer.length; contentdispositionheadervalue contentdisposition = null; if (contentdispositionheadervalue.tryparse("inline; filename=" + filename, out contentdisposition)) { response.content.headers.contentdisposition = contentdisposition; } } return response;
angular 2 code:
this.documentsservice.getfile() .subscribe((response: any) => { let file = new blob([response], { type: 'application/pdf' }); let url = url.createobjecturl(file); window.open(url); });
i think angular code wrong. nevertheless, first goal here fetch mvc side. right file gets downloaded , it's corrupted or there's not fetch correctly. give me 15bytes size pdf file, know there's wrong. i'm using itextsharp in c# backend.
thanks in advance!
from comment (providing answer easier code):
if (filename != "") { var fs = system.io.file.openread(filename); _mydisposable = fs; // see further down in answer. var response = request.createresponse(httpstatuscode.ok); response.content = new streamcontent(fs); response.content.headers.contenttype = new mediatypeheadervalue("application/pdf"); return response; } return response;
edit: code posted above works me. problem disposing of stream. best way creating private idisposable member on controller class, , adding dispose override, sort of this:
private idisposable _mydisposable; public override void dispose(bool disposing) { if (disposing && _mydisposable != null) _mydisposable.dispose(); }
please note assumes asp.net done request (which seems reasonable, because it's disposing of controller), should correct.
Comments
Post a Comment