猿问

如何使用 Apache POI 在 Word 文档中定义窄边距?

我正在使用 Apache POI 创建一个 docx 文档,并且我希望将边距设置为缩小,就像在 MS Word 中使用“布局”>“边距”>“缩小”一样。


我已经看到其他一些建议 RecordInputStream 的答案,但我不知道如何将它集成到我的代码中,因为它使用 FileInputStream 作为参数。


我使用 ByteArrayOutputStream 是因为我正在使用 omnifaces 导出它,并且我想要一种使其工作的方法。


这是我的代码:


ByteArrayOutputStream output = new ByteArrayOutputStream();

XWPFDocument document = new XWPFDocument();

XWPFParagraph titleParagraph = document.createParagraph();

//some code here...

document.write(output);

document.close();    

Faces.sendFile(output.toByteArray(), wordFilename, true);

请帮忙。提前致谢!


largeQ
浏览 398回答 1
1回答

青春有我

到目前为止,XWPFDocument 中没有设置页边距的内容。所以我们需要使用低级 beanorg.openxmlformats.schemas.wordprocessingml.x2006.main.CTSectPr和org.openxmlformats.schemas.wordprocessingml.x2006.main.CTPageMar.什么word叫窄利润率为0.5英寸利润率各地。import java.io.FileOutputStream;import org.apache.poi.xwpf.usermodel.*;import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSectPr;import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTPageMar;import java.math.BigInteger;public class CreateWordPageMargins { public static void main(String[] args) throws Exception {  XWPFDocument document = new XWPFDocument();  XWPFParagraph paragraph = document.createParagraph();  XWPFRun run = paragraph.createRun();    run.setText("Text");  CTSectPr sectPr = document.getDocument().getBody().getSectPr();  if (sectPr == null) sectPr = document.getDocument().getBody().addNewSectPr();  CTPageMar pageMar = sectPr.getPgMar();  if (pageMar == null) pageMar = sectPr.addNewPgMar();  pageMar.setLeft(BigInteger.valueOf(720)); //720 TWentieths of an Inch Point (Twips) = 720/20 = 36 pt = 36/72 = 0.5"  pageMar.setRight(BigInteger.valueOf(720));  pageMar.setTop(BigInteger.valueOf(720));  pageMar.setBottom(BigInteger.valueOf(720));  pageMar.setFooter(BigInteger.valueOf(720));  pageMar.setHeader(BigInteger.valueOf(720));  pageMar.setGutter(BigInteger.valueOf(0));  FileOutputStream out = new FileOutputStream("CreateWordPageMargins.docx");  document.write(out);  out.close();  document.close(); }}
随时随地看视频慕课网APP

相关分类

Java
我要回答