我想发送html,作为post请求的一部分到一个.NET核心网络api,转换为一个pdf在服务器上,并在客户端接收这个文件。我无法正确地获得请求/响应方法,因为我在客户机上得到了415或400个响应或解析错误。在角度上我
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");
}发布于 2020-11-21 08:16:45
后端
[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);
}
);https://stackoverflow.com/questions/64925734
复制相似问题