0

この前の質問に続いて、R チャンク内で R コマンド (dvi、dvips など) を使用して、スターゲイザー(要約統計テーブルのラテックス コード)の出力を最初に png に変換できると考えました。最悪の場合、システムコマンドを呼び出し(この投稿を参照)、次のようなコマンドを使用して、生成されたpngをRmdファイルにインポートします

![alt text](summary_lm.png)

これは可能だと思いますか?運がなかったので、やり方を教えていただけませんか?

4

1 に答える 1

6

タグを使用しobjectて PDF ファイルを HTML ファイルに埋め込むことができます (ただし、すべての Web ブラウザーでサポートされているわけではありません)。

注意点の 1 つは、LaTeX で生成される PDF ファイルのサイズを事前に設定する必要があることです。ただし、表を表示するには、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 )
于 2013-02-12T23:01:47.773 に答える