Python和java如何给word添加页眉和页脚
页眉和页脚方法基本一致,我就演示一种即可,先说java的。java使用POI给word添加页眉是存在bug的,我试了好多次,没成功过。然后我使用的是e-iceblue提供的jar包,API链接:https://www.e-iceblue.cn/spiredocforjavatext/extract-text-and-images-from-word-in-java.html里边有收费版和免费版,咱
页眉和页脚方法基本一致,我就演示一种即可,先说java的。
java使用POI给word添加页眉是存在bug的,我试了好多次,没成功过。然后我使用的是e-iceblue提供的jar包,
API链接:https://www.e-iceblue.cn/spiredocforjavatext/extract-text-and-images-from-word-in-java.html
里边有收费版和免费版,咱们使用免费版的就足够了。
先安装jar包:
pom依赖:
<dependency>
<groupId>e-iceblue</groupId>
<artifactId>spire.doc.free</artifactId>
<version>2.7.3</version>
</dependency>
<repositories>
<repository>
<id>com.e-iceblue</id>
<name>e-iceblue</name>
<url>http://repo.e-iceblue.cn/repository/maven-public/</url>
</repository>
</repositories>
import com.spire.doc.*;
import com.spire.doc.Document;
import com.spire.doc.documents.Paragraph;
import com.spire.doc.documents.VerticalOrigin;
import com.spire.doc.fields.DocPicture;
//自定义方法来添加图片、文字页眉及页码
private void addHeaderFooter(String filePath){
Document document = new Document();
document.loadFromFile(filePath);
//获取第一个section
Section section = document.getSections().get(0);
HeaderFooter header = section.getHeadersFooters().getHeader();
//添加文字到页眉的段落
//添加段落到页眉
Paragraph headerParagraph = header.addParagraph();
DocPicture headerPicture = headerParagraph.appendPicture(logoPath);
headerPicture.setHorizontalAlignment(ShapeHorizontalAlignment.Left);
headerPicture.setVerticalOrigin(VerticalOrigin.Top_Margin_Area);
headerPicture.setVerticalAlignment(ShapeVerticalAlignment.Bottom);
// TextRange text = headerParagraph.appendText("中国铁道科学研究院集团有限公司");
// text.getCharacterFormat().setFontName("Arial");
// text.getCharacterFormat().setFontSize(10);
// text.getCharacterFormat().setItalic(true);
// headerParagraph.getFormat().setHorizontalAlignment(HorizontalAlignment.Center);
document.saveToFile(filePath, FileFormat.Docx);
log.info("---------------------添加页眉完成---------------------");
}
这是java的方法,下来看Python的方法:
Python生成word的方法可以参考我的另一篇博客:
https://blog.csdn.net/weixin_42209881/article/details/103146577
使用docx包,
from docx import Document
from docx.shared import Inches,Pt
from docx.oxml.ns import qn
doc = Document()
distance = Inches(0.7) #英寸
top_distance = Inches(1)
sec = doc.sections[0] # sections对应文档中的“节”
header = sec.header
header_paragraph = header.add_paragraph()
header_run = header_paragraph.add_run("")
header_run.add_picture(os.path.dirname(__file__)+"\\common\\logo.png",width=Inches(2.7))
都是我自己项目中验证过的,请放心使用
魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。
更多推荐

所有评论(0)