代码之家  ›  专栏  ›  技术社区  ›  Atul kumar singh

将doc Node.js缓冲区转换为pdf文件以将其输出到客户端

  •  1
  • Atul kumar singh  · 技术社区  · 6 年前

    我有一个docx Node.js缓冲区。

    var buf = doc.getZip()
                 .generate({type: 'nodebuffer'});
    
    console.log("buffer is ", buf);
    

    我得到的缓冲

    <Buffer 50 4b 03 04 0a 00 00 00 00 00 42 42 3d 4d 23 df 99 8f 65 05 00 00 65 05 00 00 13 00 00 00 5b 43 6f 6e 74 65 6e 74 5f 54 79 70 65 73 5d 2e 78 6d 6c 3c ... >
    

    我想把它转换成pdf文档并在客户端下载。我不想将文档保存到服务器端。

    我有一个解决方案,即将docx缓冲区转换为docx文件,然后将docx文件转换为pdf。

    fs.writeFileSync(path.resolve(__dirname, 'output.docx'), buf);
    docToPdf('./output.docx').then(
       console.log("it is done")
    )
    

    但是,这样,文档就保存在服务器中。docToPdf也在使用LibreOffice。有没有更好的方法可以避免这一切。

    1 回复  |  直到 6 年前
        1
  •  0
  •   JasonPlutext    6 年前

    https://www.npmjs.com/package/@nativedocuments/docx-wasm (这是新的,我写,2019年1月)将做你想做的。

    const fs = require('fs');
    const docx = require("@nativedocuments/docx-wasm");
    
    // init docx engine
    docx.init({
        // ND_DEV_ID: "XXXXXXXXXXXXXXXXXXXXXXXXXX",    // goto https://developers.nativedocuments.com/ to get a dev-id/dev-secret
        // ND_DEV_SECRET: "YYYYYYYYYYYYYYYYYYYYYYYYYY", // you can also set the credentials in the enviroment variables
        ENVIRONMENT: "NODE", // required
        LAZY_INIT: true      // if set to false the WASM engine will be initialized right now, usefull pre-caching (like e.g. for AWS lambda)
    }).catch( function(e) {
        console.error(e);
    });
    
    async function convertHelper(document, exportFct) {
        const api = await docx.engine();
        await api.load(document);
        const arrayBuffer = await api[exportFct]();
        await api.close();
        return arrayBuffer;
    }
    
    convertHelper("sample.docx", "exportPDF").then((arrayBuffer) => {
        fs.writeFileSync("sample.pdf", new Uint8Array(arrayBuffer));
    }).catch((e) => {
        console.error(e);
    });
    

    从上面可以看到,您需要一个API密钥(它的freemium模型)。披露:我对此有兴趣。