我有两个文件:doc1.docx 和 doc2.docx
有谁知道如何以编程方式将 doc2 附加到 doc1 的末尾?假设 doc1 是模板首页,doc2 是数据页。因此,最终产品应该是 mergeddoc.docx ,它看起来像 doc1 然后是 doc2 又名第 1 页上的首页和第 2 页上的数据页。在 word 中,我猜你会使用插入工具添加到文档中。
我觉得这应该不难,但我已经为这个问题绞尽脑汁大约三天了。如果这是一个难题,有人知道解决方法吗?我知道你可以用 python 做这样的事情但是这是最好的解决方案吗?
谢谢!我尝试使用.docx,但它没有合并功能 “docx-merger”基本上不受支持并且已经过时 - 除非我丢失了某些东西,否则不会运行此功能 docx-templates 对我不起作用,也没有功能。
之前尝试的示例不起作用:
const fs = require("fs");
const path = require("path");
const os = require("os");
const createReport = require("docx-templates").default;
const saveDocument = (buffer, patientData) => {
try {
const downloadsPath = path.join(os.homedir(), "Downloads");
const filename = `Report_${patientData.forename}_${
patientData.surname
}_${Date.now()}.docx`;
const filePath = path.join(downloadsPath, filename);
fs.writeFileSync(filePath, buffer);
return filePath;
} catch (error) {
console.error("Error in saveDocument:", error);
throw error;
}
};
const generateDocument = async (data) => {
try {
console.log("Starting document generation...");
const selectedGenes = data.selectedGenes;
const geneData = data.geneData;
const bloodResults = {
testDetails: {
lab: data.bloodsDetails.sendingApplication,
receivedInLab: data.bloodsDetails.receivingFacility,
patientId: data.bloodPatientID,
},
results: data.bloodResults,
};
const basicData = {
patientData: data.patientData,
clinician: data.clinicianIdentity,
};
const complaints = data.patientComplaints;
const utilsData = {
time: data.time,
geneCount: data.selectedGenes.length,
countBloodTests: data.bloodResults.length,
};
console.log("Data prepared:", {
selectedGenes,
geneData,
bloodResults,
basicData,
complaints,
utilsData,
});
const templatePath = path.join(
__dirname,
"../templates/base_template.docx"
);
if (!fs.existsSync(templatePath)) {
throw new Error(`Template file not found at path: ${templatePath}`);
}
console.log(`Base template found at ${templatePath}`);
const template = fs.readFileSync(templatePath);
const dataForTemplate = {
selectedGenes: [],
geneData,
bloodResults,
basicData,
complaints,
utilsData,
};
for (const gene of selectedGenes) {
const geneName = gene.geneName;
console.log(`Processing gene: ${geneName}`);
const geneTemplatePath = path.join(
__dirname,
"../templates/gene_templates",
`${geneName}.docx`
);
if (!fs.existsSync(geneTemplatePath)) {
throw new Error(
`Gene template file not found for gene ${geneName} at path: ${geneTemplatePath}`
);
}
console.log(`Gene template found at ${geneTemplatePath}`);
const geneTemplateBuffer = fs.readFileSync(geneTemplatePath);
dataForTemplate.selectedGenes.push({
...gene,
genedoc: geneTemplateBuffer,
});
}
console.log("Data prepared for main template:", dataForTemplate);
// Generate the final report
const buffer = await createReport({
template,
data: dataForTemplate,
noSandbox: true,
additionalJsContext: {
INS: (buffer) => ({
_type: "rawXml",
xml: buffer.toString("utf8"),
}),
},
});
console.log("Final report generated.");
const filePath = saveDocument(buffer, data.patientData);
console.log(`Document saved at ${filePath}`);
return `Document generated successfully at ${filePath}`;
} catch (error) {
console.error("Error in generateDocument:", error);
return `Error in generateDocument: ${error.message}`;
}
};
module.exports = {
generateDocument,
};
if (require.main === module) {
(async () => {
try {
const data = {
selectedGenes: [
{ geneName: "COMT", rsCode: "rs6311", combined: "TC" },
],
geneData: {
COMT: { description: "Catechol-O-methyltransferase gene" },
},
bloodsDetails: {
sendingApplication: "Them",
receivingFacility: "Us",
},
bloodPatientID: "123-4567",
bloodResults: [
{
testCode: "HTR2A",
testName: "HTR2A Test",
value: "Positive",
units: "blahs",
referenceRange: "",
},
],
patientData: {
patientId: "123-4567",
title: "Mrs",
forename: "Jane",
surname: "Doe",
dob: "1999-01-01",
sex: "F",
},
clinicianIdentity: "Dr Who",
patientComplaints: [
"Decreased concentration",
"Decreased mental sharpness",
],
time: Date.now(),
};
const result = await generateDocument(data);
console.log(result);
} catch (error) {
console.error(
"Error running generateDocument from command line:",
error
);
}
})();
}
我看过其他答案:
如何在 Golang 中追加 docx 文件:错误的语言
使用 Node 的“Docx”通过 JS 附加到现有 Word 文档:解释了此特定包中的限制
如何使用docx包追加文件:同上。
要使用此方法,您需要安装Python并找到可执行文件的路径。 (例如
/usr/bin/python3
)您可以使用这个 Python 脚本(不要忘记使用
docxcompose
安装 python
pip install docxcompose
库): (./script.py)
from docxcompose.composer import Composer
from docx import Document
import sys
def main(argv):
argsCount = len(argv)
if argsCount < 2:
print("pass 2 filenames: input, output")
exit(1)
inputPaths = argv[0:argsCount - 1]
print("input paths:")
print(inputPaths)
outputPath = argv[argsCount - 1]
print("output path:")
print(outputPath)
master = False
composer = False
for inputPath in inputPaths:
if master == False:
master = Document(inputPath)
composer = Composer(master)
print("composer created")
else:
doc = Document(inputPath)
composer.append(doc)
master.save(outputPath)
exit(0)
if __name__ == "__main__":
main(sys.argv[1:])
还有这个js代码
(./main.js)
import * as childProcess from 'child_process';
import * as path from 'path';
const execCmd = `/usr/bin/python3 ${path.join(__dirname,'script.py')} path_to_doc1.docx path_to_doc2.docx result_file_name.docx`
childProcess.execSync(execCmd);
// here you can access result_file_name.docx and delete path_to_doc1.docx, path_to_doc2.docx if you need
如果您使用 node main.js
path_to_doc1.docx 运行此代码,path_to_doc2.docx 将合并到 result_file_name.docx。然后您可以将 python 和 docxcompose lib 安装添加到 dockerfile 并使用 docker 容器。