Determinar el número de páginas en un archivo PDF [cerrado]


Necesito determinar el número de páginas en un archivo PDF especificado usando código C# (. NET 2.0). El archivo PDF se leerá desde el sistema de archivos, y no desde una URL. ¿Alguien tiene algún consejo sobre cómo se podría hacer esto? Nota: Adobe Acrobat Reader está instalado en el PC donde se realizará esta comprobación.

Author: slugster, 2008-11-26

9 answers

Necesitará una API PDF para C#. iTextSharp es una API posible, aunque podrían existir otras mejores.

Ejemplo iTextSharp

Debe instalar iTextSharp.dll como referencia. Descargar iTextSharp desde SourceForge.net Este es un programa de trabajo completo que utiliza una aplicación de consola.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using iTextSharp.text.pdf;
using iTextSharp.text.xml;
namespace GetPages_PDF
{
  class Program
{
    static void Main(string[] args)
      {
       // Right side of equation is location of YOUR pdf file
        string ppath = "C:\\aworking\\Hawkins.pdf";
        PdfReader pdfReader = new PdfReader(ppath);
        int numberOfPages = pdfReader.NumberOfPages;
        Console.WriteLine(numberOfPages);
        Console.ReadLine();
      }
   }
}
 61
Author: darkdog,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-04-19 06:14:56

Esto debería hacer el truco:

public int getNumberOfPdfPages(string fileName)
{
    using (StreamReader sr = new StreamReader(File.OpenRead(fileName)))
    {
        Regex regex = new Regex(@"/Type\s*/Page[^s]");
        MatchCollection matches = regex.Matches(sr.ReadToEnd());

        return matches.Count;
    }
}

De La respuesta de Rachael y esta también.

 35
Author: Barrett,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 11:54:38

Encontró una manera en http://www.dotnetspider.com/resources/21866-Count-pages-PDF-file.aspx esto no requiere la compra de una biblioteca pdf

 6
Author: ,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-02-27 16:24:14

He usado pdflib para esto.

    p = new pdflib();

    /* Open the input PDF */
    indoc = p.open_pdi_document("myTestFile.pdf", "");
    pageCount = (int) p.pcos_get_number(indoc, "length:pages");
 4
Author: Peter Gfader,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-01-11 07:59:28

Docótico.La biblioteca Pdf se puede usar para realizar la tarea.

Aquí está el código de ejemplo:

PdfDocument document = new PdfDocument();
document.Open("file.pdf");
int pageCount = document.PageCount;

La biblioteca analizará lo menos posible, por lo que el rendimiento debería estar bien.

Descargo de responsabilidad: Trabajo para Bit Miracle.

 2
Author: Bobrovsky,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-10-05 15:43:22

Una línea:

int pdfPageCount = System.IO.File.ReadAllText("example.pdf").Split(new string[] { "/Type /Page" }, StringSplitOptions.None).Count()-2;

Recomendado: ITEXTSHARP

 2
Author: Medo Medo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-02-24 07:56:35

PDFsharp

Este debería ser mejor =)

 0
Author: darkdog,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2008-11-26 11:09:07

Tengo un buen éxito con los productos PDF dinámicos de CeTe. No son libres, pero están bien documentados. Hicieron el trabajo por mí.

Http://www.dynamicpdf.com/

 0
Author: Paul Lefebvre,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-01-09 14:29:42

He usado el código anterior que resuelve el problema usando regex y funciona, pero es bastante lento. Lee todo el archivo para determinar el número de páginas.

Lo utilicé en una aplicación web y las páginas a veces enumeraban 20 o 30 archivos PDF a la vez y en esa circunstancia el tiempo de carga de la página pasó de un par de segundos a casi un minuto debido al método de conteo de páginas.

No se si las bibliotecas de 3rd party son mucho mejores, espero que lo sean y he usado pdflib en otros escenarios con éxito.

 0
Author: ,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-02-02 19:07:29