操作aspose版本
aspose-words-21.4
官网下载地址
https://releases.aspose.com/words/java/
问题
1,每次操作文档的时候都要重新保存,不然文件损坏,打开的文件就是乱码的
记录一些简单的功能设置:
Document doc = new Document();
//设置表格超过页面边距,看不到数据,为兼容模式
doc.getCompatibilityOptions().optimizeFor(MsWordVersion.WORD_2019);
DocumentBuilder builder = new DocumentBuilder(doc);
builder.insertHtml(readHTML("D:\\1.html", StandardCharsets.UTF_8));
//获取所有的段落
for (Section section : doc.getSections()) {
Body body = section.getBody();
for (Paragraph paragraph : body.getParagraphs()) {
double firstLineIndent = paragraph.getParagraphFormat().getFirstLineIndent();
if (!paragraph.getParagraphFormat().isHeading() && firstLineIndent > 0.0) {
//设置首行 为2字符
paragraph.getParagraphFormat().setCharacterUnitFirstLineIndent(2);
}
}
}
//获取所有图片
NodeCollection<Shape> shapes = (NodeCollection<Shape>) doc.getChildNodes(NodeType.SHAPE, true);
for (Shape shape : shapes)
{
if (shape.hasImage())
{
Paragraph paragraph = (Paragraph)shape.getAncestor(NodeType.PARAGRAPH);
if (paragraph != null)
{
//设置无首行缩进
paragraph.getParagraphFormat().setFirstLineIndent(0);
}
}
}
doc.save("D:\\钻井地质设计2.doc",SaveOptions.createSaveOptions(SaveFormat.DOC));
public static String readHTML(String path, Charset utf8) throws Exception {
StringBuilder sb = new StringBuilder();
File file = new File(path);
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
sb.append(line);
}
br.close();
return sb.toString();
}
取消表单重复标题代码
Document doc = new Document("cs2.doc");
for (Table t : (Iterable<Table>)doc.getChildNodes(NodeType.TABLE, true)) {
for (Row r : t.getRows()) {
r.getRowFormat().setHeadingFormat(false);
}
}
doc.save("out.doc");
设目录字体,行距为固定值20
ParagraphCollection firstParagraph = doc.getSections().get(1).getBody().getParagraphs();
for (Paragraph param:firstParagraph){
for (Run r :param.getRuns()){
if (!r.getText().contains("目录")){
r.getParentParagraph().getParagraphFormat().setLineSpacingRule( LineSpacingRule.EXACTLY);
r.getParentParagraph().getParagraphFormat().setLineSpacing( 20);
r.getFont().setName("宋体");
}
}
}