1. 使用 gotenberg 和 LibreOffice
a. 开启 docker,运行以下指令
 docker run --rm -p 3000:3000 gotenberg/gotenberg:8
 gotenbderg 默认运行在本地 3000 端口
 
 b. 项目中添加如下依赖
 npm install chromiumly dotenv -D
 chromiumly 是用来连接 gotenberg 服务的包,dotenv 用来在 .env环境文件设置连接配置。
 c. 项目中新建 .env 文件,添加如下配置 (本地 gotenberg 服务地址)
GOTENBERG_ENDPOINT=http://localhost:3000  
 
d. 编写并执行脚本文件,内容如下:将 tes2.xlsx 转换为 test5.pdf
import { PDFEngines, LibreOffice } from "chromiumly";
async function run () {
  const buffer = await LibreOffice.convert({
    files: [
      "tes2.xlsx",
    ],
    properties: {
      singlePageSheets: true,
      skipEmptyPages: true,
      addOriginalDocumentAsStream: true,
    },
    pdfa: 'PDF/A-1b',
    pdfUA: true,
    merge: true,
    // metadata: true,
    // maxImageResolution: 75,
    reduceImageResolution: true,
  });
  await PDFEngines.generate("test5.pdf", buffer);
}
run();
 
效果:
 

 数据链路:通过 LibreOffice 获取 excel 文件 的 buffer 数据 ----> 再 使用 gotenberg 生成 pdf 文件;
注: gotenberg 同时支持将提供的 url 的目标页、 markdown、html 转换为 pdf 文件。
https://github.com/gotenberg/gotenberg
2. 使用 onlyoffice 搭建文档转换服务
a. 开启 docker , 运行以下指令
 docker run -i -t -d -p 80:80 onlyoffice/documentserver
 onlyoffice 的文档服务将运行在本地 80 端口。
 b. 调用 onlyoffice 的转换 api, 使用 post 请求,地址如下:
 http://localhost/ConvertService.ashx
 Postman 示例:
 
 请求头设置 Accept 为 application/json,不然默认情况下返回 xml格式
 
注意每次请求文档转换时,key值必须是新值,否则每次返回都是上一次转换后的文档地址
效果:返回转换后的文档地址;鼠标 hover 到返回的链接地址上,按住ctrl  ,点击即可通过浏览器下载文件。
 
 贴出示例中 将 excel文件转为 pdf的请求 json
{
    "url":"https://xxx.aliyuncs.com/xxxx/xxx.xlsx",
    "filetype": "xlsx",
    "key": "kljlkjklkhjKhirz6zTPdfd7", // 任意字符即可
    "outputtype": "pdf",
    "region": "en-US",
    "pdf":{
        "form":true
    },
    "spreadsheetLayout": {
        "ignorePrintArea": true,
        "orientation": "portrait",
        "fitToWidth": 0,
        "fitToHeight": 0,
        "scale": 100,
        "headings": true,
        "gridLines": true,
        "pageSize": {
            "width": "410mm",
            "height": "297mm"
        },
        "margins": {
            "left": "5mm",
            "right": "5mm",
            "top": "5mm",
            "bottom": "5mm"
        }
    },
    "title": "test1.pdf"
}
                


















