You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Node.js实现提交HTML表单后生成含用户输入的可下载PDF

实现方案

1. 技术依赖说明

  • 后端采用Express.js处理HTTP请求与表单数据
  • 使用pdfkit库生成结构化PDF文件
  • 用Express内置的urlencoded中间件解析表单提交的字段内容

2. 项目初始化

首先执行以下命令安装所需依赖:

npm init -y
npm install express pdfkit

3. 编写后端服务代码

在项目根目录新建server.js文件,内容如下:

const express = require('express');
const PDFDocument = require('pdfkit');
const app = express();
const port = 3000;

// 解析表单提交的POST数据
app.use(express.urlencoded({ extended: true }));

// 访问根路径返回表单页面
app.get('/', (req, res) => {
  res.send(`
  <form method="POST" action="/submit">
      <label for="name">Name:</label>
      <input type="text" name="name" id="name"  /><br><br>
      <label for="email">Email:</label>
      <input type="email" name="email" id="email"  /><br><br>
      <label for="contact">Contact Number:</label>
      <input type="phone" name="contact" id="contact"  /><br><br>
      <label for="company">Organization:</label>
      <input type="text" name="company" id="company"  /><br><br>
      <label for="designation">Designation:</label>
      <input type="text" name="designation" id="designation"  /><br><br>

      <input type="submit" value="生成并下载PDF">
    </form>
  `);
});

// 处理表单提交,生成PDF并返回下载
app.post('/submit', (req, res) => {
  const { name, email, contact, company, designation } = req.body;
  // 设置响应头,触发浏览器下载
  res.setHeader('Content-Type', 'application/pdf');
  res.setHeader('Content-Disposition', `attachment; filename=${name}_信息表.pdf`);

  // 创建PDF文档
  const doc = new PDFDocument();
  // 将PDF流直接导入响应对象
  doc.pipe(res);

  // 写入PDF内容
  doc.fontSize(20).text('用户提交信息表', { align: 'center' });
  doc.moveDown(2);
  doc.fontSize(14);
  doc.text(`姓名:${name}`);
  doc.moveDown(0.5);
  doc.text(`邮箱:${email}`);
  doc.moveDown(0.5);
  doc.text(`联系电话:${contact}`);
  doc.moveDown(0.5);
  doc.text(`所属机构:${company}`);
  doc.moveDown(0.5);
  doc.text(`职位:${designation}`);

  // 结束PDF写入
  doc.end();
});

app.listen(port, () => {
  console.log(`服务运行在 http://localhost:${port}`);
});

4. 运行测试

执行以下命令启动服务:

node server.js

打开浏览器访问http://localhost:3000,填写表单后点击提交按钮,浏览器会自动下载包含你提交内容的PDF文件。

内容的提问来源于stack exchange,提问作者Sachin Bhutekar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 12:57:03