我有一个 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。有没有更好的方法可以避免这一切。
最佳答案
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 key (其免费增值模式)。披露:我对此感兴趣。
关于javascript - 将 Node.js 文档缓冲区转换为 pdf 文件以将其输出到客户端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53369102/