112

Is there a converter that will convert LaTeX to HTML? I have tried several services but the LaTeX diagrams and some of the maths came out weird.

I actually converted the Latex to PDF without a problem. Then I used an online PDF to HTML converter to convert from PDF to HTML. The square root signs did not appear properly and some of the Cartesian coordinate plane diagrams had nothing on them except the grid.

\documentclass[12pt,a4paper]{report}
\usepackage{amssymb}
\usepackage{amsthm}
\usepackage{amsmath}
\usepackage{pstricks,pst-plot}
\usepackage{pst-eucl}
\addtolength{\hoffset}{0.2cm}
\addtolength{\textwidth}{1.1cm}
\addtolength{\textheight}{1.0cm}
\addtolength{\voffset}{-0.7cm}
\linespread{1.3}
\begin{document}

If $x$ is non-positive then $x \leq -\sqrt{\frac{1}{2}}$     $\hspace{30 mm} $     (6)\\

(4) and (6) tell us that\\

(4)  $-1 \leq x \leq 0$  \\

(6)  If $x$ is non-positive then $x \leq -\sqrt{\frac{1}{2}}$\\

Therefore $-1 \leq x \leq -\sqrt{\frac{1}{2}}$\\

\vspace{50 mm}

\begin{align*}
\psgrid[unit=2cm](0,0)(-2,-2)(2,2)
\pnode(-1.8,.87){b}\uput[50](b){b}
\pnode(-1.8,1.8){a}\uput[50](a){a}
\psset{linecolor=green}
\psline[linewidth=1pt](-1.8, 0)(-1.8,4)
\psset{linecolor=green}
\psline[linewidth=1pt](-1.8, 0)(-1.8,-4)
\psset{linecolor=blue}
\psellipticarc(0,0)(2,2){0}{180}
\psset{linecolor=red}
\psline[linewidth=1pt,linestyle=dashed,dash=2pt](-2,2)(-1.41,1.41)
\psset{linecolor=red}
\psline[linewidth=1pt](-1.41,1.41)
\psset{linecolor=red}
\psline[linewidth=1pt]{->}(4,-4)
\psset{linecolor=red}
\psline[linewidth=1pt]{->}(-2,2)(-4,4)
\end{align*}

\end{document}

PDF output:

enter image description here

PDF->HTML output:

enter image description here

12 Answers 12

86

Using PDF as an intermediate format when converting from LaTeX to HTML is not very good idea. LaTeX and HTML are both mostly structural markup langauages, which means you use them to describe the document structure (sections, emphasize, formulas etc.), whereas PDF is mostly about representation of your document on the screen or paper. When converting LaTeX to PDF, you loose much of the structural information, and it cannot be successfully recovered by conversion from PDF to HTML.

It is much better to convert LaTeX directly to HTML. There are number of ways (WayBack Archive) how to do that, one I would recommend is by using htlatex. It is probably already part of your TeX distribution, is very powerful and flexible, and its use can be as simple as running

htlatex mydocument.tex

If you tell us more about your environment (which operating system do you use, what is your TeX distribution, your text editor/LaTeX IDE, how you generated the PDF file etc.) we may be able to give you more details on how to use htlatex.

  • I used MiKTeX 2.9 which I downloaded off the internet onto a computer using Windows 7. It is TeXworks and some of the options are pdfLaTeX + MakeIndex + BibTeX, LaTeXmk, pdfTeX, pdfLaTeX, pdfLaTeX + MakeInndex + BibTex, XeTeX, XeLaTeX, XeLaTeX + MakeIndex, + BibTex, ConTeXt(LuaTeX), conTeXt(pdfTeX), ConteXt(XeTeX) – XYZ Dec 27 '11 at 14:04
  • 1
    To get htlatex on Ubuntu 14.04: sudo apt-get install tex4ht – kebs Apr 5 '17 at 13:24
  • htlatex not working for modern tex-engines like XeTeX. – buhtz Aug 5 '17 at 14:06
  • 4
    @JanHlavacek htlatex results this error. ! Undefined control sequence. \pgfsys@svg@newline ->\Hnewline l.230 \pgfusepathqfill} – alhelal Feb 25 '18 at 0:43
  • 1
    htlatex didn't really understand tikz pictures – Fábio Dias Sep 30 '18 at 14:43
21

Is there a converter that will convert LaTeX to HTML?

Yes. There are lots. But you already knew this, as evidenced by your second "question":

I have tried several services but the LaTeX diagrams and some of the maths came out weird.

"turning out weird" could mean any number of things:

  • The document fails to compile
  • The document compiles, but is empty or corrupted
  • The document compiles and opens, but is somehow faulty.

Each of these categories breaks down further and the solution may well depend on what you used to do the conversion, so as it stands, this question is unanswerable.

For diagrams, one word of general advice I would give is that it might be best to compile the diagrams separately and include them into the html by hand with <img> tags. Diagrams are hard. The standalone package/class can help with this. See also the pgf/TikZ externalisation tag.

  • I actually converted the Latex to PDF without a problem. Then I used www.pdfonline.com to convert from PDF to HTML. The square root signs did not appear properly and some of the Cartesian coordinate plane diagrams had nothing on them except the grid. – XYZ Dec 26 '11 at 13:48
  • 4
    @XYZ add this information to your question, along with an example of a file that has this problem. – Seamus Dec 26 '11 at 17:13
17

You may try to use pdf2htmlEX, which is a general PDF to HTML converter. You can compile the LaTeX source to PDF, and then convert the PDF to HTML via pdf2htmlEX. A good reference of pdf2htmlEX is its wiki page. The work-flows are given in the Figure 3 of the article on TUGboat: Online publishing via pdf2htmlEX HTML / PDF.

The screenshot shows the converted HTML (Ubuntu 14.04, Google Chrome 43).

enter image description here

  • 1
    Wow, pdf2htmlEX looks awesome: coolwanglu.github.io/pdf2htmlEX/demo/cheat.html – asmaier Sep 20 '15 at 20:44
  • 2
    This tool worked perfectly for me, and seems a lot more trustworthy than many other tools displayed by google. – mafu Sep 16 '16 at 12:05
  • pdf2htmlEX does not seem to be maintained any more. Too bad, I was hoping it will take off as it seemed promising. – Nasser May 5 at 7:38
16

I have had good mileage with and would recommend pandoc for converting LaTeX to HTML output.

Pandoc provides capability for applying CSS styling to HTML output and can take care of equation rendering with e.g. MathML and citation/bibliography styling, among many other features, and is well documented.

6

Three words: use LaTeX subset

LaTeX and its common output formats like PDF are super complicated. Converting all of it to HTML + CSS is close to impossible.

But if you restrict yourself only to a small subset of LaTeX features it becomes feasible.

First I recommend that you just try to go with a simpler format like Markdown, which can be converted to HTML and PDF by several implementations like pandoc. I have come to believe that having painless HTML is more important than the infinite many features of LaTeX.

Then, check out Softcover: it has a LaTeX subset which it calls Polytex that it can convert to HTML. The exact subset is not well documented, but it already handles 99.9% of what we need to make regular books as shown in their documentation https://github.com/softcover/softcover_book/tree/master/chapters : sections, lists, equations, tables, images, references. Softcover does it's magic through Tralics, which does LaTeX to XML.

As Seamus said, diagrams are hard, and it is unlikely they will be part of the implementable subset any time soon, so use images. Generate the images through a command line tool like gplot or pyplot, and then build the PDF with a Makefile that first builds the images and then the PDF.

5

In my perspective none works better than LaTeXML.

Here is a ready-made docker image with latexml installed and the instructions to convert tex documents. Its very much tightly integrated with LaTeX and delivers same looking output in html as in pdf.

Cheers!!

5

As previously observed using PDF format for converting from LaTeX to HTML is very bad idea. Here you will find a comprehensive list of programs that convert LaTeX to HTML (Note not all of those programs are capable of converting pure TeX.)

http://www.tex.ac.uk/cgi-bin/texfaq2html?label=LaTeX2HTML

I am familiar with three of these programs: LaTeX2HTML, TeX4ht, and Hevea. All of them have their strengths and weaknesses and they use different approaches. TeX4ht is included in TeXLive and MiKTeX unlike other two and from the point of view of theoretical CS is a "correct" way to do conversion (not surprisingly it was written by a (now deceased) member of the CS department at Ohio State). If you have just a few pages to convert, probably the right approach for you would be to chose any of the three and then do some manual editing. Now you have to be careful. For example Hevea will try to use HTML tags for things like square root while TeX4ht will use bitmap images for any math expressions. Since pure HTML has a poor support for mathematics the first approach can quickly get into trouble but when it works the output is really beautiful.

As for diagrams and pictures, all of the above programs to my knowledge rely on ImageMagic to do image conversion. Hevea has to be run multiple times (it is actually bunch of scripts) and the proper way to use it is by writing a Makefile (Unix again). I would actually convert images and diagrams manually using GraphicMagic which is IMHO far more stable and better batch image processor than ImageMagic.

  • 1
    What do you mean by "theoretical CS correct" more precisely? – Ciro Santilli 新疆改造中心996ICU六四事件 Aug 15 '14 at 14:54
  • He means that there is no provably correct HTML output for any given LaTeX input, and so authors of conversion software need to make creative decisions on what to output. – Maarten Aug 14 '17 at 14:01
4

I'm currently developing a free open source tool that can convert LaTeX to a single HTML file. Its called PDBF (https://github.com/uds-datalab/PDBF) and runs on win/linux/mac.

Instructions:

Resulting HTML file is placed in the same folder as the source tex file with the same name as the source tex file.

Technical details: The PDBF compiler basically uses a regular tex engine to compile your pdf and then stores the pdf as base64 encoded javascript string in the HTML and then includes a slightly modified version of pdf.js (The free and open source pdf engine of firefox) into the HTML to display that pdf.

Hope you like my project. Feel free to contact me through github if you have suggestions or encounter bugs.

  • What do you gain from running the standard PDF previewer of Chrome/Firefox, etc ...? – Paulo Ney Feb 15 '17 at 2:59
  • @Paulo Ney 1. You can then open the html files also with browsers that have no PDF viewer included. 2. It allowed us to extend PDF.js to make charts and other things in the resulting html interactive (example) – Patrick Bender Feb 16 '17 at 6:35
4

There is a lwarp package on CTAN which treats tikz diagrams really well: example

3

RtextDoc has a built in Latex to Html converter

  • 2
    How well does it cope with the type of documents the poster is interested in? – Andrew Swann Oct 23 '13 at 6:25
2

You might want to consider using DocOnce as primary format instead of LaTeX:

DocOnce is a modestly tagged (Markdown-like) markup language targeting scientific reports, software documentation, books, blog posts, and slides involving much math and code in the text. From DocOnce source you can generate LaTeX, Sphinx, HTML, IPython notebooks, Markdown, MediaWiki, and other formats. This means that you from a single source can get the most up-to-date publishing technologies for paper, tablets, and phones.

2

I was trying to do the same thing, and found this post. But... even though my book doesn't have fancy mathematical formulas, I thought what I developed could be of use to future generation of Latex book writers who are frustrated by HTML conversion.

I really needed to convert my Latex book to HTML. Having had experience with writing my own plain-text to HTML converters for some personal project software, and server side programming, I wrote this PHP script, that solves the problem for simple Latex documents using Regular Expressions.

By simple, I mean, only converts the following items:

  1. Images with "Figure" caption (automatic Figure N inserted)
  2. Converts begin{lstlisting}...end{lstlisting} to <code>...</code>
  3. Accurately converts \textbf, \textit and \texttt, so long as you follow the rule of nesting italics inside bolds (and not the other way around) to <b>, <i> and <span style = "font-family: Courier; font-weight: bold; color: #FF4500"> respectively. Change the color if need to.
  4. \section to <H1>
  5. \subsection to <H2>
  6. \subsubsection to <H3>
  7. Note, \begin{figure} will be converted to <img src = ""/>

The last item (7) requires additional attention. You must replicate your image folder elsewhere, and tweak the PHP script to point to it. In this example it is set to http://localhost/ it is assumed that you have some base image folder for entire manuscript. Make sure it exists somewhere and specify it in this part of the script.

One idea is... if possible, you can convert your mathematical formulas to images, use those images in your Latex document, and you should have no problem with the conversion using this script. Unfortunately, HTML doesn't really support math too well, at least at this time. Good luck!

It also does some other silly clean-up tweaking, like converting <p></p> to space, just to make sure there are no HTML redundancies.

The script is surprisingly simple. All glory to Regular Expressions.

It is also flexible - If you encounter errors, tweak it to your own heart desire. But be warned - it is quite important to perform some replacements in the exact order they appear in the script. Otherwise, you might break it.

Run following PHP script on your localhost, and make sure source.tex is your Latex manuscript and that it resides in the same folder from which you are running the script:

<?php

chdir(dirname(__FILE__));
$file = file_get_contents("source.tex");

$figure_counter = 1;
$all_codes = array();

// Replace code 
$file = preg_replace('/.lstset(.*)/', '', $file);                                   // replace code block
$file = preg_replace('/.begin{lstlisting}(.*)/', '<code>', $file);              // replace code block
$file = preg_replace('/.end{lstlisting}/', '</code>', $file);                       // replace code block

// Replace all <code>....</code> with CODE0, CODE1, CODE2, ... etc.
// It's best  to do code clean up before any thing else
// Clean up < brackets inside <code> blocks, memorize all codes for later re-insertion,
function callback($matches) { global $all_codes; $M = str_replace(">", "&gt;", str_replace(">","&lt;",$matches[0])); $C = count($all_codes); $all_codes[$C] = $M; return "\n\nCODE".$C."\n\n"; }
$file = preg_replace_callback('/<code>(\r|\n|.*?)<\/code>/s', 'callback', $file);   

// order is important here --  must convert TTT first, before BF AND IT
$file = preg_replace_callback('/.texttt{(.*?)}/', 'callbackT', $file);          // mono text

// convert text styles
$file = preg_replace('/.textbf{(.*?)}/', '<b>$1</b>', $file);           // bold text
$file = preg_replace('/.textit{(.*?)}/', '<i>$1</i>', $file);           // italic text
function callbackT($matches) { return '<span style = "font-family:Courier; font-weight: bold; color: #FF4500">' . str_replace(">", "&gt;", str_replace("<","&lt;",substr($matches[0],8,-1))) . '</span>'; }

// convert sections to headers
$file = preg_replace('/.section{(.*?)}/', '<h1>$1</h1>', $file);            // H1
$file = preg_replace('/.subsection{(.*?)}/', '<h2>$1</h2>', $file);         //  H2
$file = preg_replace('/.subsubsection{(.*?)}/', '<h3>$1</h3>', $file);      //  H3

// Replace images
$file = preg_replace('/.begin{figure}(.*)/', '', $file);                        // replace images
$file = preg_replace('/.end{figure}(.*)/', '', $file);                      // replace images
$file = preg_replace('/ .centering/', '', $file);                       // replace images
function callback1($matches) { global $figure_counter; return "<p>Figure " . ($figure_counter++) . ": " . substr($matches[0], 10, -1) . "</p>"; }
$file = preg_replace_callback('/    .caption{(.*?)}/', 'callback1', $file);                     // replace images

$file = preg_replace('/ .includegraphics(.*?){"\.\.(.*?)"}/', '<p><img src = "http://localhost/$2.png"></p>', $file);                       // replace images
$file = preg_replace('/ .label{(.*?)}/', '', $file);                        // replace images

// Insert paragraphs
$file = preg_replace('/(.*?)\r\n\r\n/', "\n<p>$1</p>\n", $file);

// just in case
$file = preg_replace('/<p><p>/', "<p>" . "\n", $file);
$file = preg_replace('/<\/p><\/p>/', "</p>" . "\n", $file);
$file = preg_replace('/<p>\nFigure/', "<p>Figure", $file);
$file = preg_replace('/<p>Figure\n/', "<p>Figure", $file);

// As the last step, reinsert codes, to avoid messing them up by previous replacements
for ($i = 0; $i < count($all_codes); $i++)
    $file = preg_replace('/CODE'.$i.'/', $all_codes[$i], $file);

// Not sure why this is still the case but it is..
$file = preg_replace('/\n<p><\/code><\/p>/', "</code>", $file);

$style = "<style>body {background:white !important; color: black !important;} code { border: 1px solid gray; padding: 4px; } img { margin: 0 auto; position: relative; display: block; text-align: center; width: 75%; max-width: 500px; }</style>";

/* Print out the book in HTML! */   
print "<body>" . $style . "\n" . $file . "</body>";

?>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.