Setting pdftitle and pdfauthor automatically in a LaTeX stylesheet
Asked Answered
S

2

32

I use the code below to set the title and author in the pdf document properties.

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

I would like to automate this by putting it in a stylesheet (.sty) Below is my attempt, but it is not working. The pdf is compiled (pdflatex) with errors. But the pdf document properties remain empty.

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

I use the \@title and the \@author variables to create a custom titlepage. So I know those work.

Any suggestions?

Suwannee answered 2/8, 2010 at 12:59 Comment(0)
A
34

If you get compile errors, I'm guessing the problem is the @ character. You need to wrap your code in \makeatletter and \makeatother. Another possible problem is that you do this before you execute the \title and \author commands. A nice fix for this would be to use \AtBeginDocument, which would allow you to place this anywhere in your preamble. Note that you have to define the \title and \author information before \begin{document}.

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

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

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

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

UPDATE: Putting the relevant parts in a style file named xxx.sty:

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

\makeatletter
\AtBeginDocument{
  \hypersetup{
    pdftitle = {\@title},
    pdfauthor = {\@author}
  }
}
\makeatother
Appreciate answered 7/8, 2010 at 10:10 Comment(4)
Your solution works fine when put in the main tex file. However, it does not work when you put it in a .sty file.Suwannee
@Thierry: I have no problems putting this in a .sty file.Appreciate
After your update, everything works fine. Thank you for the answer.Suwannee
Wouldn't \makeatother provoke problems if used in a .sty file? I would suggest removing \makeatletter and \makeatother from the .sty version, as they are not needed there, anyways.Unroot
C
12

There is the package option pdfusetitle for it, see Make hyperref take pdfinfo from \title and \author.

Cryan answered 2/1, 2016 at 15:33 Comment(1)
Can we change this to the accepted answer?Animadversion

© 2022 - 2024 — McMap. All rights reserved.