使用Python写latex:pylatex的简单使用

文章目录

  • Latex简述
    • 常用latex包简介
      • fontenc
      • cjk
      • graphics
    • Latex文档结构
      • 命令
      • 文档类声明
      • 环境
      • 序言
      • 正文
      • Floats
  • PyLaTex简述
    • 项目相关
  • PyLatex入门
      • 导入相关包
      • 创建文档实例
      • 添加包
      • 添加其他序言
      • 创建章节的两种方式
        • 使用with
        • 直接添加
      • 使用命令的两种方式
        • Command
        • NoEscape
      • 使用环境
      • 创建命令和环境
        • 创建命令
          • 在文档中手动添加方法声明
          • 建立类(可选)
          • 使用命令
      • 创建环境
      • 导出
        • 返回字符串
        • 导出tex文件到本地
        • 直接生成pdf文件
  • PyLatex高级使用

Latex简述

Latex是一个专业论文制作工具,在国外,大多高水平的论文都使用Latex对论文进行排版。Latex以其页面的美观整洁,以及功能的强大受到国际专家学者的重视。

常用latex包简介

所有的常用latex包的简介和使用范例,查看:http://www.latexstudio.net/hulatex/package/font.htm

fontenc

在 LaTeX 中,默认字体是按 OT1 编码的计算机现代字体,它不包含欧洲重音字符,因此也无法对欧洲文字进行断词处理。

cjk

用于提供对中文的支持,最好选用xelatex方式编译,详细的设置方式查看 https://www.cnblogs.com/dezheng/p/3874434.html

graphics

用来添加对图片的支持,其中如果一个位置要插入多张图片,则subfigure包可以很好的提供支持

Latex文档结构

命令

\newcommand{commandname}[params num][default]{content #1 #2...}定义
使用方式:

\name{content}{}...

文档类声明

用来指明文档类型,常用的类型有三种,分别是article,report,book,命令的一种

\documentclass{article}

环境

\newenvironment{environmentname}[params num]{left #i}{right #j}定义,使用方式:

\begin{name}{param1}{p2}
...
\end{name}

关于如何定义环境和命令,参考 https://en.wikibooks.org/wiki/LaTeX/Macros

序言

放在文档类声明后的一些命令,用于完成一些特殊任务,如引入宏包,环境,变量,如

\usepackage{subfigure}
\title{A title}

正文

顾名思义,由document环境包裹,也是环境的一种

\begin{document} %正文
...
\end{document}

Floats

Floats是一种特殊环境,Floats环境中内容必须被放置在一个单页中,而不能被拆分为多页,如Table或者Figure,他们可以被认为是Floats的一个子类,关于其更多的介绍参考:https://www.overleaf.com/learn/latex/Positioning_of_Figures

要注意的是,tabular可以拿出来单独活动,tabular本身不是Floats环境,会浮动的只是Table及其内的内容,如果tabular单独使用,则不会产生浮动

PyLaTex简述

PyLaTeX是使用Python语法产生LaTex文档的函数库,安装方式:

pip install pylatex

项目相关

github主页: https://github.com/JelteF/PyLaTeX/tree/master/docs

API文档: https://jeltef.github.io/PyLaTeX/

PyLatex入门

导入相关包

一般需要用到的对象均在pylatex包中,另外pylatex.utils和pylatex.base_classes中还有一些常用包,会在之后逐一使用到

from pylatex import Document, Section, Subsection, Command,Package
from pylatex.utils import italic, NoEscape

创建文档实例

doc = Document(default_filepath='basic',
              documentclass='article')

添加包

包或者序言在添加的时候都会自动排重

doc.packages.append(Package("graph1"))
5

添加其他序言

包不可以在这里添加,因为序言不会查重,重复导包会报错

doc.preamble.append(Command('date'))

创建章节的两种方式

使用with

这种方式可以用缩进的方式确保要添加的内容在文档里

with doc.create(Section('A second section')):
    doc.append('Some text.')

直接添加

doc.append(Section("B"))
doc.append("some in B")

使用命令的两种方式

Command

doc.append(Command("commandName",arguments={'a':1.2},options="options",extra_arguments="extra",packages=[Package("graph")]))

只有第一个命令名是必选参数,其余是可选参数

其中,argument/extra_arguments/options支持数字,字符串,list,甚至是map,非常方便,packages必须为可迭代对象,且每一个元素必须是Package实例

NoEscape

doc.append()中直接添加字符串,其中的\{}[]等会被转义,因此我们如果想直接添加命令是不可行的,但也不是不可以,方法就是NoEscape对象

doc.append(NoEscape(r'\commandname[]...{}'))#Python 中,字符串前加r表示raw string,不用对其中的斜杠等进行转义

使用环境

以插入两个子图为例

from pylatex import Figure,SubFigure
image_filename = "path+name"

with doc.create(Figure(position='h!')) as kittens:
    with doc.create(SubFigure(
            position='b',
            width=NoEscape(r'0.45\linewidth'))) as left_kitten:

        left_kitten.add_image(image_filename,
                              width=NoEscape(r'\linewidth'))
        left_kitten.add_caption('Kitten on the left')
    with doc.create(SubFigure(
            position='b',
            width=NoEscape(r'0.45\linewidth'))) as right_kitten:

        right_kitten.add_image(image_filename,
                               width=NoEscape(r'\linewidth'))
        right_kitten.add_caption('Kitten on the right')
    kittens.add_caption("Two kittens")

以插入一个表格为例

from pylatex import Tabular
with doc.create(Tabular('rc|cl')) as table:
    table.add_hline()
    table.add_row((1, 2, 3, 4))
    table.add_hline(1, 2)
    table.add_empty_row()
    table.add_row((4, 5, 6, 7))

创建命令和环境

创建命令

创建命令稍微有一些复杂,如果想要在doc.append()中直接用自己实现的命令的类的话,就需要实现CommandBase的子类,当然如果需要实现的子类不需要任何的额外包的话,其实是可以通过NoEscape类将定义的命令添加到doc.preamble中并用Command()使用,因此非复杂命令还是可以稍微简单一点的

在文档中手动添加方法声明
from pylatex import UnsafeCommand
new_comm = UnsafeCommand('newcommand'#必填项
                         '\exampleCommand'
                         ,3
                         ,r'content#1 #2 #3'
                         ,packages=[]#这里添加使用该条命令依赖的包,
                        )
doc.append(new_comm)

这句话相当于

\newcommand{\exampleCommand[3]{content#1 #2 #3}}
建立类(可选)
from pylatex.base_classes import CommandBase
class ExampleCommand(CommandBase):
    _latex_name = 'exampleCommand'
    packages = [Package('color')]#这里声明需要的包
    #可以通过重写初始化函数来设置默认参数
使用命令
from pylatex.base_classes import Arguments
doc.append(NoEscape(r"\exampleCommand{1}{2}{3}")) #如果没有声明类
doc.append(ExampleCommand(Arguments(1,2,3)))#如果有声明相应类
doc.append(ExampleCommand([1,2,3]))#等价于第二条语句

创建环境

基本和创建命令一样,但由于环境在内容上下侧都有,所以一般创建类较为方便

from pylatex.base_classes import Environment
class ExampleEnvironment(Environment):
    """
    A class representing a custom LaTeX environment.

    This class represents a custom LaTeX environment named
    ``exampleEnvironment``.
    """

    _latex_name = 'exampleEnvironment'
    packages = []
new_env = UnsafeCommand('newenvironment', 'exampleEnvironment'
                        ,options=2
                        ,extra_arguments=[
                                r'left content',#left
                                r'right content'])#right
doc.append(new_env)
with doc.create(ExampleEnvironment(arguments=Arguments('red', 3))) as environment:
        environment.append('This is the actual content')

导出

返回字符串

doc.dumps()

导出tex文件到本地

doc.generate_tex()

直接生成pdf文件

doc.generate_pdf(filepath="path")#如果出错,如缺少包会报错

PyLatex高级使用

如果PyLatex只是这样按部就班的生成文档,那么其实也就只是方便了一点,PyLatex最好的地方是,可以基于matplotlib和numpy等,直接生成公式,图片

to be continue...

你可能感兴趣的:(python)