Angular 11 post 请求 .Net Core 后端的 pdf

Angular 11 post request for a pdf to .Net Core backend

我想将 html 作为 post 请求的一部分发送到 .NET Core web api,以便在服务器上转换为 pdf 并接收此文件在客户端上。我无法正确使用 request/response 方法,因为我在客户端收到 415 或 400 响应或解析错误。 在 Angular 我有

   this.apiService
      .generatePdf((this.diagram.nativeElement as HTMLDivElement).innerHTML)
      .subscribe((response) => {
        const url = window.URL.createObjectURL(new Blob([response]));
        const link = document.createElement('a');
        link.href = url;
        link.setAttribute('download', 'file.pdf');
        document.body.appendChild(link);
        link.click();
      });

generatePdf(html: string): Observable<any> {
    return this.http.post(
      `${this.urls.document}/html2pdf`,
      { html },
      {
        headers: new HttpHeaders().set('Content-Type', 'application/pdf')
      }
    );

后端的方法是

[HttpPost("html2pdf")]
public FileResult Html2Pdf([FromBody] string html)
{
   HttpContext.Response.ContentType = "application/pdf";
   var stream = repository.Html2Pdf(html);
   return File(stream, "application/pdf");
}

编辑:我最近的努力导致 400 错误是这样的

this.apiService
      .generatePdf((this.diagram.nativeElement as HTMLDivElement).innerHTML)
      .subscribe(
        (blob) => {
          downloadFile(blob, 'diagram.pdf');
        }
          );
  generatePdf(html: string): Observable<Blob> {
    return this.http.post<Blob>(
      `${this.urls.document}/html2pdf`,
      { html },
      { responseType: 'blob' as 'json' }
    );
  }

在服务器上

[HttpPost("html2pdf")]
        public async Task<IActionResult> Html2Pdf([FromBody] string html)
        {            
            var bytes = await repository.Html2Pdf(html);
            return File(bytes, "application/pdf");
        }

后端

[HttpPost("html2pdf")]
public async Task<IActionResult> Html2Pdf([FromBody] DocumentConvertRequest model)
{            
    var bytes = await repository.Html2Pdf(model.Html);
    return new FileContentResult(bytes, "application/pdf");
}

前端

generatePdf(html: string): Observable<any> {
  return this.http.post(
      `${this.urls.document}/html2pdf`,
      JSON.stringify({ html }),
      {
        headers: this.headers,
        responseType: 'arraybuffer'
      }
    );
  }

this.apiService
  .generatePdf((this.diagram.nativeElement as HTMLDivElement).innerHTML)
  .subscribe(
    (res) => {          
      const newBlob = new Blob([res], { type: 'application/pdf' });
      const data = window.URL.createObjectURL(newBlob);

      const link = document.createElement('a');
      link.href = data;
      link.download = 'diagram.pdf';
      link.dispatchEvent(
        new MouseEvent('click', {
          bubbles: true,
          cancelable: true,
          view: window
        })
      );

      setTimeout(function () {            
        window.URL.revokeObjectURL(data);
        link.remove();
      }, 0);
    }
  );