2010-07-15 240 views
5

我想要生成一些LaTeX代碼,從那裏應該生成PDF文檔。 目前,我使用Django模板系統來動態創建代碼,但我不知道如何從這裏繼續。我知道我可以將代碼保存在.tex文件中,並使用子進程運行pdflatex來生成PDF。但是我在使用「普通」Python時逃避了LaTeX代碼的麻煩,所以我決定使用Django模板系統。有沒有一種方法可以將Django生成的輸出傳遞給pdflatex?生成的代碼工作正常,只是我不知道如何處理它。如何以編程方式使用LaTeX生成PDF?

在此先感謝

回答

5

我解決同樣的問題在一個項目中,我曾經工作且,而不是管道輸出,我在一個臨時文件夾中創建的臨時文件,因爲我很擔心處理中間上LaTeX生成的文件。這是我使用的代碼(請注意,從我剛剛成爲Python/Django時起,這已經過了幾年了;如果我今天編寫這個代碼,我相信我能想出更好的東西,但這對我來說確實有效):

import os 
from subprocess import call 
from tempfile import mkdtemp, mkstemp 
from django.template.loader import render_to_string 
# In a temporary folder, make a temporary file 
tmp_folder = mkdtemp() 
os.chdir(tmp_folder)   
texfile, texfilename = mkstemp(dir=tmp_folder) 
# Pass the TeX template through Django templating engine and into the temp file 
os.write(texfile, render_to_string('tex/base.tex', {'var': 'whatever'})) 
os.close(texfile) 
# Compile the TeX file with PDFLaTeX 
call(['pdflatex', texfilename]) 
# Move resulting PDF to a more permanent location 
os.rename(texfilename + '.pdf', dest_folder) 
# Remove intermediate files 
os.remove(texfilename) 
os.remove(texfilename + '.aux') 
os.remove(texfilename + '.log') 
os.rmdir(tmp_folder) 
return os.path.join(dest_folder, texfilename + '.pdf') 

dest_folder變量通常被設置在媒體目錄裏,這樣PDF隨後可以靜態地提供。返回的值是磁盤上文件的路徑。它的URL的邏輯將由dest_folder的任何函數來處理。

+0

謝謝!但我仍然有一個問題。它會以某種方式在現有文件上使用模板引擎嗎?那麼,它會正確地改變變量?我可以寫一個適當的tex文件。 Atm我有存儲在文件中的模板系統sytanx中的代碼。 – 2010-07-16 15:12:04

+1

我不確定我是否完全遵循了你的問題,但在上面的例子中,「tex/base.tex」是模板目錄中的一個TeX文件,其中也包含Django模板標籤/過濾器,當它通過'render_to_string()'時。如果你想加載任何舊文件(來自模板目錄之外),你可以這樣做:'t = Template(open('/ path/to/your/file.tex')。read()); os.write(texfile,t.render(Context({'var':'whatever'}))'如果你想寫入特定的地方,請執行:'os.write(open('/ path/to/new/file.tex','w')。fileno(),t.render(...))'。 – 2010-07-16 15:34:44

+0

好吧,我錯誤地理解了你的代碼,現在沒關係:D。處理一個奇怪的bug atm,不知道它是否相關。 – 2010-07-16 15:59:12