LaTeX到png的转换

时间:2013-02-12 07:53:08

标签: windows r latex png converter

关注this previous question,我想我可以先将stargazer(摘要统计表的乳胶代码)的输出转换为png,使用R命令(如dvi,dvips,...) R chunk,或者在最坏的情况下,调用系统命令(请参阅此post),然后使用像

这样的命令将生成的png导入到我的Rmd文件中
![alt text](summary_lm.png)

你认为这是可能的吗?你能告诉我怎么做,因为我没有运气吗?

1 个答案:

答案 0 :(得分:6)

您可以使用object标记嵌入PDF文件 在HTML文件中 (但并非所有Web浏览器都支持它。)

一个棘手的问题是,生成的PDF文件的大小 LaTeX必须提前设定;但是,要显示一张桌子,你可以 如果PDF文件的大小恰好与表格相同,则更喜欢 避免大的空边距和/或滚动条。 您可以使用GhostScript裁剪PDF文件。

这是一个例子。

# Sample data
library(stargazer)
example(stargazer)
code <- .Last.value$value

# Generate the LaTeX file
file <- tempfile("latex_", fileext = "")
tex_file  <- paste( file, "tex",  sep="." )
pdf_file  <- paste( file, "pdf",  sep="." )
pdf_file2 <- paste( file, "_cropped.pdf",  sep="" )
png_file  <- paste( file, "png",  sep="." )
html_file <- paste( file, "html", sep="." )
cat( 
  "\\documentclass{report}",
  # Unreasonably tall page size: we want everything on the same page
  "\\usepackage[paperwidth=10cm,paperheight=100cm,noheadfoot,margin=0in]{geometry}",
  "\\begin{document}",
  "\\pagestyle{empty}", 
  paste(code, collapse="\n"),
  "\\end{document}\n", 
  sep="\n",
  file = tex_file
)

# Generate the PDF file
old_wd <- getwd()
setwd( tempdir() )
system(paste( "pdflatex --interaction=nonstopmode", shQuote(tex_file) ))

# We need to crop the file.
# I will use Ghostscript, but you could also use
#   http://pdfcrop.sourceforge.net/
# or
#   http://www.ctan.org/tex-archive/support/pdfcrop
# First, find the dimensions 
bbox <- system(paste( "gs -sDEVICE=bbox -dNOPAUSE -dBATCH -f", pdf_file, "2>&1" ), intern=TRUE)
bbox <- bbox[ grep("%%BoundingBox", bbox) ]
bbox <- as.numeric( strsplit(bbox, " ")[[1]][-1] )
# Then, crop the file
cmd <- paste( 
  "gs -sDEVICE=pdfwrite",
  "-o", pdf_file2, 
  "-c \"[/CropBox [", paste(bbox, collapse=" "), "] /PAGES pdfmark\"",
  "-f", pdf_file 
)
system(cmd)

# Convert it to PNG, in case the browser cannot display inline PDF files.
# This assumes that ImageMagick is installed.
# You may want to play with the options to have a better quality and/or larger file.
system(paste( "convert", "-trim", "-density 400", pdf_file2, "-resize 50%", png_file ))

# You can now include it in an HTML file 
# (or a Markdown file, since you can include raw HTML).
cat(
  "<html><body><p>Here is an embedded PDF file.</p>\n",
  "<object width='100%' height='100%' type='application/pdf' data='", pdf_file2, "'>",
  "<img src='", png_file, "'/>",
  "</object>\n",
  "</body></html>",
  sep="",
  file=html_file
)

# Check that the result can be displayed in your browser
# (Chrome should be fine, but I have not had any success with the others.)
browseURL( html_file )