如何将jspdf从angular发送到nodejs服务器

pprl5pva  于 2022-12-03  发布在  Node.js
关注(0)|答案(1)|浏览(141)
type here

你好,我想使用jspdf将html转换为pdf,并发送到nodejs服务器
有人能帮我吗?
或者给予我点建议
我将此代码保存在浏览器中,并希望将其发送到nodejs服务器

public openPDF(): void {
    let DATA: any = document.getElementById('content');
    html2canvas(DATA).then((canvas) => {
      let fileWidth = 208;
      let fileHeight = (canvas.height * fileWidth) / canvas.width;
      const FILEURI = canvas.toDataURL('image/png');
      let PDF = new jsPDF('p', 'mm', 'a4');
      let position = 0;
      PDF.addImage(FILEURI, 'PNG', 0, position, fileWidth, fileHeight);
      PDF.save();
      
    });
  }
mwngjboj

mwngjboj1#

要在Angular中使用jspdf将HTML转换为PDF,可以执行以下步骤:

Install jspdf and html2canvas packages using npm:

npm install jspdf html2canvas

在组件中导入jspdf和html 2canvas包:

import * as jsPDF from 'jspdf';
import html2canvas from 'html2canvas';

使用html 2canvas函数将具有ID内容的HTML元素转换为canvas元素:

let DATA: any = document.getElementById('content');
html2canvas(DATA).then((canvas) => {
  // code to generate PDF goes here
});

Use the jsPDF constructor to create a new PDF object with the desired dimensions (in this case, A4):

let PDF = new jsPDF('p', 'mm', 'a4');

使用addImage方法将画布元素作为PNG图像添加到PDF:

PDF.addImage(canvas, 'PNG', 0, 0, canvas.width, canvas.height);

使用保存方法将PDF保存到用户设备:

PDF.save();

要将生成的PDF发送到Node.js服务器,可以使用Angular中的httpClient模块向服务器发出POST请求,沿着将PDF数据作为请求主体。

import { HttpClient } from '@angular/common/http';

constructor(private httpClient: HttpClient) {}

public sendPDF(): void {
  let DATA: any = document.getElementById('content');
  html2canvas(DATA).then((canvas) => {
    let fileWidth = 208;
    let fileHeight = (canvas.height * fileWidth) / canvas.width;
    const FILEURI = canvas.toDataURL('image/png');
    let PDF = new jsPDF('p', 'mm', 'a4');
    let position = 0;
    PDF.addImage(FILEURI, 'PNG', 0, position, fileWidth, fileHeight);
    // get the PDF data as a base64-encoded string
    const pdfData = PDF.output('datauristring');

    // send the PDF data to the server
    this.httpClient.post('https://your-server.com/pdf', pdfData)
      .subscribe(response => {
        // handle the response from the server
      });
  });
}

在服务器端,您可以使用Node.js缓冲区模块中的Buffer类将base64编码的PDF数据转换为二进制缓冲区,然后可以将其保存到文件或作为响应发送到客户端。

const buffer = require('buffer');

app.post('/pdf', (req, res) => {
  const pdfData = req.body;
  // convert the base64-encoded PDF data to a binary buffer
  const pdfBuffer = buffer.Buffer.from(pdfData, 'base64');

  // save the PDF buffer to a file
  fs.writeFileSync('file.pdf', pdfBuffer);

// send the PDF file as a response to the client
res.sendFile('file.pdf');
});

我希望这对你有帮助!

相关问题