LaTeX to image | Python

Aspose.TeX for Python provides us with the capability to convert LaTeX files into various raster image formats.

Converting LaTeX to PNG

Now, let’s examine the Python code that offers the most straightforward approach to converting LaTeX to PNG format in depth.

Set ASPOSE_TEX_INPUT_FILE to your LaTeX file and ASPOSE_TEX_OUTPUT_DIR to the output directory, or edit the paths in the example. The defaults are hello-world.ltx and output. Apply a license first as described in Licensing. The examples resolve additional input files beside the main document and use noninteractive processing.

 1# Convert LaTeX to PNG.
 2import os
 3from pathlib import Path
 4from aspose.tex import Interaction, TeXConfig, TeXJob, TeXOptions
 5from aspose.tex.io import InputFileSystemDirectory, OutputFileSystemDirectory, OutputMemoryTerminal
 6from aspose.tex.presentation.image import ImageDevice, PngSaveOptions
 7
 8# Set these paths to your LaTeX document and output directory.
 9input_file = Path(os.environ.get("ASPOSE_TEX_INPUT_FILE", "hello-world.ltx")).resolve()
10output_dir = Path(os.environ.get("ASPOSE_TEX_OUTPUT_DIR", "output")).resolve()
11if not input_file.is_file():
12    raise FileNotFoundError(input_file)
13output_dir.mkdir(parents=True, exist_ok=True)
14
15# Use the Object LaTeX format and resolve additional inputs beside the main file.
16options = TeXOptions.console_app_options(TeXConfig.object_latex)
17options.input_working_directory = InputFileSystemDirectory(str(input_file.parent))
18options.output_working_directory = OutputFileSystemDirectory(str(output_dir))
19options.interaction = Interaction.NONSTOP_MODE
20options.terminal_out = OutputMemoryTerminal()
21options.save_options = PngSaveOptions()
22device = ImageDevice(True)
23job_result = TeXJob(str(input_file), device, options).run()

To start with, we need to create an instance of the TeXOptions class using the console_app_options() method. Don’t worry about the name, it’s just the static method that creates the instance. This method takes the object_latex instance of the TeXConfig class, which is perfect for converting a LaTeX file. This configuration sets up the Object TeX engine to load the Object LaTeX format and be ready to process the LaTeX file. The Object LaTeX format is essentially the same as the LaTeX format, but it uses Object TeX specific primitives to define the page metrics.

The first of the necessary options is output_working_directory, which specifies the location where the TeX output will be saved. If interested, you can learn more information about the concept of the output directory in Aspose.TeX for Python. In this particular example, we utilize the OutputFileSystemDirectory class to write the output to a specific directory or folder.

The second option is an instance of the SaveOptions class, which is responsible for managing the conversion from the object model to the desired format. In this case, since we are converting LaTeX to PNG, we use the PngSaveOptions class instance, which allows us to specify the resolution of the output images.

Next, we create an instance of the TeXJob class. In this case, since we want to convert a LaTeX file stored in the file system, we use this version of the constructor . We need to provide the full path to the file, otherwise, the engine will look for it in the current directory (which is the script’s working directory) and may not find it. However, the .tex extension can be omitted as the engine will automatically append it. The second argument of the constructor is an instance of the Device class. Since we are converting LaTeX to PNG, it’s an ImageDevice class instance, which is common to all supported image formats. Finally, we pass the prepared conversion options as the last argument.

Now, all that remains is to run the job.

The example captures terminal output in OutputMemoryTerminal rather than printing it to the console. The output directory also contains a .log transcript. A successful conversion produces a transcript similar to this (version details may differ):

 1This is ObjectTeX, Version 3.1415926-1.0 (Aspose.TeX 21.8)
 2entering extended mode
 3
 4(<input_directory>\hello-world.ltx
 5LaTeX2e <2011/06/27>
 6(article.cls
 7Document Class: article 2007/10/19 v1.4h Standard LaTeX document class
 8(size10.clo))
 9No file hello-world.aux.
10[1]
11(<output_directory>\hello-world.aux) )
12Output written on hello-world.png (1 page).
13Transcript written on hello-world.log.

The results of the engine’s work can be found in the output directory that we specified. This will include the transcript file and, most importantly, the main output PNG image file(s).

An alternative way to write the main output PNG file(s)

There is an alternative method to obtain image data as an array of byte arrays, where each array in the second dimension represents the image data for a separate page.

 1# Convert LaTeX to PNG and save each page from the returned byte arrays.
 2import os
 3from pathlib import Path
 4from aspose.tex import Interaction, TeXConfig, TeXJob, TeXOptions
 5from aspose.tex.io import InputFileSystemDirectory, OutputFileSystemDirectory, OutputMemoryTerminal
 6from aspose.tex.presentation.image import ImageDevice, PngSaveOptions
 7
 8# Set these paths to your LaTeX document and output directory.
 9input_file = Path(os.environ.get("ASPOSE_TEX_INPUT_FILE", "hello-world.ltx")).resolve()
10output_dir = Path(os.environ.get("ASPOSE_TEX_OUTPUT_DIR", "output")).resolve()
11if not input_file.is_file():
12    raise FileNotFoundError(input_file)
13output_dir.mkdir(parents=True, exist_ok=True)
14
15# Use the Object LaTeX format and resolve additional inputs beside the main file.
16options = TeXOptions.console_app_options(TeXConfig.object_latex)
17options.input_working_directory = InputFileSystemDirectory(str(input_file.parent))
18options.output_working_directory = OutputFileSystemDirectory(str(output_dir))
19options.interaction = Interaction.NONSTOP_MODE
20options.terminal_out = OutputMemoryTerminal()
21save_options = PngSaveOptions()
22save_options.device_writes_images = False
23options.save_options = save_options
24device = ImageDevice(True)
25job_result = TeXJob(str(input_file), device, options).run()
26
27# Write the returned PNG page bytes yourself.
28for index, page_bytes in enumerate(device.result, start=1):
29    (output_dir / f"page-{index}.png").write_bytes(page_bytes)

The example sets device_writes_images = False on PngSaveOptions before assigning it to options.save_options. It writes the returned page bytes as page-1.png, page-2.png, and so on. The device therefore does not create duplicate PNG files.

Regarding input options

If our main input file requires dependencies, such as packages that are not included in the basic LaTeX system or supported packages, we need to set the required_input_directory option in a similar way to how we set the output_working_directory option and place the dependencies in that directory. The dependencies can be organized in subdirectories as needed. If we have our files to include in the typesetting process, such as external graphics files, we also need to set the input_working_directory to the location where those files are stored. We can also place the main input file within the input directory and pass the relative path to the TeXJob constructor, or specify no path at all if the main input file is in the root directory. There are also more details about the input directory concept in Aspose.TeX and the provided implementations described.

Also learn the other TeX job options here.

You can also explore the free web app for LaTeX-to-PNG conversion, which is developed using the Aspose.TeX for .NET API.

Below, we will briefly explain the conversion of LaTeX to other supported raster image formats, without diving into too much detail as there are no significant differences. The only variation lies in the type of the save_options property in the conversion options.

Converting LaTeX to JPG

 1# Convert LaTeX to JPEG.
 2import os
 3from pathlib import Path
 4from aspose.tex import Interaction, TeXConfig, TeXJob, TeXOptions
 5from aspose.tex.io import InputFileSystemDirectory, OutputFileSystemDirectory, OutputMemoryTerminal
 6from aspose.tex.presentation.image import ImageDevice, JpegSaveOptions
 7
 8# Set these paths to your LaTeX document and output directory.
 9input_file = Path(os.environ.get("ASPOSE_TEX_INPUT_FILE", "hello-world.ltx")).resolve()
10output_dir = Path(os.environ.get("ASPOSE_TEX_OUTPUT_DIR", "output")).resolve()
11if not input_file.is_file():
12    raise FileNotFoundError(input_file)
13output_dir.mkdir(parents=True, exist_ok=True)
14
15# Use the Object LaTeX format and resolve additional inputs beside the main file.
16options = TeXOptions.console_app_options(TeXConfig.object_latex)
17options.input_working_directory = InputFileSystemDirectory(str(input_file.parent))
18options.output_working_directory = OutputFileSystemDirectory(str(output_dir))
19options.interaction = Interaction.NONSTOP_MODE
20options.terminal_out = OutputMemoryTerminal()
21options.save_options = JpegSaveOptions()
22device = ImageDevice(True)
23job_result = TeXJob(str(input_file), device, options).run()

You can also explore the free web app for LaTeX-to-JPG conversion, which is developed using the Aspose.TeX for .NET API.

Converting LaTeX to TIFF

 1# Convert LaTeX to TIFF.
 2import os
 3from pathlib import Path
 4from aspose.tex import Interaction, TeXConfig, TeXJob, TeXOptions
 5from aspose.tex.io import InputFileSystemDirectory, OutputFileSystemDirectory, OutputMemoryTerminal
 6from aspose.tex.presentation.image import ImageDevice, TiffSaveOptions
 7
 8# Set these paths to your LaTeX document and output directory.
 9input_file = Path(os.environ.get("ASPOSE_TEX_INPUT_FILE", "hello-world.ltx")).resolve()
10output_dir = Path(os.environ.get("ASPOSE_TEX_OUTPUT_DIR", "output")).resolve()
11if not input_file.is_file():
12    raise FileNotFoundError(input_file)
13output_dir.mkdir(parents=True, exist_ok=True)
14
15# Use the Object LaTeX format and resolve additional inputs beside the main file.
16options = TeXOptions.console_app_options(TeXConfig.object_latex)
17options.input_working_directory = InputFileSystemDirectory(str(input_file.parent))
18options.output_working_directory = OutputFileSystemDirectory(str(output_dir))
19options.interaction = Interaction.NONSTOP_MODE
20options.terminal_out = OutputMemoryTerminal()
21options.save_options = TiffSaveOptions()
22device = ImageDevice(True)
23job_result = TeXJob(str(input_file), device, options).run()

You can also explore the free web app for LaTeX-to-TIFF conversion, which is developed using the Aspose.TeX for .NET API.

Converting LaTeX to BMP

 1# Convert LaTeX to BMP.
 2import os
 3from pathlib import Path
 4from aspose.tex import Interaction, TeXConfig, TeXJob, TeXOptions
 5from aspose.tex.io import InputFileSystemDirectory, OutputFileSystemDirectory, OutputMemoryTerminal
 6from aspose.tex.presentation.image import ImageDevice, BmpSaveOptions
 7
 8# Set these paths to your LaTeX document and output directory.
 9input_file = Path(os.environ.get("ASPOSE_TEX_INPUT_FILE", "hello-world.ltx")).resolve()
10output_dir = Path(os.environ.get("ASPOSE_TEX_OUTPUT_DIR", "output")).resolve()
11if not input_file.is_file():
12    raise FileNotFoundError(input_file)
13output_dir.mkdir(parents=True, exist_ok=True)
14
15# Use the Object LaTeX format and resolve additional inputs beside the main file.
16options = TeXOptions.console_app_options(TeXConfig.object_latex)
17options.input_working_directory = InputFileSystemDirectory(str(input_file.parent))
18options.output_working_directory = OutputFileSystemDirectory(str(output_dir))
19options.interaction = Interaction.NONSTOP_MODE
20options.terminal_out = OutputMemoryTerminal()
21options.save_options = BmpSaveOptions()
22device = ImageDevice(True)
23job_result = TeXJob(str(input_file), device, options).run()

You can also explore the free web app for LaTeX-to-BMP conversion, which is developed using the Aspose.TeX for .NET API.

Converting LaTeX to SVG

Another supported target format is SVG. Scalable Vector Graphics (SVG) is an XML-based vector image format that is used to define two-dimensional graphics. It supports interactivity and animation.

SVG images are stored in XML text files and defined in a vector graphics format. This means that SVG images can be scaled in size without losing quality, and SVG files themselves can be searched, indexed, scripted, and compressed. The XML text files can be created and edited using text editors or vector graphics editors, and they can be rendered by the most commonly used web browsers.

The Aspose.SVG API offers a range of features for working with SVG, such as creating, loading, editing, and converting SVG documents.

Converting LaTeX to SVG is just as straightforward as converting to raster image formats, with the only difference being that the save_options must be set to an instance of the SvgSaveOptions class and the device must be changed to an instance of the SvgDevice class.

 1# Convert LaTeX to SVG.
 2import os
 3from pathlib import Path
 4from aspose.tex import Interaction, TeXConfig, TeXJob, TeXOptions
 5from aspose.tex.io import InputFileSystemDirectory, OutputFileSystemDirectory, OutputMemoryTerminal
 6from aspose.tex.presentation.svg import SvgDevice, SvgSaveOptions
 7
 8# Set these paths to your LaTeX document and output directory.
 9input_file = Path(os.environ.get("ASPOSE_TEX_INPUT_FILE", "hello-world.ltx")).resolve()
10output_dir = Path(os.environ.get("ASPOSE_TEX_OUTPUT_DIR", "output")).resolve()
11if not input_file.is_file():
12    raise FileNotFoundError(input_file)
13output_dir.mkdir(parents=True, exist_ok=True)
14
15# Use the Object LaTeX format and resolve additional inputs beside the main file.
16options = TeXOptions.console_app_options(TeXConfig.object_latex)
17options.input_working_directory = InputFileSystemDirectory(str(input_file.parent))
18options.output_working_directory = OutputFileSystemDirectory(str(output_dir))
19options.interaction = Interaction.NONSTOP_MODE
20options.terminal_out = OutputMemoryTerminal()
21options.save_options = SvgSaveOptions()
22device = SvgDevice()
23job_result = TeXJob(str(input_file), device, options).run()

You can also explore the free web app for LaTeX-to-SVG conversion, which is developed using the Aspose.TeX for .NET API.