您好。用aspose.word java 对word文件设置页眉,可以把文字设置进去,但word页眉的横线无法设置,查看了api也没有找到好的方法,只能设置文字下划线,但这并不能解决项目的需求。有其他更好的方法吗?谢谢~微信截图_20180806173708.png (21.5 KB)
谢谢你的询问。 请压缩并上传您的简单输入Word文档和期望的Word文档,以显示所需的输出,以供我们参考。 请使用MS Word创建预期的Word文档。 然后我们将通过使用Aspose.Words为您提供实现相同的代码。
请尝试使用以下代码:
public static boolean setWordHeaderAndFooter(String filePath, String headerData, Double size, String font) throws Exception {
File file = new File(filePath);
if (!file.isFile() || !file.exists()) {
return false;
}
String fileName = file.getName();
String name = fileName.substring(0, fileName.lastIndexOf("."));
String suffix = fileName.substring(fileName.lastIndexOf("."));
int lastIndexOf = filePath.lastIndexOf("\\");
String path = filePath.substring(0, lastIndexOf);
Document document = new Document(filePath);
DocumentBuilder builder = new DocumentBuilder(document);
// 如果原文档有页眉页码则先删除
SectionCollection sections = document.getSections();
for (Section section : sections) {
HeaderFooter header = section.getHeadersFooters().getByHeaderFooterType(HeaderFooterType.HEADER_PRIMARY);
if (header != null) {
header.remove();
}
HeaderFooter footer = section.getHeadersFooters().getByHeaderFooterType(HeaderFooterType.FOOTER_PRIMARY);
if (footer != null) {
footer.remove();
}
}
HeaderFooter header = new HeaderFooter(document, HeaderFooterType.HEADER_PRIMARY);
document.getFirstSection().getHeadersFooters().add(header);
Paragraph para = header.appendParagraph(headerData);
para.getParagraphFormat().setAlignment(ParagraphAlignment.RIGHT);
para.getParagraphFormat().setStyleName("Header");
document.save("D:\\temp\\180780\\2\\awjava-18.7.doc");
return true;
}
String headerData = "测试页眉测试页眉测试页眉";
String path = "D:\\Temp\\180780\\2\\input.doc";
setWordHeaderAndFooter(path,headerData,9.0,"仿宋_GB2312");
已经完美解决页面问题,非常感谢~!