【发布时间】:2018-10-19 23:40:02
【问题描述】:
我按照以下链接在我的 Angular 5 应用程序的新选项卡中显示 pdf 页面。但无法达到效果。
我正在使用来自 spring 控制器 api 的字节数组。
PDF Blob is not showing content, Angular 2
PDF Blob - Pop up window not showing content
我尝试了以下选项,但没有一个有效。
试用 1
将响应作为 json 消费
组件.ts
clickEvent(){
this.service.getPDF().subscribe((response)=>{
let file = new Blob([response.byteString], { type: 'application/pdf' });
var fileURL = URL.createObjectURL(file);
window.open(fileURL);
})
}
service.ts
getPDF(){
const url = `${this.serviceUrl}/pdf`;
const httpOptions = {
headers: new HttpHeaders(
{
'Accept': 'application/json',
'responseType':'blob'
}
)
};
return this.http.get<any>(url, httpOptions);
}
试用 2
将响应作为 json 消费
组件.ts
clickEvent(){
this.service.getPDF().subscribe((response)=>{
let file = new Blob([response.byteArray], { type: 'application/pdf' });
var fileURL = URL.createObjectURL(file);
window.open(fileURL);
})
}
service.ts
getPDF(){
const url = `${this.serviceUrl}/pdf`;
const httpOptions = {
headers: new HttpHeaders(
{
'Accept': 'application/json',
'responseType':'arraybuffer'
}
)
};
return this.http.get<any>(url, httpOptions);
}
试用 3
将响应消耗为字节
组件.ts
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 = {
headers: new HttpHeaders(
{
'responseType':'blob' //both combination
//'responseType' : 'arraybuffer'
}
)
};
return this.http.get<any>(url, httpOptions);
}
通过所有的组合,我只得到两个结果。 空的 pdf 文档或无法加载 PDF 文档。
为了理解发布 java spring 控制器代码。
controller.java
@GetMapping(value = "/pdf")
public ResTest generatePDF(HttpServletResponse response) throws IOException {
ResTest test = new ResTest();
ByteArrayOutputStream baos = docTypeService.createPdf();
test.setByteArray(baos.toByteArray());
test.setByteString(new String(baos.toByteArray()));
return test;
}
【问题讨论】: