[Tex/LaTex] How to make text copy in PDF previewers ignore lineno line numbers

copy/pasteline-numberingpdfpdftexviewers

I'm using lineno for a document. I have it configured to put line numbers in the margins of the document. I generate PDF using pdflatex. Here's the problem: when people copy a region of text in a PDF previewer (Acrobat, or Mac OS X's Preview), the line numbers are included in the text that's copied. This leads to confusing text when they paste it into another document or application.

Is there a way to make it so that the line numbers are ignored when someone copies text from within a PDF previewer? I would like just the main text to be copied, not the line numbers.

Best Answer

Using a method similar to that proposed in How to make listings code correct copyable from PDF and with hyperlink, the following works (at least in Adobe Reader).

The accsupp package provides accessibility support for PDFs. By using the \BeginAccSupp and \EndAccSupp group, the line numbers can be typeset in the PDF, but actually replaced by an empty space {}. This is done by supplying the option ActualText={}. As such, a simple redefinition of the linenumber counter (the basic/standard counter providing the line numbers for lineno) printing mechanism \thelinenumber does the trick:

\documentclass{article}
\usepackage{lineno}% http://ctan.org/pkg/lineno
\usepackage{accsupp}% http://ctan.org/pkg/accsupp
\usepackage{lipsum}% http://ctan.org/pkg/lipsum

\renewcommand{\thelinenumber}{% Line number printing mechanism
  \BeginAccSupp{ActualText={}}\arabic{linenumber}\EndAccSupp{}%
}

\begin{document}
\linenumbers% Turn line numbering on

\lipsum[1-5]% Dummy text
\end{document}

enter image description here