Sphinx文档 - 如何在构建HTML时呈现动画GIF,但在构建latexpdf时呈现PNG?

4

正如标题所述,我正在使用sphinx-doc,并且我真的希望在构建输出为latexpdf时有条件地呈现静态PNG,而在为web构建时则为动画GIF。

理想情况下,希望能够在rst文件本身中以某种方式实现这一点...语义上:

如果构建器 == html: .. image: blah blah elif 构建器 == latexpdf: .. image: blah blah

2个回答

8

以下是针对图片的Sphinx文档

Sphinx extends the standard docutils behavior by allowing an asterisk for the extension:

.. image:: gnu.*

Sphinx then searches for all images matching the provided pattern and determines their type. Each builder then chooses the best image out of these candidates. For instance, if the file name gnu.* was given and two files gnu.pdf and gnu.png existed in the source tree, the LaTeX builder would choose the former, while the HTML builder would prefer the latter. Supported image types and choosing priority are defined at Available builders.

要为给定的构建器定制“最佳图像”顺序,请编辑您的conf.py,用您喜欢的supported_image_types顺序来覆盖StandaloneHTMLBuilder类。

from sphinx.builders.html import StandaloneHTMLBuilder
StandaloneHTMLBuilder.supported_image_types = [
    'image/svg+xml',
    'image/gif',
    'image/png',
    'image/jpeg'
]

我看到了,但如果我理解正确的话,HTML构建器将始终优先选择png图像而不是动画gif。或者我有什么误解吗? - Robert Neville
是的,刚刚验证了这一点...虽然这修复了latexpdf构建,但现在html构建不是我想要的方式。:( - Robert Neville
好的,我找到了解决方法...如果您编辑您的答案,我会将其标记为被接受的答案。我必须添加一些代码来猴子补丁我的conf.py文件中的StandaloneHTMLBuilder类,通过重新定义supported_image_types将image/gif放在image/png之前。 - Robert Neville
你提到了一个问题,但是没有提供明确的代码。这是我的猜测 supported_image_types = ['image/gif', 'image/svg+xml', 'image/png', 'image/jpeg'] - Steve Piercy
from sphinx.builders.html import StandaloneHTMLBuilder StandaloneHTMLBuilder.supported_image_types = [ 'image/svg+xml', 'image/gif', 'image/png', 'image/jpeg' ] - Robert Neville

3
如果对其他人有用的话,我选择了Steve Piercy非常有帮助的答案的一个变体,它试图使代码具有未来性并防止出现神秘的缺失图像。它使用相同的结构,但默认情况下将任何在StandaloneHTMLBuilder.supported_image_types中的项附加到我们提供的新集合中不存在的项目后面。我正在考虑如果Sphinx开始支持像HEIC图像这样的东西,或者其他新的标准出现,这将允许它们被无缝地集成。
new_supported_image_types = [
    'image/svg+xml',
    'image/gif',
    'image/png',
    'image/jpeg'
]

# construct it this way so that if Sphinx adds default support for additional images, such
# as HEIC, then what we do is add any of those to the end. We start with the ones
# we want to support in this order, then subtract them from the defaults to identify
# any remaining items that we append to the end of the list

additional_default_supported_images = list(set(StandaloneHTMLBuilder.supported_image_types) - set(new_supported_image_types))
StandaloneHTMLBuilder.supported_image_types = new_supported_image_types + additional_default_supported_images

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接