Open pdf from bytes array in angular 5
At last, I was able to render pdf. There were two small mistakes from my side.
1 st Problem was, I gave 'responseType' inside HttpHeaders which was wrong.
It should be outside as below.
2 nd Problem was, even though if you mention as responseType : 'arraybuffer', it was unable to take it. For that you need to mention as responseType : 'arraybuffer' as 'json'.(Reference)
The corrected and working code below.
Trial 3
component.ts (nochanges)
clickEvent(){
this.service.getPDF().subscribe((response)=>{
let file = new Blob([response], { type: 'application/pdf' });
var fileURL = URL.createObjectURL(file);
window.open(fileURL);
})
service.ts
getPDF(){
const url = `${this.serviceUrl}/pdf`;
const httpOptions = {
'responseType' : 'arraybuffer' as 'json'
//'responseType' : 'blob' as 'json' //This also worked
};
return this.http.get<any>(url, httpOptions);
}
Referred from the below link
https://github.com/angular/angular/issues/18586
Angular 5 - Display Embedded PDF from byte[]
This approach works fine for me:
Controller:
[HttpGet("pdf/{docId}")]public ActionResult GetPdf(int docId){ var byteArray = get byte array... var cd = new System.Net.Mime.ContentDisposition { FileName = "Pdf_" + docId + ".pdf", Inline = true };
Response.Headers.Add("Content-Disposition", cd.ToString());
return File(outputBytes, "application/pdf");}
Angular 6 open pdf from byte array sent from WebAPI
Try this one:
service:
getPdfDocument(): Observable<any> {
let headers = new HttpHeaders({ 'Content-Type': 'application/JSON' });
return this.httpClient
.get(this.configuration.serverUrl + this.configuration.getPdfDoc,
{ headers: headers, responseType: 'blob' as 'json', observe: 'response' as 'body' }
});
}
request:
this.service.getPdfDocument()
.subscribe(
(data) => {
this.openFileForPrint(data);
});
openFileForPrint(data: HttpResponse<any>) {
let fileUrl = window.URL.createObjectURL(data);
window.open(fileUrl, '_blank', 'location=yes,height=600,width=800,scrollbars=yes,status=yes');
}
Server side[HttpGet]
public HttpResponseMessage getpdf(DateTime datum, int idlokacija)
{
var r = _printService.getdata(datum, idlokacija);
if (r == null)
{
return new HttpResponseMessage(HttpStatusCode.NotFound);
}
return SendPdfFile(r);
}
public static HttpResponseMessage SendPdfFile(string filePath, bool brisanje = true)
{
var stream = new FileStream(filePath, FileMode.Open);
HttpResponseMessage response = new FileHttpResponseMessage(filePath, brisanje)
{
StatusCode = HttpStatusCode.OK,
Content = new StreamContent(stream)
};
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
return response;
}
Convert byte array into blob (pdf file) and download using angular 5
Install file-saver
npm i --save file-saver@latest
Your service method
downloadPdf(id: number) {
return this.http
.get(this.apiRoutes.download + "/" + id, { responseType:'blob' })
.toPromise();
}
Now in your component
import { saveAs } from 'file-saver'
this.contractsService.downloadPdf(id)
.then(blob=> {
saveAs(blob, 'testing.pdf');
});
This should do the trick. The HttpClient will now extract the file from the stream. Also have a look in the documentation for blobs with the HttpClient.
How to get bytecode from selected pdf in angular
I'd suggest you to store the file as a base64 String in your database.
This would look as following. With the line number 2 you're fetching the file from your input event.
const reader = new FileReader();
reader.readAsDataURL(event.target.files[0]);
reader.onload = (event) => {
if (reader.result) {
//save pdf base64 into database
}
Related Topics
Java.Lang.Illegalargumentexception: Not a Managed Type: Class
How to Do a Limit Query in Jpql or Hql
How to Create a Spring JPA Repository Findby Query Using a Property That Contains a Keyword
Sqlite_Error - SQL Error or Missing Database (Near "Autoincrement": Syntax Error)
Regular Expression for Uppercase Letters in a String
How to Make a Jframe Button Open Another Jframe Class in Netbeans
How to Find Distinct Rows With Field in List Using JPA and Spring
Java.Lang.Classcastexception: [Ljava.Lang.Object; Cannot Be Cast to Classname
How to Skip the First Line of a CSV in Java
How to Send Image With Post Request
How to Disable Log4J Logging from Java Code
Nb: Java_Home Should Point to a Jdk Not a Jre
Spring @Value Annotation Always Evaluating as Null
Mockito Mock Objects Returns Null
How to Make the Icon Background of an Android App Transparent
How Does Bufferedreader Read Files from S3
The Request Was Rejected Because No Multipart Boundary Was Found in Springboot