杰瑞科技汇

Sphinx如何用Python生成PDF?

Of course! Generating PDFs from Sphinx documentation is a very common and powerful workflow. It allows you to create professional-looking, offline-ready books, reports, or manuals.

Sphinx如何用Python生成PDF?-图1
(图片来源网络,侵删)

Here's a comprehensive guide covering the most common methods, from the simplest to the most advanced.

The Core Concept: ReStructuredText (reST) + Sphinx + a Builder

Sphinx doesn't create PDFs directly. Instead, it uses a "builder" to convert your reStructuredText (.rst) or Markdown (.md) source files into a final output format. For PDFs, the most common builders are:

  1. LaTeX (Recommended for best quality): This is the most powerful and traditional method. Sphinx converts your reST into a .tex file, which is then compiled into a PDF using a LaTeX distribution (like XeLaTeX or pdfLaTeX). This gives you precise control over typography, layout, and mathematical formulas.
  2. WeasyPrint (Simpler, no LaTeX needed): This builder converts your reST into HTML and then uses the WeasyPrint library to render that HTML into a PDF. It's easier to set up but offers less control over advanced formatting.

Method 1: The Recommended LaTeX Builder (for best quality)

This is the standard and most robust way to generate high-quality PDFs.

Step 1: Install Prerequisites

You need two things: Sphinx itself and a LaTeX distribution.

Sphinx如何用Python生成PDF?-图2
(图片来源网络,侵删)

A. Install Sphinx and the Sphinx extension

pip install sphinx
pip install sphinxcontrib-latex  # Provides the LaTeX builder

B. Install a LaTeX Distribution

This is the most common point of failure. You need a full LaTeX installation on your system.

  • Windows: MiKTeX (Recommended) or TeX Live
  • macOS: MacTeX (This is a large ~5GB download, but it's the easiest way to get everything). Alternatively, you can use Homebrew: brew install --cask mactex-no-installer
  • Linux (Debian/Ubuntu):
    sudo apt-get update
    sudo apt-get install texlive-latex-recommended texlive-fonts-recommended texlive-latex-extra latex-xcolor

    Note: You might need more packages depending on your theme and extensions (e.g., for fonts or math).

Step 2: Configure Your Sphinx Project

In your Sphinx project's conf.py file, you need to tell Sphinx to use the LaTeX builder.

  1. Set the html_theme (Optional but Recommended): The LaTeX builder often uses themes designed for HTML to get its styling. A popular choice is sphinx_rtd_theme.

    # conf.py
    html_theme = 'sphinx_rtd_theme'
    pip install sphinx_rtd_theme
  2. Configure the LaTeX Builder:

    # conf.py
    # -- General configuration ------------------------------------------------
    # Add any Sphinx extension module names here, as strings. They can be
    # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
    # ones.
    extensions = [
        'sphinxcontrib.latex', # <-- IMPORTANT
        # ... other extensions like 'sphinx.ext.mathjax'
    ]
    # The master toctree document.
    master_doc = 'index'
    # -- Options for LaTeX output ---------------------------------------------
    # Grouping the document tree into LaTeX files. List of tuples
    # (source start file, target name, title,
    #  author, documentclass [howto, manual, or own class]).
    latex_documents = [
        (master_doc, 'your_project_name.tex', 'Your Project Documentation',
         'Your Name', 'manual'),
    ]
    # Additional stuff for the LaTeX preamble.
    # latex_preamble = ''
    # Documents to append as an appendix to all manuals.
    # latex_appendices = []
    # If false, no module index is generated.
    # latex_domain_indices = True

Step 3: Build the PDF

Navigate to your Sphinx project's root directory (the one containing Makefile, conf.py, etc.) in your terminal and run:

# The -b flag specifies the builder
make latexpdf

You can also use the shorter alias:

make pdf

Sphinx will now:

  1. Parse your .rst files.
  2. Generate a build/latex/ directory containing a .tex file and other support files.
  3. Call a LaTeX compiler (like pdflatex or xelatex) to compile the .tex file.
  4. Place the final PDF in the build/latex/ directory, usually named your_project_name.pdf.

Method 2: The WeasyPrint Builder (Simpler, No LaTeX)

This method is great if you want to avoid the complexity of a LaTeX installation. It's based on HTML, so it works well with modern CSS.

Step 1: Install Prerequisites

You need Sphinx and the WeasyPrint library. Note: WeasyPrint has system dependencies (like Cairo, Pango, etc.).

pip install sphinx
pip install weasyprint

For System Dependencies (WeasyPrint):

  • Windows/macOS: The pip install is usually sufficient.
  • Linux (Debian/Ubuntu):
    sudo apt-get install build-essential python3-dev python3-pip python3-setuptools python3-wheel libpango-1.0-0 libharfbuzz0b libpangoft2-1.0-0 libjpeg-dev libcairo2-dev libgdk-pixbuf2.0-dev libpangocairo-1.0-0 libffi-dev shared-mime-info

Step 2: Configure Your Sphinx Project

In your conf.py, enable the WeasyPrint builder.

# conf.py
# -- General configuration ------------------------------------------------
extensions = [
    'sphinx_weasyprint', # <-- IMPORTANT
    # ... other extensions
]
# The master toctree document.
master_doc = 'index'
# -- Options for WeasyPrint output -----------------------------------------
# Grouping the document tree into PDF files.
# WeasyPrint can also generate a single PDF for the whole project.
weasyprint_documents = [
    (master_doc, 'your_project_name.pdf', 'Your Project Documentation'),
]

Step 3: Build the PDF

Use the weasyprint builder with the make command.

make -b weasyprint your_project_name.pdf

The final PDF will be created directly in your project's root directory.


Troubleshooting Common Issues

  • LaTeX Builder Fails:

    • Error: ! LaTeX Error: File 'xxx.sty' not found.
    • Cause: You are missing a LaTeX package.
    • Solution: Install the missing package using your LaTeX distribution's package manager (e.g., MiKTeX's Package Manager, or tlmgr install <package-name> on TeX Live).
    • Pro Tip: If you're using special fonts, you might need to configure fontspec in your conf.py and use XeLaTeX as the compiler. Set latex_engine = 'xelatex' in conf.py.
  • Images Missing in PDF:

    • Cause: The image path is relative to the .rst file, but LaTeX needs it relative to the build/latex/ directory.
    • Solution: Use the sphinx.ext.imgconverter extension. It will automatically convert images to a format LaTeX can use (like PDF or PNG) and place them correctly. Add it to your extensions in conf.py:
      extensions = [
          'sphinx.ext.imgconverter', # <-- Add this
          'sphinxcontrib.latex',
      ]
  • Table of Contents (ToC) is not generated:

    • Cause: LaTeX needs to run multiple passes to resolve cross-references for the ToC.
    • Solution: The make latexpdf command should handle this automatically by running pdflatex multiple times. If you are compiling manually, you need to run pdflatex your-file.tex at least three times.

Summary: Which Method to Choose?

Feature LaTeX Builder (make latexpdf) WeasyPrint Builder (make weasyprint)
Quality & Typography Excellent. Professional book quality. Good. Web-based, can be very good.
Setup Complexity High. Requires a full LaTeX installation. Low. Just pip install weasyprint.
Mathematical Formulas Best. Native support via amsmath, etc. Good. Relies on MathJax/KaTeX, which WeasyPrint renders well.
Fonts & Layout Full control. Access to all LaTeX fonts and packages. Limited. Based on HTML/CSS. Good for web fonts.
Use Case Academic papers, books, official documentation, precise control. Simple reports, user guides, when a quick PDF is needed without LaTeX hassle.

For most serious documentation projects, taking the time to set up the LaTeX builder is worth the effort for the superior quality and control it provides.

分享:
扫描分享到社交APP
上一篇
下一篇