Qt and LaTeX via KLFBackend
Render LaTeX code via KLFBackend library
23/5/2014 Update: TinyTex's Qt 5 port of KLFBackend has been "updated to 3.2.8":https://bitbucket.org/bruceoutdoors/tiny-tex/pull-request/1/updated-to-328/diff (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":https://bitbucket.org/bruceoutdoors/tiny-tex/get/master.zip . It comes with an simple example("TinyTex":https://bitbucket.org/bruceoutdoors/tiny-tex ). 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.
Requirements
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":http://miktex.org/download - 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
<br />DEFINES ''= KLF_SRC_BUILD<br />
or it will output a bunch of warnings(though the app still runs happily). You will also need the following:
<br /># note that in unix(linux) systems library names are case sensitive<br />win32:CONFIG (release, debug|release): LIBS''= -L$$PWD/build-KLFBackend/ -lklfbackend<br />else:win32:CONFIG (debug, debug|release): LIBS ''= -L$$PWD/build-KLFBackend/ <s>lklfbackend<br />else:unix: LIBS ''= -L$$PWD/build-KLFBackend/ -lKLFBackend
<br />INCLUDEPATH''= $$PWD/klfbackend<br />
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.
mainwindow.h
<br />#ifndef MAINWINDOW_H<br />#define MAINWINDOW_H
<br />#include <QMainWindow&gt;<br />#include <QClipboard&gt;<br />#include "klfbackend.h&quot;<br />#include "klfpreviewbuilderthread.h&quot;
<br />namespace Ui {<br />class MainWindow;<br />}
<br />class MainWindow : public QMainWindow<br />{<br /> Q_OBJECT
<br />public:<br /> explicit MainWindow(QWidget *parent = 0);<br /> ~MainWindow();
<br />private slots:<br /> void updatePreviewBuilderThreadInput();<br /> void showRealTimePreview(const QImage&amp; preview, bool latexerror);<br /> void copyToClipboard();
<br />private:<br /> Ui::MainWindow *ui;<br /> KLFPreviewBuilderThread *mPreviewBuilderThread;<br /> KLFBackend::klfInput input;<br /> KLFBackend::klfSettings settings;<br /> KLFBackend::klfOutput output;<br /> QClipboard *clipboard;<br /> QPixmap pixmap;
<br />};
<br />#endif // MAINWINDOW_H<br />
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:
mainwindow.cpp
<br />#include "mainwindow.h&quot;<br />#include "ui_mainwindow.h&quot;<br />#include "klfbackend.h&quot;<br />#include <QDebug&gt;
<br />MainWindow::MainWindow(QWidget *parent) :
<br /> QMainWindow(parent),<br /> ui(new Ui::MainWindow)<br />{
<br /> ui</s>>setupUi(this);<br /> input.mathmode = "";<br /> input.dpi = 200;<br /> ui->label->setMinimumHeight(input.dpi/2);
<br />// input.bg_color = qRgba(225, 225, 225, 225);<br /> input.preamble = QString("usepackage{amssymb,amsmath,mathrsfs}");<br /> if(!KLFBackend::detectSettings(&settings)) {<br /> qDebug() << "unable to find LaTeX in default directories.";<br /> } else {<br /> qDebug() << "default settings working!";<br /> }
<br /> // setup variables:<br /> mPreviewBuilderThread = new KLFPreviewBuilderThread(this, input, settings);
<br /> // make connections<br /> connect(ui->plainTextEdit, SIGNAL (textChanged()), this,<br /> SLOT (updatePreviewBuilderThreadInput()), Qt::QueuedConnection);<br /> connect(mPreviewBuilderThread, SIGNAL (previewAvailable(const QImage&amp;, bool)),<br /> this, SLOT (showRealTimePreview(const QImage&amp;, bool)), Qt::QueuedConnection);<br /> connect(ui->clipBtn, SIGNAL (clicked()), this, SLOT (copyToClipboard()));
<br /> ui->plainTextEdit->setFocus();<br /> ui->statusBar->showMessage("Waiting for input…");<br />}
<br />void MainWindow::copyToClipboard()<br />{<br /> clipboard->setPixmap(pixmap);<br /> ui->statusBar->showMessage("your image has been copied to clipboard&quot;);
<br />}
<br />MainWindow::~MainWindow()<br />{<br /> delete mPreviewBuilderThread;<br /> delete ui;<br />}
<br />void MainWindow::updatePreviewBuilderThreadInput()<br />{<br /> // in linux, I need to reinstate the preamble when rendering. No idea why.<br /> input.preamble = QString("usepackage{amssymb,amsmath}");<br /> input.latex = ui->plainTextEdit->toPlainText();<br /> if(mPreviewBuilderThread->inputChanged(input)) {<br /> qDebug() << "input changed. Render…";<br /> ui->statusBar->showMessage("Input changed. Render…");<br /> mPreviewBuilderThread->start();<br /> }<br />}
<br />void MainWindow::showRealTimePreview(const QImage&amp; preview, bool latexerror)<br />{<br /> if (latexerror) {<br /> ui->statusBar->showMessage("Unable to render your equation. Please double check.");<br /> } else {<br /> ui->statusBar->showMessage("render is succesful[[Image:|Image:]] :D&quot;);<br /> pixmap = QPixmap::fromImage(preview);<br /> ui->label->setPixmap(pixmap);<br /> ui->label->adjustSize();<br /> }<br />}<br />
Although the LaTeX equation itself is
<br />{amssymb,amsmath,mathrsfs}<br />
I have to write it as
<br />usepackage{amssymb,amsmath,mathrsfs}<br />
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:
<br />#if defined(Q_OS_WIN)<br /> settings.tempdir = QDir::tempPath();<br /> settings.dvipsexec = "D:/Program Files/MiKTeX 2.9/miktex/bin/dvips.exe&quot;;<br /> settings.gsexec = "D:/Program Files/MiKTeX 2.9/miktex/bin/mgs.exe&quot;;<br /> settings.latexexec = "D:/Program Files/MiKTeX 2.9/miktex/bin/latex.exe&quot;;<br />#elif defined(Q_OS_LINUX)<br /> settings.tempdir = QDir::tempPath();<br /> settings.dvipsexec = "/usr/bin/dvips&quot;;<br /> settings.gsexec = "/usr/bin/gs&quot;;<br /> settings.latexexec = "/usr/bin/latex&quot;;<br />#endif<br />
note that to use QDir you need to include QDir in your implementation file.
Where to go from here:
"the KLFBackend API documentation":http://klatexformula.sourceforge.net/doc/apidoc/klfbackend/html/
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.
<br /> > svn checkout https://klatexformula.svn.sourceforge.net/svnroot/klatexformula/trunk/klatexformula<br /> > cd klatexformula/<br /> > mkdir build && cd build/<br /> > cmake .. -DKLF_BUILD_GUI=off -DKLF_LIBKLFTOOLS_STATIC=on -DKLF_LIBKLFBACKEND_STATIC=on -DKLF_BUILD_KTEXTEDITORPLUGIN=off -DCMAKE_INSTALL_PREFIX=/usr/local<br />