3. Producing images

There are multiple ways to produce high quality images from pdfs generated from LaTeX.
The methods below are focussed on pdf to png conversion.
The last method is the most efficient.
  1. manual saving using Adobe Acrobat Pro.

  2. in python via the subprocess module, or from the command line, both using ImageMagick.

  3. in python, via the wand module, which requires ImageMagick installation.

  4. in VSCode when building the pdf, via LaTeX Workshop extension, via a custom tool, a custom recipe calls a python script that uses ImageMagick.


3.1. Adobe Acrobat Pro

All pdfs produced as output from .tex files can be opened in Adobe Acrobat Pro.
From within Adobe Acrobat Pro, use either File: Save As or File Export.
Choose png as the file extension and click settings in the save dialog to choose 600 dpi for high quality results when the png is resized in Word.

3.2. ImageMagick

Image Magick can be used to convert pdfs to jpgs or pngs from the command line or from within python via the subprocess module.
Download and install Image Magick.
It’s likely folder path is: C:/Program Files/ImageMagick-7.1.1-Q16-HDRI/
Add the folder path to the Windows PATH Environment Variable.
See how to add PATH variables:

3.3. wand module

The python module, wand, can be used to convert pdfs to jpgs or pngs from within python.
Wand requires that ImageMagick is installed.

3.4. Sample python to convert a pdf to a png

An example of code to convert a pdf to a png is below.
The full path of a pdf file needs to be pasted into the code.
The full path to a pdf file can be obtained by right clicking on a file in the VSCode file explorer or by using the Copy path command in the ribbon in windows File Explorer.
The choice of using magick or wand can be made using commenting and uncommenting in th epython file.
convert a pdf to a png.py uses two custom modules that have been designed to use similar syntax.
The python files need to be in the same folder.

3.4.1. Downloads

To convert one pdf convert_pdf_to_png.py.
To convert a folder of pdfs folder_pdf_to_png.py.

Magick module file magick_pdf_to_png.py module.
Wand module file wand_pdf_to_png.py module.

3.4.2. Python code

The folder_pdf_to_png.py file is shown below.
 1"""
 2Paste in a full folder path to convert pdfs therewithin to pngs @GMC 2023
 3"""
 4from pathlib import Path
 5from tkinter import filedialog
 6
 7
 8import magick_pdf_to_png
 9import wand_pdf_to_png
10
11
12def main():
13    currfile_dir = Path(__file__).parent
14    pdf_dir = filedialog.askdirectory(initialdir=currfile_dir)
15    if pdf_dir == "":
16        print("Exited, by clicking Cancel")
17        return
18
19
20    for pdf_file_path in Path(pdf_dir).glob("*.pdf"):
21        print(pdf_file_path)
22        magick_pdf_to_png.pdf_to_png(pdf_file_path)
23
24
25if __name__ == "__main__":
26    print("starting")
27    main()
28    print("finished")
The convert_pdf_to_png.py file is shown below.
 1"""
 2Paste in a pdf file path to convert the pdf to a png @GMC 2023
 3"""
 4import pathlib
 5import magick_pdf_to_png
 6import wand_pdf_to_png
 7
 8# pdf_file_path = input("Enter a windows full file path to a pdf: ")
 9
10# a raw r string is used since backslashes are normally escape characters
11# paste in windows pdf full file path
12pasted_pdf_file_path = r"C:\Users\Latex_maths\grid_papers\files\graph10by10_black.pdf"
13
14# get file path object
15pdf_file_path = pathlib.PureWindowsPath(pasted_pdf_file_path)
16# use magick or wand -- comment or uncomment to choose
17magick_pdf_to_png.pdf_to_png(pdf_file_path)
18# wand_pdf_to_png.pdf_to_png(pdf_file_path)
The magick_pdf_to_png.py module is shown below.
 1"""
 2Module to convert a pdf to a png using image magick @GMC 2023
 3"""
 4from pathlib import Path
 5import subprocess
 6
 7
 8def convert_pdf_to_png(pdf_path, png_path):
 9    """Called by pdf_to_png to Create a png from a pdf using 600 dpi and max quality
10        Use the subprocess module to call Image Magick in the commandline
11
12    Args:
13        pdf_path (path object): full path to the pdf
14        png_path (path object): full path to the png to be created
15
16    magick args as a list:
17        '-quiet' suppresses the warning in the terminal (that can be ignored), relating to colour profiles
18        '-density','600' sets the dpi to 600
19        '-quality','100' makes the best quality png
20        '-alpha','off' is used here so all transparency is removed
21    """
22    subprocess.run(['magick', 'convert', '-quiet', '-background', 'white', '-alpha', 'off', '-quality', '100', '-density', '600', pdf_path, png_path])
23    # subprocess.run(['magick', 'convert', '-quiet', '-background', 'white', '-alpha', 'off', '-quality', '100', '-density', '600', '-colorspace', 'Gray', pdf_path, png_path]) 
24
25
26def pdf_to_png(pdf_file_path):
27    """create a png from a pdf.
28        png will be created with same file name in same folder as the pdf.
29
30    Args:
31        pdf_file_path (path object from pathlib): the full file path of a pdf.
32    """
33    parent_folder = pdf_file_path.parent
34    file_path_without_extension = parent_folder / pdf_file_path.stem
35    png_path = f"{file_path_without_extension}.png"
36    convert_pdf_to_png(pdf_file_path, png_path)
The wand_pdf_to_png.py module is shown below.
 1"""
 2Module to convert a pdf to a png using the wand python module @GMC 2023
 3"""
 4from pathlib import Path
 5from wand.image import Image
 6
 7
 8def convert_pdf_to_png(pdf_path, png_path):
 9    """Called by pdf_to_png to create a png from a pdf using 600 dpi and max quality
10        Use the Image class from wand.image module
11
12    Args:
13        pdf_path (path object): full path to the pdf
14        png_path (path object): full path to the png to be created
15    """
16    with Image(filename=pdf_path, resolution=600) as img:
17        img.format = "png"
18        img.compression_quality = 99
19        img.alpha_channel = "opaque"
20        img.save(filename=png_path)
21
22
23def pdf_to_png(pdf_file_path):
24    """create a png from a pdf.
25        png will be created with same file name in same folder as the pdf.
26
27    Args:
28        pdf_file_path (path object from pathlib): the full file path of a pdf.
29    """
30    parent_folder = pdf_file_path.parent
31    file_path_without_extension = parent_folder / pdf_file_path.stem
32    png_path = f"{file_path_without_extension}.png"
33    convert_pdf_to_png(pdf_file_path, png_path)

3.5. VSCode LaTeX Workshop

In VSCode, make sure that the LaTeX Workshop is installed.

3.5.1. LaTeX-workshop.LaTeX.tools json

Go to Preferences: Settings.
Search for “LaTeX-workshop tools” or simply “LaTeX tools”.
Edit the tools json at: LaTeX-workshop.LaTeX.tools in the json file.
Add the code block below to the tools json.
Adjust the name value as preferred but it must be also adjusted in the recipe to be identical.
Replace Full_Path_folder with the folder path for your python file.
Put in the full path to the python script using \ as the folder delimiter.
{
    "name": "Python Script to Generate PNG",
    "command": "python",
    "args": [
            "Full_Path_folder\\LaTeX_pdf_to_png.py",
            "%DOCFILE%",
            "%OUTDIR%"
    ],
    "env": {}
}
The json code block defines a custom tool that can be used to convert a LaTeX document to a PNG image.
Here is what each key in the object does:
  • “name”: name of the tool.

  • “command”: the command that will be executed when the tool is run. In this case, it is the Python interpreter.

  • “args”: These are the arguments that will be passed to the command when it is run. In this case, it is a list of three strings:

    • “Full_Path_folder\LaTeX_pdf_to_png.py”: This is the path to the Python script that will be executed.

    • “%DOCFILE%”: This is a placeholder that will be replaced with the name of the LaTeX document file.

    • “%OUTDIR%”: This is a placeholder that will be replaced with the output directory for the PNG image. It is here in case it is needed for further actions in the python script that are yet to be scripted, such as copying the png to a pictures folder.

3.5.2. LaTeX-workshop.LaTeX.recipes json

Go to Preferences: Settings.
Search for “LaTeX-workshop recipes” or simply “LaTeX recipes”.
Edit the recipe json at: LaTeX-workshop.LaTeX.recipes in the json file.
{
    "name": "PDF ➞ PNG",
    "tools": [
            "pdfLaTeX",
            "Python Script to Generate PNG"
    ]
}
The json code block above is a custom tool called “PDF ➞ PNG” and it has two tools: “pdfLaTeX” and “Python Script to Generate PNG”.
The tool is used to convert PDF files to PNG files.
The pdfLaTeX tool is used to generate the PDF file from the LaTeX source code.
The Python script is then used to convert the PDF file to a PNG file.

3.5.3. Python LaTeX_pdf_to_png.py

The python code to go in the python file LaTeX_pdf_to_png.py is below.
Adjust the magick arguments to suit.
import sys
import subprocess

tex_filename = sys.argv[1]
pdf_path = f'{tex_filename}.pdf'
png_path = f'{tex_filename}.png'

subprocess.run(['magick', '-quiet', '-background', 'white', '-alpha', 'off', '-quality', '100', '-density', '600', pdf_path, png_path])
sys.argv is a list in Python that contains the command-line arguments passed to the script. |
tex_filename = sys.argv[1] assigns the first command-line argument passed to the script to the variable tex_filename. From the tools json, the placeholder "%DOCFILE%" is the pdf file name that will be used to name the png file.
This Python code uses the subprocess.run() method to execute the ImageMagick command line tool.
The command line tool is used to convert a PDF file to a PNG file.
Here is what each argument in the command does:
  • magick: This is the ImageMagick command line tool.

  • -quiet: suppresses all output except for errors and warnings.

  • -background white: sets the background color of the output image to white.

  • -alpha off: removes any transparency from the input image.

  • -quality 100: sets the quality of the output image to 100%.

  • -density 600: sets the resolution of the input PDF file to 600 DPI.

  • pdf_path: is the path of the input PDF file.

  • png_path: is the path of the output PNG file.