~
~
:wq

Showing posts with label pdf. Show all posts
Showing posts with label pdf. Show all posts

Saturday, 23 January 2010

Counting pages

spanish version - all english posts

We have an application that generates PDF reports from rst formated text files. One of the requirements that the applicaction should have is the numbering of pages in the format "Page X of Y". Unfortunaltely our application is an implemetation of rst2pdf 0.11 which doesn't have shuch feature (at least in the version we have). Although it wouldn't be too complex to implement it by modifying the code of python-docutils, this goes against my principles: Packages should be maintained by their developers at first instance, and by the distro packagers at second stage (in this case Ubuntu LTS 8.04). As an administrator I do not like altering this policy because then we must be aware of future security updates that may break things when our changes will be overriden.

I'm a bash guy, hence I always tend to prototype using the shell. So here is a quick way to implement a method to count the total pages of a PDF document w/o installing any specific tool.

Total PDF pages obtained by grep:

hmontoliu@blogspot:/tmp$ grep -c --binary-files=text '/Page\b' foo.pdf
818

Of course the package xpdf-utils includes the command "pdfinfo" which reports the number of pages in a document; but again, if you can avoid installing extra packages on a server much better.

The avobe command also applies to ps documents with minor modifications:

hmontoliu@blogspot:/tmp$ grep -c '%%Page' bar.ps
5

More information at "man grep" :-)

Implementing this simple grep in python as a call to the shell or doing a grep-like stuff through re or string.count('text') is trivial; for example:

In [1]: with open('/tmp/foo.pdf','rb') as f:
   ...:     f.read().count('/Page>')
   ...:
   ...: 

Out[1]: 818

Contando páginas

english version - all spanish posts

Tenemos una aplicación que genera informes en PDFs a partir de ficheros con formato rst. Uno de los requisitos que debía tener la aplicación es la numeración de páginas de tipo "página X de Y". Lamentablemente se trata de una implementación a partir de rst2pdf 0.11 que de momento no incorpora esa característica (al menos en la versión que tenemos). Aunque no sería demasiado complejo implementarla modificando el código de python-docutils esto va en contra de mis principios: Los paquetes los deben mantener primero sus desarrolladores y en segunda instancia la distribución de turno; en este caso Ubuntu LTS 8.04. Como administrador no me gusta alterar esta política pues luego hay que estar pendiente de qué se rompe o se deja de romper con las actualizaciones de seguridad.

Como las cabras que tiran al monte, yo siempre tiro a la shell para «prototipar». Así que aquí va un método rápido de implementar que permite contar el total de páginas de un PDF sin herramientas específicas.

Páginas de un documento PDF obtenidas con grep:

hmontoliu@blogspot:/tmp$ grep -c --binary-files=text '/Page\b' foo.pdf
818

Por supuesto el paquete xpdf-utils incluye el comando "pdfinfo" que informa del número de páginas de un documento; pero, nuevamente, si se puede evitar la instalación de paquetes extra en un servidor mucho mejor.

El anterior grep nos vale también para documentos PS con mínimas modificaciones:

hmontoliu@blogspot:/tmp$ grep -c '%%Page' bar.ps
5

Mas información en man grep :-)

Implementar este sencillo grep en python como llamada a la shell o haciendo un grep-like directamente con python mediante re o con un cadena.count('texto') es trivial; por ejemplo:

In [1]: with open('/tmp/foo.pdf','rb') as f:
   ...:     f.read().count('/Page>')
   ...:
   ...: 

Out[1]: 818