下载通过角度前端在nodejs中使用pdfkit库创建的Pdf

问题描述 投票:2回答:1
async createpdf(){

const doc = new PDFDocument();

doc.pipe(fs.createWriteStream('example.pdf'));

// content of the pdf

doc.end();
}

我在项目中使用了nodejs和angular。为了导出pdf,我使用了pdfkit库并导出了pdf。但是,当单击有角度的前端中的按钮时,我需要下载pdf。单击角形前端中的按钮时,您能解释如何下载pdf吗?

这是我在component.ts中添加的代码

exportToPdf(){
  this.classroomService.createpdf();
  this.subscription = this.classroomService.alertMessageOccured
  .subscribe((alert) => {
   if (alert.code == 200) {
    this.alertService.clear();
          this.alertService.success(alert.message);


        } else {
          this.alertService.clear();
          this.alertService.error(alert.message);
        }
 })
}

这是按钮的代码

 <button class="btn btn-primary btn-sm float-right" (click)="exportToPdf()">
              Export to PDF
  </button>
node.js angular pdfkit
1个回答
0
投票

成功创建pdf后,将成功/失败结果返回给您的客户端

为了让用户知道它是否失败,

如果成功,请请求下载路径

app.get('/download-pdf', function(req, res){
  const pdf_file = `${__dirname}/your_file.pdf`;
  res.setHeader('Content-type', 'application/pdf');
  res.download(pdf_file); 
});

这是一个简单的示例,但是请记住要返回唯一的ID,以下载特定文件或进行其他任何身份验证。

© www.soinside.com 2019 - 2024. All rights reserved.