【问题标题】:Insert values from a file in a latex document在 Latex 文档中插入文件中的值
【发布时间】:2015-03-16 13:31:19
【问题描述】:

如果有一个乳胶文档,我如何从文件中读取一些键值对并将它们插入到文档中?

类似这样的:

乳胶代码:

customer ID: ${customerID}

文本文件:

customerID=123456

生成的 .pdf 文件应该包含客户 ID。

【问题讨论】:

    标签: pdf pdf-generation latex pdflatex


    【解决方案1】:

    我们总是可以编写一个 perl 脚本来扩展它们...

    defs.txt:

     customerID=123456
     customerTel=22530000000
    

    doc.tex:

    \documentclass{article}
    \begin{document}
    latex
    customer ID: ${customerID}
    and ${address} 
    costum telphone ID: ${customerTel}
    \end{document}
    

    perl 脚本 tex-defs:

    #!/usr/bin/perl -n
    
    BEGIN{$tex=0;}
    
    if(not $tex and /^(\w+)=(.*)/) { $v{$1}=$2 }
    if(/\\documentclass\{/       ) { $tex=1  }
    if($tex)                       { s/\$\{(\w+)\}/$v{$1} || "???$1"/ge; print }
    

    测试(在 chmod... 之后):

    $ tex-defs defs.txt doc.tex 
    \documentclass{article}
    \begin{document}
    latex
    customer ID: 123456
    and ???address
    costum telphone ID: 22530000000
    \end{document}
    

    【讨论】:

      【解决方案2】:

      如果您在保存为“data/foo.dat”的文件中有一些数据(例如您的 customerID),那么您可以在 .tex 文件中使用该值,如下所示:

      This is the customerID: \input{data/foo.dat}.
      

      然后pdf会显示

      This is the customerID: 123456.
      

      \input 命令只是插入您提供的文件中的任何内容。我不太确定如何使键值对工作,但也许您可以这样做,以便将所需的值存储在以“键”作为文件名的文件中。如果您将这些文件放在某个子文件夹中,它不会弄乱您的工作目录,并且可能是存储数据的好地方。

      【讨论】:

        【解决方案3】:

        只需在序言中使用以下代码导入 .dat 文件:

        % package to open file containing variables
        \usepackage{datatool, filecontents}
        \DTLsetseparator{,}% Set the separator between the columns.
        
        % import data
        \DTLloaddb[noheader, keys={thekey,thevalue}]{mydata}{../mydata.dat}
        % Loads mydata.dat with column headers 'thekey' and 'thevalue'
        \newcommand{\var}[1]{\DTLfetch{mydata}{thekey}{#1}{thevalue}}
        

        请注意,在此示例中,keysvalues 使用逗号分隔。我的 .dat 文件如下所示:

        number_participants,21
        total_score,32.55
        

        然后在您的 LaTeX 文档正文中使用以下命令引用变量:\var{variable_name}

        更多信息请关注this video

        【讨论】:

          猜你喜欢
          • 2011-02-13
          • 1970-01-01
          • 1970-01-01
          • 2011-03-11
          • 2012-10-03
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多