如何在Angular 18应用中渲染Spring Boot API返回的PDF文件?
解决Angular内嵌Spring Boot返回PDF无响应的问题
核心原因:Angular安全策略拦截了URL
Angular的DomSanitizer会自动拦截它认为不安全的资源URL,即便地址是同源的,直接绑定到src/data属性时也会被标记为不安全,导致浏览器不发起请求。而<a>标签的href不受此限制,因此能正常跳转。
解决步骤
1. 在组件中注入DomSanitizer并处理URL
在Angular组件中引入DomSanitizer和SafeResourceUrl,将原始pdfUrl转换为安全的资源URL:
import { Component, Input } from '@angular/core'; import { DomSanitizer, SafeResourceUrl } from '@angular/platform-browser'; @Component({ selector: 'app-pdf-viewer', templateUrl: './pdf-viewer.component.html', styleUrls: ['./pdf-viewer.component.css'] }) export class PdfViewerComponent { @Input() file: any; safePdfUrl: SafeResourceUrl; constructor(private sanitizer: DomSanitizer) { // 从file对象生成原始API地址 const rawPdfUrl = `/api/file/${this.file.id}`; // 转换为安全资源URL this.safePdfUrl = this.sanitizer.bypassSecurityTrustResourceUrl(rawPdfUrl); } }
2. 在模板中使用处理后的安全URL
将模板里的pdfUrl替换为处理后的safePdfUrl:
<!-- 三种标签选其一即可,推荐embed或object --> <embed [src]="safePdfUrl" type="application/pdf" width="100%" height="500" /> <object [data]="safePdfUrl" type="application/pdf" width="100%" height="500"></object> <iframe [src]="safePdfUrl" type="application/pdf" width="100%" height="500"></iframe>
额外验证点
- 检查Spring Boot响应头:确保接口返回的
Content-Disposition不是attachment,该头会触发浏览器下载而非内嵌渲染。可改为inline或直接不设置:@GetMapping("/api/file/{fileId}") public ResponseEntity<byte[]> getFile(@PathVariable String fileId) { byte[] pdfContent = // 从存储介质获取文件内容 HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_PDF); // 可选:指定内嵌显示的文件名 headers.setContentDispositionInline("document.pdf"); return new ResponseEntity<>(pdfContent, headers, HttpStatus.OK); } - 无需HTTPS或浏览器设置:开发环境下HTTP完全支持内嵌PDF,不需要强制HTTPS,也无需修改浏览器默认配置。
内容的提问来源于stack exchange,提问作者Vihung
相关产品推荐
相关产品推荐

