chemfig化學式轉換為pdf


SMILES 與 chemfig

針對化學分子結構,可以用SMILES (用ASCII字符串明確描述分子結構的規范)來定義。

SMILES(Simplified molecular input line entry specification),簡化分子線性輸入規范,是一種用ASCII字符串明確描述分子結構的規范。SMILES由Arthur Weininger和David Weininger於20世紀80年代晚期開發,並由其他人,尤其是日光化學信息系統有限公司(Daylight Chemical Information Systems Inc.),修改和擴展

但是SMILES需要一定的化學基礎,而chemfig則是從圖形層面定義了一套規范,方便定義和顯示化學式。當然,SMILES可以方便的轉換到chemfig.

比如:

CN1C=NC2=C1C(=O)N(C(=O)N2C)C

可通過mol2chemfig進行轉換:

mol2chemfig -wz -i direct 'CN1C=NC2=C1C(=O)N(C(=O)N2C)C' > caffeine.tex

轉換后:

\chemfig{-[:138]N-[:84]=^[:156]N-[:228]=[:300](-[:240](-[:180]N(-[:240]%
)-[:120](-[:60]N(-[:120])-)=[:180]O)=[:300]O)-[:12]\phantom{N}}

chemfig 轉換為pdf

我們可以通過pdflatex(textlive的一個工具)來轉換tex為pdf:

拉取txtlive鏡像:

docker pull listx/texlive:2020
docker run -it --rm -v `pwd`:/app listx/texlive:2020 bash

公司內部可以使用鏡像:hub.iflytek.com/ainote/texlive:2020

然后用pdflatex轉換。首先,我們生成一個tex文件test.tex,一個空tex文件,使用mol2chemfig(可從mol2chemfig下載),中間放上\chemfig{H_3C-[:30]N**6(-(=O)-(**5(-N(-CH_3)--N-))--N(-CH_3)-(=O)-)}

\documentclass{minimal}
\usepackage{xcolor, mol2chemfig}
\usepackage[margin=(margin)spt,papersize={%(width)spt, %(height)spt}]{geometry}

\usepackage[helvet]{sfmath}
\setcrambond{2.5pt}{0.4pt}{1.0pt}
\setbondoffset{1pt}
\setdoublesep{2pt}
\setatomsep{%(atomsep)spt}
\renewcommand{\printatom}[1]{\fontsize{8pt}{10pt}\selectfont{\ensuremath{\mathsf{#1}}}}

\setlength{\parindent}{0pt}
\setlength{\fboxsep}{0pt}
\begin{document}
\vspace*{\fill}
\vspace{-8pt}
\begin{center}

\chemfig{H_3C-[:30]N**6(-(=O)-(**5(-N(-CH_3)--N-))--N(-CH_3)-(=O)-)}

\end{center}
\vspace*{\fill}
\end{document}

然后執行轉換:

pdflatex -interaction=nonstopmode  test.tex

等待1~2s,可以看到生成的pdf,打開:

PDF

如何返回給前端呢,可以讀取文件,然后轉換為base64,python代碼:

pdfstring = open('test.pdf').read()
encoded = base64.encodestring(pdfstring)
pdflink = "data:application/pdf;base64,{}".format(encoded)


感謝您的認真閱讀。

如果你覺得有幫助,歡迎點贊支持!

不定期分享軟件開發經驗,歡迎關注作者, 一起交流軟件開發:


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM