在LaTeX样式表中自动设置PDF标题和作者

32

我使用下面的代码设置pdf文档属性中的标题和作者。

\usepackage[pdftex]{hyperref}
\hypersetup{
    pdftitle = {The documents title},
    pdfauthor = {me}
}

我想通过放在一个样式表(.sty)中来自动化这个过程。以下是我的尝试,但它没有起作用。使用pdflatex编译pdf时会出现错误。但是pdf文档属性仍保持为空。

\usepackage[pdftex]{hyperref}
\hypersetup{
    pdftitle = {\@title},
    pdfauthor = {\@author}
}

我使用\@title和\@author变量创建自定义的标题页,所以我知道它们是有效的。

有什么建议吗?

2个回答

33

如果你遇到编译错误,我猜想问题可能出在@字符上。你需要用\makeatletter\makeatother将你的代码包装起来。另一个可能的问题是,你在执行\title\author命令之前这样做。一个好的解决方法是使用\AtBeginDocument,这将允许你将其放置在导言区的任何位置。请注意,在\begin{document}之前必须定义\title\author信息。

\documentclass{article}
\usepackage[pdftex]{hyperref}

\makeatletter
\AtBeginDocument{
  \hypersetup{
    pdftitle = {\@title},
    pdfauthor = {\@author}
  }
}
\makeatother

\title{Test title}
\author{Sam Author}

\begin{document}
\maketitle
\end{document}

更新: 将相关部分放入名为xxx.sty的样式文件中:

\NeedsTeXFormat{LaTeX2e}
\ProvidesPackage{xxx}
\RequirePackage{hyperref}

\makeatletter
\AtBeginDocument{
  \hypersetup{
    pdftitle = {\@title},
    pdfauthor = {\@author}
  }
}
\makeatother

当您将解决方案放在主TeX文件中时,它可以正常工作。但是,当您将其放在.sty文件中时,它无法正常工作。 - Thierry
@Thierry:我没有问题将这个放在.sty文件中。 - grddev
经过您的更新,一切都运行良好。感谢您的回答。 - Thierry
如果在.sty文件中使用\makeatother,会不会引起问题?我建议从.sty版本中删除\makeatletter\makeatother,因为它们在那里并不需要。 - Scz

10

我们能把这个改成被接受的答案吗? - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接