1.3 Install missing LaTeX packages

When you compile a document to PDF through LaTeX, you may run into errors like these:

! LaTeX Error: File `ocgbase.sty' not found.

!pdfTeX error: pdflatex (file 8r.enc):
  cannot open encoding file for reading

!pdfTeX error: /usr/local/bin/pdflatex (file tcrm0700):
  Font tcrm0700 at 600 not found

If you are using TinyTeX as introduced in Section 1.2, usually you do not need to deal with such errors, since tinytex (Xie 2020e) will automatically deal with them, but if you run into such errors anyway, it is still easy to install the missing LaTeX package(s) via tinytex::parse_install(). This function takes the path of the LaTeX log file as the input, tries to figure out the missing packages automatically, and installs them if they are found on CTAN (the Comprehensive TEX Archive Network, https://ctan.org). The LaTeX log file typically has the same base name as your input document, and has an extension .log. If you cannot find this log file, you can pass the error message to the text argument of this function. Both ways should work:

# if the log file is filename.log
tinytex::parse_install("filename.log")

# or use the `text` argument
tinytex::parse_install(
  text = "! LaTeX Error: File `ocgbase.sty' not found."
)
# it will install the "ocgx2" package

If you do not use TinyTeX, the R package tinytex can still help you figure out the LaTeX package names from the error log—use the function tinytex::parse_packages(), e.g.,

# if the log file is filename.log
tinytex::parse_packages("filename.log")

# or use the `text` argument
tinytex::parse_packages(
  text = "! LaTeX Error: File `ocgbase.sty' not found."
)
# it should return "ocgx2"

Once you know the package names, you can install them with the package manager of your LaTeX distribution.

If you are using MiKTeX instead, it can also install missing packages automatically. During the installation of MiKTeX, be sure to check the setting “Always install missing packages on-the-fly.” If you have already installed it without this setting, you can still change it in the MiKTeX Console.

References

———. 2020e. Tinytex: Helper Functions to Install and Maintain TeX Live, and Compile LaTeX Documents. https://github.com/yihui/tinytex.