PDF転送docxのオンラインサービスを確立する

7514 ワード

まず、typeScriptのexpressアプリケーションを構築します.
package.json
{
  "name": "pdf2docx",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "nodemon ./src/index.ts",
    "build": "tsc --project ./",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "codetyphon",
  "license": "ISC",
  "dependencies": {
    "@types/multer": "^1.4.4",
    "cors": "^2.8.5",
    "express": "^4.17.1",
    "multer": "^1.4.2",
    "winax": "^1.20.0"
  },
  "devDependencies": {
    "@types/cors": "^2.8.7",
    "@types/express": "^4.17.8",
    "@types/node": "^14.11.2",
    "nodemon": "^2.0.4",
    "ts-node": "^9.0.0",
    "tslint": "^6.1.3",
    "typescript": "^4.0.3"
  }
}

tsconfig.json
{
    "compilerOptions": {
        "target": "es6",
        "module": "commonjs",
        "rootDir": "./src",
        "outDir": "./build",
        "esModuleInterop": true,
        "strict": true
    }
}

srcindex.ts
var express = require('express')
import { Request, Response, NextFunction } from 'express'
import cors from 'cors'

var app = express()
app.use(cors())
var port = 9090

app.get('/', async function (req: Request, res: Response) {
    res.send('hello')
})

app.listen(port, '0.0.0.0', () => console.log(`app listening on port ${port}!`))

次の操作を開始できます.
yarn start

次に、PDFファイルをアップロードできるようにmulter(アップロードされたミドルウェア)をインストールします.
yarn add multer

次にwinaxをインストールしてactivexを操作します.
yarn add winax

今、package.jsonは以下の通りです.
{
  "name": "pdf2docx",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "nodemon ./src/index.ts",
    "build": "tsc --project ./",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "codetyphon",
  "license": "ISC",
  "dependencies": {
    "@types/multer": "^1.4.4",
    "cors": "^2.8.5",
    "express": "^4.17.1",
    "multer": "^1.4.2",
    "winax": "^1.20.0"
  },
  "devDependencies": {
    "@types/cors": "^2.8.7",
    "@types/express": "^4.17.8",
    "@types/node": "^14.11.2",
    "nodemon": "^2.0.4",
    "ts-node": "^9.0.0",
    "tslint": "^6.1.3",
    "typescript": "^4.0.3"
  }
}

srcindex.tsはマルチ、winaxを導入
import multer from 'multer'
var winax = require('winax');

Wordを作成アプリケーションの例
var word = new winax.Object('Word.Application');

Word.アプリケーションの具体的な使い方はhttps://docs.microsoft.com/en...を参照してください.
Multierの構成:
const storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, `${__dirname}/../upload`)
    },
    filename: function (req, file, cb) {
        cb(null, file.fieldname + '-' + Date.now() + '.pdf')
    }
})

const upload = multer({
    storage: storage,
    fileFilter: (req:Request, file, cb) => {
        if (file.mimetype == "application/pdf") {
            cb(null, true);
        } else {
            cb(null, false);
            return cb(new Error('Only .pdf format allowed!'));
        }
    }
})

ルーティングの設定:
app.post('/pdf2doc', upload.single('file'), async (req: Request, res: Response) => {
    try {
        const { originalname, mimetype, path } = req.file
        if (mimetype == 'application/pdf') {
            //do
            console.log(path)
            const doc = word.documents.open(path)
            const name = originalname.replace('.pdf', '.docx')
            doc.SaveAs2(`${__dirname}/../download/${name}`, 16)
            doc.close()
            res.json(`http://localhost:9090/download/${name}`);
        } else {
            res.json({
                err: true,
                msg: 'file type is not pdf'
            });
        }
    } catch (err) {
        console.log(err)
        res.sendStatus(400);
    }
})

ミドルウェアはfileを設定しており、アップロード時、ファイルのフィールドも同様にfileを必要とします.
upload.single('file')

ダウンロードディレクトリの設定
app.use('/download', express.static('download'))

最後に、POST MANでテストを行い、すべて正常です.
完全なsrcindex.ts:
var express = require('express')
import { Request, Response, NextFunction } from 'express'
import cors from 'cors'
import multer from 'multer'
var winax = require('winax');
const word = new winax.Object('Word.Application');
//https://docs.microsoft.com/en-us/javascript/api/word/word.application

const storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, `${__dirname}/../upload`)
    },
    filename: function (req, file, cb) {
        cb(null, file.fieldname + '-' + Date.now() + '.pdf')
    }
})

const upload = multer({
    storage: storage,
    fileFilter: (req:Request, file, cb) => {
        if (file.mimetype == "application/pdf") {
            cb(null, true);
        } else {
            cb(null, false);
            return cb(new Error('Only .pdf format allowed!'));
        }
    }
})

var app = express()
app.use(cors())
app.use('/download', express.static('download'))
var port = 9090

app.get('/', async function (req: Request, res: Response) {
    res.send('hello')
})

app.post('/pdf2doc', upload.single('file'), async (req: Request, res: Response) => {
    try {
        const { originalname, mimetype, path } = req.file
        if (mimetype == 'application/pdf') {
            //do
            console.log(path)
            const doc = word.documents.open(path)
            const name = originalname.replace('.pdf', '.docx')
            doc.SaveAs2(`${__dirname}/../download/${name}`, 16)
            doc.close()
            res.json(`http://localhost:9090/download/${name}`);
        } else {
            res.json({
                err: true,
                msg: 'file type is not pdf'
            });
        }
    } catch (err) {
        console.log(err)
        res.sendStatus(400);
    }
})

app.listen(port, '0.0.0.0', () => console.log(`app listening on port ${port}!`))

最後に、すべてのコードはhttps://github.com/codetyphon...にあります.