Qt and LaTeX via KLFBackend

From Qt Wiki
Jump to navigation Jump to search

En Ar Bg De El Es Fa Fi Fr Hi Hu It Ja Kn Ko Ms Nl Pl Pt Ru Sq Th Tr Uk Zh

Render LaTeX code via KLFBackend library

2016-03-23 Update: TinyTex compiles with Qt 5.6 (at least on Linux) but won't render any input. Probably some TeX Live package is missing on my machine. --Wieland (talk) 21:46, 23 March 2016 (UTC)

2014-05-23 Update: TinyTex's Qt 5 port of KLFBackend has been updated to 3.2.8 (fixes a bug with ghostscript) thanks to retux

What is KLFBackend?

KLFBackend is a C++ library originally developed by Philippe Faist to render LaTeX code in KLatexFormula: http://klatexformula.sourceforge.net/doc/apidoc/klfbackend/html/

Getting it


The source code of KLFBackend is inside KLatexFormula from here http://klatexformula.sourceforge.net/download/ (as of this writing the current stable source version is 3.2.6). However, the library only works with Qt 4. I have a modified version of the library that allows it to support both Qt 4 and Qt 5 plus certain features which I'll get to. For this tutorial to work you'll need this modified version. Download it from here . It comes with an simple example(TinyTex ). Note that TinyTex only works with Qt 5. To make it work with Qt 4 you would need to rebuild it and change some includes.


Library is tested to work on Windows 7 and Linux Mint 14 32bit, in Qt 4 and Qt 5. However, for windows users you can only use MinGW version of Qt. MSCV2010 compiler will produce an error should you try to build the library or run programs with it.

To get latex working: In linux you'll nees to install texlive and ghostscript from synaptic package manager. In windows install Miktex - just the basic Miktex would work.

Building the library

Open the KLFBackend pro file located in the latextest folder that you've downloaded and build the project. Now go to the "build-KLFBackend" directory where you have build your library and you should see KLFBackend.dll(windows) or libKLFBackend.so, libKLFBackend.so.1, libKLFBackend.so.1.0, libKLFBackend.so.1.0.0(linux). You can freely choose to discard the rest of the files cause they're taking up space.

Using KLFBackend in your Qt app.

Open TinyTex.pro to access the example(alternatively you can refer to KLatexFormula's source code as most of the code in this mini example originated from there).

in your pro file be sure you have


or it will output a bunch of warnings(though the app still runs happily). You will also need the following:

# note that in unix(linux) systems library names are case sensitive
win32:CONFIG (release, debug|release): LIBS''= -L$$PWD/build-KLFBackend/ -lklfbackend
else:win32:CONFIG (debug, debug|release): LIBS ''= -L$$PWD/build-KLFBackend/ -lklfbackend
else:unix: LIBS ''= -L$$PWD/build-KLFBackend/ -lKLFBackend

INCLUDEPATH''= $$PWD/klfbackend

this will add KLFBackend library(LIB) when running app, and import all the headers(INCLUDEPATH) in KLFBackend into your project. Note that $$PWD refers to the project working directory.



#include <QMainWindow>
#include <QClipboard>
#include "klfbackend.h"
#include "klfpreviewbuilderthread.h"

namespace Ui {
class MainWindow;

class MainWindow : public QMainWindow

 explicit MainWindow(QWidget *parent = 0);

private slots:
 void updatePreviewBuilderThreadInput();
 void showRealTimePreview(const QImage& preview, bool latexerror);
 void copyToClipboard();

 Ui::MainWindow *ui;
 KLFPreviewBuilderThread *mPreviewBuilderThread;
 KLFBackend::klfInput input;
 KLFBackend::klfSettings settings;
 KLFBackend::klfOutput output;
 QClipboard *clipboard;
 QPixmap pixmap;


#endif // MAINWINDOW_H

KLFBackend::klfInput object stores input like preamble, mathmode, latex code and size. KLFBackend::klfSettings stores settings like the directories of your latex executable. the KLFPreviewBuilderThread object is used to render your equations by feeding it with KLFBackend::klfInput and KLFBackend::klfSettings. We will save the image as a QPixmap to the clipboard although it's output a QImage, because for some reason copying the QImage of the equation gives really choppy results.

Below is the implementation file:


#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "klfbackend.h"
#include <QDebug>

MainWindow::MainWindow(QWidget *parent) :

 ui(new Ui::MainWindow)

 input.mathmode = "";
 input.dpi = 200;

// input.bg_color = qRgba(225, 225, 225, 225);
 input.preamble = QString("usepackage{amssymb,amsmath,mathrsfs}");
 if(!KLFBackend::detectSettings(&settings)) {
 qDebug() << "unable to find LaTeX in default directories.";
 } else {
 qDebug() << "default settings working!";

 // setup variables:
 mPreviewBuilderThread = new KLFPreviewBuilderThread(this, input, settings);

 // make connections
 connect(ui->plainTextEdit, SIGNAL (textChanged()), this,
 SLOT (updatePreviewBuilderThreadInput()), Qt::QueuedConnection);
 connect(mPreviewBuilderThread, SIGNAL (previewAvailable(const QImage&, bool)),
 this, SLOT (showRealTimePreview(const QImage&, bool)), Qt::QueuedConnection);
 connect(ui->clipBtn, SIGNAL (clicked()), this, SLOT (copyToClipboard()));

 ui->statusBar->showMessage("Waiting for input…");

void MainWindow::copyToClipboard()
 ui->statusBar->showMessage("your image has been copied to clipboard");


 delete mPreviewBuilderThread;
 delete ui;

void MainWindow::updatePreviewBuilderThreadInput()
 // in linux, I need to reinstate the preamble when rendering. No idea why.
 input.preamble = QString("usepackage{amssymb,amsmath}");
 input.latex = ui->plainTextEdit->toPlainText();
 if(mPreviewBuilderThread->inputChanged(input)) {
 qDebug() << "input changed. Render…";
 ui->statusBar->showMessage("Input changed. Render…");

void MainWindow::showRealTimePreview(const QImage& preview, bool latexerror)
 if (latexerror) {
 ui->statusBar->showMessage("Unable to render your equation. Please double check.");
 } else {
 ui->statusBar->showMessage("render is succesful[[Image:|Image:]] :D");
 pixmap = QPixmap::fromImage(preview);

Although the LaTeX equation itself is


I have to write it as


because in C+ strings, the backslash is used to indicate some commands(e.g is newline). So is read as by the program.

KLFBackend::detectSettings is a useful function to automatically search your the required executables. However should you need to set it manually you'll do is as so:

#if defined(Q_OS_WIN)
 settings.tempdir = QDir::tempPath();
 settings.dvipsexec = "D:/Program Files/MiKTeX 2.9/miktex/bin/dvips.exe";
 settings.gsexec = "D:/Program Files/MiKTeX 2.9/miktex/bin/mgs.exe";
 settings.latexexec = "D:/Program Files/MiKTeX 2.9/miktex/bin/latex.exe";
#elif defined(Q_OS_LINUX)
 settings.tempdir = QDir::tempPath();
 settings.dvipsexec = "/usr/bin/dvips";
 settings.gsexec = "/usr/bin/gs";
 settings.latexexec = "/usr/bin/latex";

note that to use QDir you need to include QDir in your implementation file.

Where to go from here:

the KLFBackend API documentation

The development version of KLatexFormula adds extra features to KLFBackend. According to the author…

Performance wise the older version might be slightly better, if only because it's more lightweight. The new version no longer depends on "epstopdf" for generating pdf, and uses directly ghostscript directly. It has much better detection of bounding boxes, can also generate SVG if the ghostscript driver is installed, and has a better interface for different fonts sizes and vector scaling. It stores also meta-information in PDF files too. You can also invoke user scripts that change the way the formula is rendered (for example for feynman diagrams with feynmf). Maybe more and I'm forgetting. So basically, it has more features, but if you were fine with 3.2, you can stick to that. KLFBackend now needs some tools that are defined in klftools (e.g. data serializing, and utilities for the user scripts), and so depends on that library. And it wasn't logical to have klftools depend on klfbackend.

Note that you will need to install cmake to configure it, and that it currently only works with Qt 4, and that I can't get to build in windows.

 > svn checkout https://klatexformula.svn.sourceforge.net/svnroot/klatexformula/trunk/klatexformula
 > cd klatexformula/
 > mkdir build && cd build/