Angular 11发布pdf到.Net Core后端的请求



我想将html作为发布请求的一部分发送到.NET Core web api,在服务器上转换为pdf,并在客户端上接收此文件。我无法正确处理请求/响应方法,因为我在客户端上收到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);
}
);

最新更新