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
里边有收费版和免费版,咱们使用免费版的就足够了。
先安装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))  
 

都是我自己项目中验证过的,请放心使用

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值