node.js接收PDF文件并打印

ny6fqffe  于 2023-08-04  发布在  Node.js
关注(0)|答案(1)|浏览(207)

我尝试创建一个端点API,它可以:
1.接收来自标准html表单的PDF文档
1.存储pdf文件
1.使用pdf-to-printer打印输出
1.从点2删除临时pdf文件
这是目前的主要结构-我不能得到文件后解决…

import express from "express";
import ptp from "pdf-to-printer";
import fs from "fs";
import path from "path";

const app = express();
const port = 3000;

ptp.getPrinters().then(console.log);

app.post('', express.raw({ type: 'application/pdf' }), async(req, res) => {

    const options = {
        printer: "Microsoft Print to PDF"
        //pages: "1-3,5",
        //scale: "fit",
      };

    /*if (req.query.printer) {
        options.printer = req.query.printer;
    }*/
    const tmpFilePath = path.join(`./tmp/${Math.random().toString(36).substr(7)}.pdf`);

    fs.writeFileSync(tmpFilePath, req.body, 'binary');
    await ptp.print(tmpFilePath, options);
    fs.unlinkSync(tmpFilePath);

    res.status(204);
    res.send();
});

app.listen(port, () => {
    console.log(`PDF Printing Service listening on port ${port}`)
});

字符串
我的“文件上传”只是一个普通的HTML表单-但我不能让它工作

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>PDF Printer</title>
    <link rel="stylesheet" href="style.css">
  </head>
  <body>
    <form action="http://localhost:3000" method="post" enctype="multipart/form-data">
        <input type="file" name="someExpressFiles" id="myFile" size="500" />
        <input type="text" name="title" />
        <br />
        <input type="submit" value="Upload" />
        </form>
  </body>
</html>

dgjrabp2

dgjrabp21#

公平地说,我也是新来的,但你可以试试这个与穆特

npm install multer

字符串
我们使用req.file.path来获取上传的PDF文件的路径,该文件由multer临时存储。这应该可以解决您遇到的“TypeError [ERR_INVALID_ARG_TYPE]”问题

import express from "express";
import ptp from "pdf-to-printer";
import multer from "multer";
import path from "path";
import fs from "fs/promises";

const app = express();
const port = 3000;

app.use(express.urlencoded({ extended: true }));
app.use(express.json());

const storage = multer.diskStorage({
  destination: "./tmp",
  filename: (req, file, cb) => {
    const uniqueSuffix = Date.now() + "-" + Math.round(Math.random() * 1e9);
    cb(null, "pdf_" + uniqueSuffix + path.extname(file.originalname));
  }
});

const upload = multer({ storage });

app.post('/print', upload.single("pdfFile"), async (req, res) => {
  try {
    const pdfFilePath = req.file.path;
    const options = {
      printer: "Microsoft Print to PDF"
      // Other print options here
    };

    await ptp.print(pdfFilePath, options);
    await fs.unlink(pdfFilePath);

    res.status(200).send("PDF printed successfully.");
  } catch (error) {
    console.error(error);
    res.status(500).send("Error printing PDF.");
  }
});

app.listen(port, () => {
  console.log(`PDF Printing Service listening on port ${port}`);
});

相关问题