要更改docxjs中的默认文档边距,您需要首先了解docxjs文档结构以及如何创建自定义样式
const docx = require("docx");
const customMargins = {
top: docxPgMargin cmToInches(1), // 默认 1 英寸
bottom: docxPgMargin cmToInches(1),
left: docxPgMargin cmToInches(1.5), // 可根据需要更改
right: docxPgMargin cmToInches(1.5),
};
const customPageSize = {
size: docx.PageSize.A4,
orientation: docx.Orientation.PORTRAIT,
};
const doc = new docx.Document({
pagesize: customPageSize,
margins: customMargins,
});
const paragraph = new docx.Paragraph("Hello World!");
doc.addParagraph(paragraph);
// Save as DOCX
docx.Packer.toBuffer(doc).then((buffer) => {
fs.writeFileSync("MyDocument.docx", buffer);
});
// Save as PDF
docx.Packer.toBuffer(doc).then((buffer) => {
const pdf = require("pdfkit");
const writeStream = fs.createWriteStream("MyDocument.pdf");
const doc = new pdf();
doc.pipe(writeStream);
doc.addPage();
doc.fontSize(25).text("Hello World!", 0, 0);
doc.end();
});
以上示例中的cmToInches
函数将厘米转换为英寸,如果您需要将边距值从厘米转换为英寸,请使用以下辅助函数:
function cmToInches(cm) {
return cm / 2.54;
}
这样,您就可以根据需要自定义docxjs中的默认文档边距了。
领取专属 10元无门槛券
手把手带您无忧上云