2010-04-10 55 views

回答

3

Displaying fancy equations with Java Generate Images for formulas in Java

約有我說你的選擇是:

  • 使用的第一個問題提到的,如果他們適合你的應用程序和乳膠形式的Java庫之一(例如,它是否包含宏,樣式文件和BibTex或者單個方程式的整個文檔)。
  • 執行texvc作爲外部程序(如Wikipedia/MediaWiki),或通過JNI鏈接到OCaml代碼。

EDIT

斯蒂芬c。所述,這些僅用於乳膠的片段。如果你想轉換一個完整的Latex文檔,你需要一個完整的Latex實現 - 以上都不是。這些需要有點大而複雜,因爲它們是通過編寫乳膠代碼來排版文檔的完整「開發環境」。如果這是你所需要的,那麼你沒有太多的選擇,只能通過exec來使用標準的Latex發行版中的一個(我猜如果Latex解釋器報告Latex代碼中的錯誤,那麼我們會優雅地失敗)。

也就是說,至少有一些嘗試將Latex移植到Java(包括兩個名爲「JavaTex」)。最有可能這些都不是會適合你的狀態 - 但看到最近的一些嘗試的總結自己判斷:

http://www.monperrus.net/martin/running+tex+on+a+java+virtual+machine

0

這樣做並非不可能。 (Java是圖靈完成...)。但是(IMO)不太可能會找到一個現有的庫來處理Java中的TeX/LaTeX,而且您自己實現這一點也不切實際。

我會尋找將TeX/LaTeX轉換成某些東西(例如pdf或postscript)的命令行應用程序,然後尋找能夠頁面圖像的東西。然後,我會創建一個包裝腳本,根據需要組合應用程序,並使用Process.exec(...)來運行該腳本。

編輯

如果你只是想使乳膠數學公式,嘗試通過@ RD1鏈接的答案提示的選項。

1

另一種解決方案是(這裏可供選擇:http://www.forkosh.com/mimetex.html)調用mimetex.cgi從Java。

我不敢說這個解決方案比之前給出,尤其是使用JLatexMath的那些「更好」。目的只是爲了提供替代品。結果的

實施例:

enter image description here

代碼導致這種結果:

import java.awt.*; 
import java.io.*; 
import java.util.ArrayList; 
import javax.swing.*; 

public class Exemple106_MimetexInterface { 

private static String MIMETEX_EXE = "c:\\Program Files (x86)\\mimetex\\mimetex.cgi"; 

final private static int BUFFER_SIZE = 1024; 

/** 
* Convert LaTeX code to GIF 
* 
* @param latexString LaTeX code 
* @return GIF image, under byte[] format 
*/ 
public static byte[] getLaTeXImage(String latexString) { 
    byte[] imageData = null; 
    try { 
     // mimetex is asked (on the command line) to convert 
     // the LaTeX expression to .gif on standard output: 
     Process proc = Runtime.getRuntime().exec(MIMETEX_EXE + " -d \"" + latexString + "\""); 
     // get the output stream of the process: 
     BufferedInputStream bis = (BufferedInputStream) proc.getInputStream(); 
     // read output process by bytes blocks (size: BUFFER_SIZE) 
     // and stores the result in a byte[] Arraylist: 
     int bytesRead; 
     byte[] buffer = new byte[BUFFER_SIZE]; 
     ArrayList<byte[]> al = new ArrayList<byte[]>(); 
     while ((bytesRead = bis.read(buffer)) != -1) { 
      al.add(buffer.clone()); 
     } 
     // convert the Arraylist in an unique array: 
     int nbOfArrays = al.size(); 
     if (nbOfArrays == 1) { 
      imageData = buffer; 
     } else { 
      imageData = new byte[BUFFER_SIZE * nbOfArrays]; 
      byte[] temp; 
      for (int k = 0; k < nbOfArrays; k++) { 
       temp = al.get(k); 
       for (int i = 0; i < BUFFER_SIZE; i++) { 
        imageData[BUFFER_SIZE * k + i] = temp[i]; 
       } 
      } 
     } 
     bis.close(); 
     proc.destroy(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
    return imageData; 
} 

/** 
* demonstration main 
* 
* @param args command line arguments 
*/ 
public static void main(String[] args) { 
    JFrame jframe = new JFrame(); 
    jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    jframe.setLayout(new BorderLayout()); 

    String LATEX_EXPRESSION_1 = "4$A=\\(\\array{3,c.cccBCCC$&1&2&3\\\\\\hdash~1&a_{11}&a_{12}&a_{13}\\\\2&a_{21}&a_{22}&a_{23}\\\\3&a_{31}&a_{32}&a_{33}}\\) "; 
    byte[] imageData1 = getLaTeXImage(LATEX_EXPRESSION_1); 
    JLabel button1 = new JLabel(new ImageIcon(imageData1)); 
    jframe.add(button1, BorderLayout.NORTH); 

    String LATEX_EXPRESSION_2 = "4$\\array{rccclBCB$&f&\\longr[75]^{\\alpha:{-1$f\\rightar~g}}&g\\\\3$\\gamma&\\longd[50]&&\\longd[50]&3$\\gamma\\\\&u&\\longr[75]_\\beta&v}"; 
    byte[] imageData2 = getLaTeXImage(LATEX_EXPRESSION_2); 
    JLabel button2 = new JLabel(new ImageIcon(imageData2)); 
    jframe.add(button2, BorderLayout.CENTER); 

    String LATEX_EXPRESSION_3 = "4$\\hspace{5}\\unitlength{1}\\picture(175,100){~(50,50){\\circle(100)}(1,50){\\overbrace{\\line(46)}^{4$\\;\\;a}}(52,50) {\\line(125)}~(50,52;115;2){\\mid}~(52,55){\\longleftar[60]}(130,56){\\longrightar[35]}~(116,58){r}~(c85,50;80;2){\\bullet} (c85,36){3$-q}~(c165,36){3$q}(42,30){\\underbrace{\\line(32)}_{1$a^2/r\\;\\;\\;}}~}"; 
    byte[] imageData3 = getLaTeXImage(LATEX_EXPRESSION_3); 
    JLabel button3 = new JLabel(new ImageIcon(imageData3)); 
    jframe.add(button3, BorderLayout.SOUTH); 

    jframe.pack(); 
    jframe.setLocationRelativeTo(null); 
    jframe.setVisible(true); 
} 
} 

尼古拉斯

0

另一種解決方案來創建由膠乳提供膠乳A PNG圖像(實例:MiKTeX)安裝在電腦上 ...

LaTeX獨立程序包允許創建一個PNG輸出文件,其大小與公式或文本的大小完全一致。

所以,我們只能從Java調用乳膠,並獲得PNG輸出文件。

1.先決條件

一個)膠乳應被安裝在計算機
...上與所需的式(所有包在下面的例子:amsfonts和amsmath)
...與獨立軟件包

GhostScript將被安裝(對於獨立軟件包必需)
包含gswin32c.exe的目錄應添加到PATH中。
在我的電腦:C:\ Program Files文件(x86)的\ GS \ gs9.10 \ BIN

應安裝(必要的獨立包)ImageMagick的
CONVERT.EXE應改名爲imgconvert.exe
包含imgconvert.exe的目錄應添加到PATH中。
在我的電腦:C:\ Program Files文件(x86)的\ ImageMagick的-6.8.8-9

2.檢查乳膠(帶獨立包)成功地生成PNG文件(沒有Java在這個階段) 。

參考:https://tex.stackexchange.com/questions/11866/compile-a-latex-document-into-a-png-image-thats-as-short-as-possible

LaTeX的文件,名爲New21。特(例如):

\documentclass[border=0.50001bp,convert={convertexe={imgconvert},outext=.png}]{standalone} 

\usepackage{amsfonts} 

\usepackage{amsmath} 

\begin{document} 

$\begin{array}{l} 

\forall\varepsilon\in\mathbb{R}_+^*\ \exists\eta>0\ |x-x_0|\leq\eta\Longrightarrow|f(x)-f(x_0)|\leq\varepsilon\\ 

\det\begin{bmatrix}a_{11}&a_{12}&\cdots&a_{1n}\\a_{21}&\ddots&&\vdots\\\vdots&&\ddots&\vdots\\a_{n1}&\cdots&\cdots&a_{nn}\end{bmatrix}\overset{\mathrm{def}}{=}\sum_{\sigma\in\mathfrak{S}_n}\varepsilon(\sigma)\prod_{k=1}^n a_{k\sigma(k)}\\ 

{\sideset{_\alpha^\beta}{_\gamma^\delta}{\mathop{\begin{pmatrix}a&b\\c&d\end{pmatrix}}}}\\ 

\int_0^\infty{x^{2n} e^{-a x^2}\,dx} = \frac{2n-1}{2a} \int_0^\infty{x^{2(n-1)} e^{-a x^2}\,dx} = \frac{(2n-1)!!}{2^{n+1}} \sqrt{\frac{\pi}{a^{2n+1}}}\\ 

\int_a^b{f(x)\,dx} = (b - a) \sum\limits_{n = 1}^\infty {\sum\limits_{m = 1}^{2^n - 1} {\left({ - 1} \right)^{m + 1} } } 2^{ - n} f(a + m\left({b - a} \right)2^{-n})\\ 

\int_{-\pi}^{\pi} \sin(\alpha x) \sin^n(\beta x) dx = \textstyle{\left \{ \begin{array}{cc} (-1)^{(n+1)/2} (-1)^m \frac{2 \pi}{2^n} \binom{n}{m} & n \mbox{ odd},\ \alpha = \beta (2m-n) \\ 0 & \mbox{otherwise} \\ \end{array} \right .}\\ 

L = \int_a^b \sqrt{ \left|\sum_{i,j=1}^ng_{ij}(\gamma(t))\left(\frac{d}{dt}x^i\circ\gamma(t)\right)\left(\frac{d}{dt}x^j\circ\gamma(t)\right)\right|}\,dt\\ 

\begin{array}{rl} s &= \int_a^b\left\|\frac{d}{dt}\vec{r}\,(u(t),v(t))\right\|\,dt \\ &= \int_a^b \sqrt{u'(t)^2\,\vec{r}_u\cdot\vec{r}_u + 2u'(t)v'(t)\, \vec{r}_u\cdot\vec{r}_v+ v'(t)^2\,\vec{r}_v\cdot\vec{r}_v}\,\,\, dt. \end{array}\\ 

\end{array}$ 

\end{document} 

命令行:

pdflatex -shell-escape New21.tex 

這應該生成包含文件New21.png下面的圖片: enter image description here

3. PNG文件的生成從Java,通過致電LaTeX

代碼:

import java.awt.FlowLayout; 
import java.io.BufferedReader; 
import java.io.File; 
import java.io.FileWriter; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.InputStreamReader; 
import javax.swing.ImageIcon; 
import javax.swing.JFrame; 
import javax.swing.JLabel; 

class StreamPrinter implements Runnable { 

    // Source: http://labs.excilys.com/2012/06/26/runtime-exec-pour-les-nuls-et-processbuilder/ 
    private final InputStream inputStream; 

    private boolean print; 

    StreamPrinter(InputStream inputStream, boolean print) { 
     this.inputStream = inputStream; 
     this.print = print; 
    } 

    private BufferedReader getBufferedReader(InputStream is) { 
     return new BufferedReader(new InputStreamReader(is)); 
    } 

    @Override 
    public void run() { 
     BufferedReader br = getBufferedReader(inputStream); 
     String ligne = ""; 
     try { 
      while ((ligne = br.readLine()) != null) { 
       if (print) { 
        System.out.println(ligne); 
       } 
      } 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
    } 
} 

public class Exemple141_LaTeX_to_PNG_using_installed_LaTeX_distribution { 

    public static void main(String[] args) { 

     String TEMP_DIRECTORY = "D:\\_tmp"; 
     String TEMP_TEX_FILE_NAME = "New22"; // for New22.tex 

     // 1. Prepare the .tex file 
     String newLineWithSeparation = System.getProperty("line.separator")+System.getProperty("line.separator"); 
     String math = ""; 
     math += "\\documentclass[border=0.50001bp,convert={convertexe={imgconvert},outext=.png}]{standalone}" + newLineWithSeparation; 
     math += "\\usepackage{amsfonts}" + newLineWithSeparation; 
     math += "\\usepackage{amsmath}" + newLineWithSeparation; 
     math += "\\begin{document}" + newLineWithSeparation; 
     math += "$\\begin{array}{l}" + newLineWithSeparation; 
     math += "\\forall\\varepsilon\\in\\mathbb{R}_+^*\\ \\exists\\eta>0\\ |x-x_0|\\leq\\eta\\Longrightarrow|f(x)-f(x_0)|\\leq\\varepsilon\\\\" + newLineWithSeparation; 
     math += "\\det\\begin{bmatrix}a_{11}&a_{12}&\\cdots&a_{1n}\\\\a_{21}&\\ddots&&\\vdots\\\\\\vdots&&\\ddots&\\vdots\\\\a_{n1}&\\cdots&\\cdots&a_{nn}\\end{bmatrix}\\overset{\\mathrm{def}}{=}\\sum_{\\sigma\\in\\mathfrak{S}_n}\\varepsilon(\\sigma)\\prod_{k=1}^n a_{k\\sigma(k)}\\\\" + newLineWithSeparation; 
     math += "{\\sideset{_\\alpha^\\beta}{_\\gamma^\\delta}{\\mathop{\\begin{pmatrix}a&b\\\\c&d\\end{pmatrix}}}}\\\\" + newLineWithSeparation; 
     math += "\\int_0^\\infty{x^{2n} e^{-a x^2}\\,dx} = \\frac{2n-1}{2a} \\int_0^\\infty{x^{2(n-1)} e^{-a x^2}\\,dx} = \\frac{(2n-1)!!}{2^{n+1}} \\sqrt{\\frac{\\pi}{a^{2n+1}}}\\\\" + newLineWithSeparation; 
     math += "\\int_a^b{f(x)\\,dx} = (b - a) \\sum\\limits_{n = 1}^\\infty {\\sum\\limits_{m = 1}^{2^n - 1} {\\left({ - 1} \\right)^{m + 1} } } 2^{ - n} f(a + m\\left({b - a} \\right)2^{-n})\\\\" + newLineWithSeparation; 
     math += "\\int_{-\\pi}^{\\pi} \\sin(\\alpha x) \\sin^n(\\beta x) dx = \\textstyle{\\left \\{ \\begin{array}{cc} (-1)^{(n+1)/2} (-1)^m \\frac{2 \\pi}{2^n} \\binom{n}{m} & n \\mbox{ odd},\\ \\alpha = \\beta (2m-n) \\\\ 0 & \\mbox{otherwise} \\\\ \\end{array} \\right .}\\\\" + newLineWithSeparation; 
     math += "L = \\int_a^b \\sqrt{ \\left|\\sum_{i,j=1}^ng_{ij}(\\gamma(t))\\left(\\frac{d}{dt}x^i\\circ\\gamma(t)\\right)\\left(\\frac{d}{dt}x^j\\circ\\gamma(t)\\right)\\right|}\\,dt\\\\" + newLineWithSeparation; 
     math += "\\begin{array}{rl} s &= \\int_a^b\\left\\|\\frac{d}{dt}\\vec{r}\\,(u(t),v(t))\\right\\|\\,dt \\\\ &= \\int_a^b \\sqrt{u'(t)^2\\,\\vec{r}_u\\cdot\\vec{r}_u + 2u'(t)v'(t)\\, \\vec{r}_u\\cdot\\vec{r}_v+ v'(t)^2\\,\\vec{r}_v\\cdot\\vec{r}_v}\\,\\,\\, dt. \\end{array}\\\\" + newLineWithSeparation; 
     math += "\\end{array}$" + newLineWithSeparation; 
     math += "\\end{document}"; 

     // 2. Create the .tex file 
     FileWriter writer = null; 
     try { 
      writer = new FileWriter(TEMP_DIRECTORY + "\\" + TEMP_TEX_FILE_NAME + ".tex", false); 
      writer.write(math, 0, math.length()); 
      writer.close(); 
     } catch (IOException ex) { 
      ex.printStackTrace(); 
     } 

     // 3. Execute LaTeX from command line to generate picture 
     ProcessBuilder pb = new ProcessBuilder("pdflatex", "-shell-escape", TEMP_TEX_FILE_NAME + ".tex"); 
     pb.directory(new File(TEMP_DIRECTORY)); 
     try { 
      Process p = pb.start(); 
      StreamPrinter fluxSortie = new StreamPrinter(p.getInputStream(), false); 
      StreamPrinter fluxErreur = new StreamPrinter(p.getErrorStream(), false); 
      new Thread(fluxSortie).start(); 
      new Thread(fluxErreur).start(); 
      p.waitFor(); 
     } catch (IOException | InterruptedException ex) { 
      ex.printStackTrace(); 
     } 

     // 4. Display picture 
     JFrame maFrame = new JFrame(); 
     maFrame.setResizable(false); 
     maFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     maFrame.setSize(400, 400); 
     maFrame.getContentPane().setLayout(new FlowLayout()); 
     maFrame.getContentPane().add(new JLabel(new ImageIcon(TEMP_DIRECTORY + "\\" + TEMP_TEX_FILE_NAME + ".png"))); 
     maFrame.pack(); 
     maFrame.setVisible(true); 

     // 5. Delete files 
     for (File file : (new File(TEMP_DIRECTORY).listFiles())) { 
      if (file.getName().startsWith(TEMP_TEX_FILE_NAME + ".")) { 
       file.delete(); 
      } 
     } 
    } 
} 

上述代碼應創建下面框架: enter image description here

尼古拉斯