【问题标题】:Open PDF file in new tab在新选项卡中打开 PDF 文件
【发布时间】:2019-04-12 11:33:48
【问题描述】:

使用 Angular 6 在新选项卡中打开 PDF 文件。我试过这个:

休息控制器:

@RestController
@RequestMapping("/downloads")
public class DownloadsController {

    private static final String EXTERNAL_FILE_PATH = "/Users/test/Documents/blacklist_api.pdf";

    @GetMapping("export")
    public ResponseEntity<InputStreamResource> export() throws IOException {
        ClassPathResource pdfFile = new ClassPathResource(EXTERNAL_FILE_PATH);

        HttpHeaders headers = new HttpHeaders();
        headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
        headers.add("Pragma", "no-cache");
        headers.add("Expires", "0");

        return ResponseEntity.ok().headers(headers).contentLength(pdfFile.contentLength())
                .contentType(MediaType.parseMediaType("application/pdf"))
                .body(new InputStreamResource(pdfFile.getInputStream()));
    }
}

服务:

@Injectable({
  providedIn: 'root'
})
export class DownloadService {

  constructor(private http: HttpClient) {
  }

  exportPdf() {
    return this.http.get(environment.api.urls.downloads.getPdf,  { responseType: 'blob' });
  }
}

组件:

@Component({
  selector: 'app-download',
  templateUrl: './download.component.html',
  styleUrls: ['./download.component.scss']
})
export class DownloadComponent implements OnInit {

  constructor(private downloadService: DownloadService,
              private router: Router,
              private route: ActivatedRoute) {
  }

  ngOnInit() {

  }

  export() {     
     window.open(this.downloadService.exportPdf());
  }
}

HTML 代码:

<h1 class="title">Export</h1>

<div class="content grid-wrapper">

  <div class="export">
      <button class="btn btn-secondary" (click)="export()">Export</button>
    </div>

</div>

当我单击按钮时,为了在新选项卡中打开 PDF 文档,实现 Angular 服务和组件的正确方法是什么?

你能建议吗?

【问题讨论】:

  • 您不能只使用来自后端的响应。您必须创建 Blob 对象,然后创建链接并自动打开它或用于&lt;embed&gt;。有关详细信息,请参阅stackoverflow.com/questions/21628378/…。 @edit:线程用于 Angular.JS,但您需要的部分是用 vanilla js 编写的
  • stackoverflow.com/questions/35368633/… 这应该会有所帮助
  • 我用我尝试实现的实现更新了答案,但仍然出现错误。你能建议如何解决它吗?
  • 你能发布你从服务器得到的响应吗?
  • 使用上面的代码,我得到了具有相同页面的新标签:PDF 文档未显示。

标签: angular typescript angular6


【解决方案1】:

你可以试试

export() {
    this.downloadService.exportPdf();
}

...

exportPdf(){
     window.open(environment.api.urls.downloads.getPdf);
}

【讨论】:

  • 这是为服务的组件?
  • 服务。获取组件中ngOnInit 的装备。只需从组件export 调用服务新export
  • 你能用工作示例更新你的答案吗?
  • 我更新了我尝试实现的代码,但是当我按下按钮时没有任何反应。知道为什么吗?
  • 好吧,我得到“访问此资源需要完全身份验证”。为什么 window.open 应该放在服务中?也许它应该放在组件中?
猜你喜欢
  • 1970-01-01
  • 2020-10-09
  • 2018-11-28
  • 1970-01-01
  • 1970-01-01
  • 2017-02-07
  • 1970-01-01
  • 1970-01-01
  • 2021-12-26
相关资源
最近更新 更多