我正在按照以下链接在我的angular 5应用程序的新选项卡中显示pdf页面 . 但无法达到效果 .
我正在使用spring controller api中的bytes数组 .
PDF Blob is not showing content, Angular 2
PDF Blob - Pop up window not showing content
我尝试了以下选项,但它们都没有工作 .
试验1
作为json消耗了回应
component.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消耗了回应
component.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
消耗响应为字节
component.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;
}
3 回答
最后,我能够渲染pdf . 我身边有两个小错误 .
第一个问题是,我在HttpHeaders中给出了'responseType',这是错误的 . 它应该在外面如下 .
第二个问题是,即使你提到responseType:'arraybuffer',也无法接受它 . 为此,您需要提及responseType:'arraybuffer' as 'json' . (Reference)
下面的更正和工作代码 .
Trial 3
component.ts(nochanges)
service.ts
从以下链接中提到
https://github.com/angular/angular/issues/18586
角度和pdf显示我有同样的问题 . 我将描述我的解决方案 - 使用base64编码的字符串 . 所有现代浏览器都支持base64 .
import java.util.Base64
解码字节数组data:application/pdf;base64,
.参考 . 到哑剧类型:https://en.wikipedia.org/wiki/Media_type
如果需要在新窗口中打开文档:
bypassSecurityTrustUrl
将清理您的网址 . 我记得角度安全性存在一些问题,这使我无法看到内容 .PS . 在检查角度如何工作之前,我建议您将pdf文件存储在驱动器上并尝试打开它 . 我的意思是,您应该确定您的文件是有效的,您可以使用简单的阅读器打开它 .
更新 . 最简单的解决方案是使用pdf.js库https://github.com/mozilla/pdf.js
你找了一个角度组件来包装pdf.js吗?
样品用法:
pdfSrc
可以是网址string
或UInt8Array