在新标签页中打开PDF文件

时间:2018-11-08 21:40:50

标签: angular typescript angular6

使用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>

单击按钮时,为将Angular服务和组件打开PDF文档到新选项卡该怎么做?

你能建议吗?

1 个答案:

答案 0 :(得分:0)

您可以尝试

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

...

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