如何使用PyLaTeX调整PDF上边距、添加可动态修改的全局页眉
解决方案
核心改动说明
- 修复上边距过大:补充
geometry配置的top参数明确设置顶部边距,新增includehead=True参数让页眉占用空间算入顶部边距范围,避免页眉额外撑开顶部边距。 - 灵活配置页眉:封装页眉创建函数,可传入任意文本生成对应页面样式,需要切换练习页眉时只需调用函数生成新样式并应用即可。
完整可运行代码
from pylatex import Document, PageStyle, LineBreak, Section, Subsection, Math, Alignat, LargeText, Center, MediumText from pylatex.utils import bold, italic, NoEscape import re from sympy import * import sympy as sp # 封装自定义页眉生成函数,传入页眉文本即可生成对应页面样式 def create_custom_header(header_content): page_style = PageStyle(f"style_{header_content.replace(' ', '_')}", header_thickness=0.6) # 页眉内容居中加粗显示,可根据需要调整格式 with page_style.create(Center()): page_style.append(bold(MediumText(header_content))) return page_style TituloPDF="Ejercicio 001" archivotxt = "%s.txt"% TituloPDF texto = open(archivotxt,"w") x = sp.Symbol('x', real=True) y = sp.Symbol('y', real=True) MatrizCoef=[y-x*y+1-x,-x*y] g=0 texto.write("\\text{Para la ecuación diferencial:} \r") texto.write("\\left({%s}\\right)dy = \\left({%s}\\right)dx \r"%(sp.latex(MatrizCoef[0]),sp.latex(MatrizCoef[1]))) texto.close() class Math_LaTeX (): def __init__(self, doc): #---Inicializamos--- self.doc = doc #---De aqui sacamos las ecuaciones del archivo .txt--- equations = self.Read() #---Creamos el documento Latex--- self.Create(equations) #---Creamos el PDF--- self.doc.generate_pdf(filepath = TituloPDF, clean_tex = True, compiler = 'pdflatex') def Read(self): data = open(archivotxt, 'rt') equations = data.readlines() eqs = [] for eq in equations: eqs.append(' '.join([line.strip() for line in eq.strip().splitlines()])) return eqs def Create(self, equations): for eq in equations: with self.doc.create(Alignat(numbering = False, escape = False)) as math_eq: math_eq.append(eq) geometry_options = { "head": "0.5cm", "top": "1cm", # 明确设置顶部边距,可根据需要调整数值 "left": "0.5cm", "right": "0.5cm", "bottom": "2.5cm", "includehead": True # 页眉计入顶部边距范围,避免顶部边距过大 } doc = Document(geometry_options = geometry_options, inputenc = 'utf8') # 为当前练习添加页眉 current_exercise_header = create_custom_header("Ejercicio 001") doc.preamble.append(current_exercise_header) doc.change_document_style(current_exercise_header.name) # 如果后续需要切换新练习的页眉,取消注释以下代码修改内容即可 # new_exercise_header = create_custom_header("Ejercicio 002") # doc.preamble.append(new_exercise_header) # doc.change_document_style(new_exercise_header.name) Math_LaTeX(doc)
页眉修改方法
需要切换新练习/示例的页眉时,仅需调用create_custom_header函数传入新的页眉文本,再将生成的样式添加到文档序言并应用即可,后续所有页面都会自动使用新的页眉。
内容的提问来源于stack exchange,提问作者LoboFJP
相关产品推荐
相关产品推荐

