LaTeX to PDF | Python

Converting LaTeX to PDF

Now, let’s examine the Python code that offers the most straightforward approach to converting LaTeX to PDF 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 PDF.
 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.pdf import PdfDevice, PdfSaveOptions
 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 = PdfSaveOptions()
22device = PdfDevice()
23job_result = TeXJob(str(input_file), device, options).run()

To begin, we need to create an instance of the TeXOptions class. The console_app_options() method is the only static method that accomplishes this, so don’t worry about its name. This method takes an object_latex instance of the TeXConfig class, which is perfect for converting a LaTeX file. This configuration instructs the Object TeX engine to load the Object LaTeX format and be prepared to process the LaTeX file. The Object LaTeX format is essentially the same as the LaTeX format, but it utilizes Object TeX specific primitives to define the page metrics.

The first option that needs to be specified is output_working_directory, which determines the location where the TeX output will be saved. If needed, you can find more information on the concept of the output directory in Aspose.TeX. In this particular case, we utilize the OutputFileSystemDirectory class, which enables us to write the output to a designated directory or folder.

The second option requires an instance of the SaveOptions class, which determines how the object model is transformed into the desired format. In our case, as we are converting LaTeX to PDF, it refers to an instance of the PdfSaveOptions class.

To convert a LaTeX file stored in the file system, we need to create an instance of the TeXJob class using the constructor that takes the file’s full path as a parameter. If we don’t specify the full path, the engine will look for the file in the current directory (which is the script’s working directory) and may not find it. However, we can omit the extension if our file has the .tex extension, as the engine will automatically append it. The second argument of the constructor is an instance of the Device class. In our case, since we are converting LaTeX to PDF, it’s an instance of the PdfDevice class. Finally, we pass the recently 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.pdf (1 page).
13Transcript written on hello-world.log.

In the folder we specified as the output directory, we will find the transcript file and, here it is!, the main output PDF file, among other results of the engine’s work.

An alternative way to write the main output PDF file

The PdfDevice class has another constructor that allows us to obtain the resulting PDF file differently.

 1# Convert LaTeX to PDF using an explicitly named binary output stream.
 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.pdf import PdfDevice, PdfSaveOptions
 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 = PdfSaveOptions()
22
23# Supply a binary stream to choose the output filename.
24with (output_dir / "any-name.pdf").open("wb") as output_stream:
25    device = PdfDevice(output_stream)
26    job_result = TeXJob(str(input_file), device, options).run()

The binary stream writes any-name.pdf into the configured output directory. The device does not create an additional default-named PDF; auxiliary files and the transcript still go to output_working_directory.

About input options

If our main input file requires dependencies, such as packages that are not included in the basic LaTeX system and supported packages, it is necessary to set the required_input_directory option in a similar way as we set the output_working_directory option and place the dependencies in that directory. The dependencies can be organized in subdirectories as desired. Additionally, if we have our own files to include in the typesetting process, such as external graphics files, we must also set the input_working_directory using the path to the location where those files are stored. We can also place the main input file inside 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. For more details about the input directory concept in Aspose.TeX for Python and the provided implementations, please refer to here.

There are also other TeX job options discussed.

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