Php pdf page count

Подсчитайте количество страниц в PDF только в PHP

Мне нужен способ подсчитать количество страниц PDF в PHP. Я сделал немного Googling, и единственные вещи, которые я нашел, либо используют сценарии shell / bash, perl, либо другие языки, но мне нужно что-то в родном PHP. Существуют ли какие-либо библиотеки или примеры того, как это сделать?

Вы можете использовать расширение ImageMagick для PHP. ImageMagick понимает PDF, и вы можете использовать команду identify для извлечения количества страниц. Функция PHP – это Imagick :: identImage () .

Если вы используете Linux, это намного быстрее, чем использование identify чтобы получить количество страниц (особенно с большим количеством страниц):

exec('/usr/bin/pdfinfo '.$tmpfname.' | awk \'/Pages/ \'', $output); 

Вам необходимо установить pdfinfo.

Я знаю, что это довольно старый … но если это актуально для меня сейчас, это может быть актуально и для других.

Я просто разработал этот метод получения номеров страниц, так как перечисленные здесь методы неэффективны и чрезвычайно медленны для больших PDF-файлов.

$im = new Imagick(); $im->pingImage('name_of_pdf_file.pdf'); echo $im->getNumberImages(); 

Кажется, это отлично работает для меня!

Я на самом деле пошел с комбинированным подходом. Поскольку у меня отключен exec на моем сервере, я хотел придерживаться решения на основе PHP, поэтому в итоге получилось:

function getNumPagesPdf($filepath) < $fp = @fopen(preg_replace("/\[(.*?)\]/i", "",$filepath),"r"); $max=0; while(!feof($fp)) < $line = fgets($fp,255); if (preg_match('/\/Count 8+/', $line, $matches))< preg_match('/2+/',$matches[0], $matches2); if ($max<$matches2[0]) $max=$matches2[0]; >> fclose($fp); if($max==0)< $im = new imagick($filepath); $max=$im->getNumberImages(); > return $max; > 

Если он не может понять, потому что нет меток Count, то он использует расширение php imagick. Причина, по которой я делаю двукратный подход, заключается в том, что последняя довольно медленная.

Вы можете попробовать fpdi (см. Здесь ), как вы можете видеть, когда вы устанавливаете исходный файл, вы возвращаете номера страниц.

 else < $max=0; while(!feof($fp)) < $line = fgets($fp,255); if (preg_match('/\/Count 4+/', $line, $matches))< preg_match('/8+/',$matches[0], $matches2); if ($max<$matches2[0]) $max=$matches2[0]; >> fclose($fp); echo 'There '.($max ?> 

Тег Count показывает количество страниц в разных узлах. Родительский узел имеет сумму других в своем теге Count, поэтому этот скрипт просто ищет max (то есть количество страниц).

function getNumPagesPdf($filepath) < $fp = @fopen(preg_replace("/\[(.*?)\]/i", "", $filepath), "r"); $max = 0; if (!$fp) < return "Could not open file: $filepath"; >else < while (!@feof($fp)) < $line = @fgets($fp, 255); if (preg_match('/\/Count 5+/', $line, $matches)) < preg_match('/1+/', $matches[0], $matches2); if ($max < $matches2[0]) < $max = trim($matches2[0]); break; >> > @fclose($fp); > return $max; > 

Это делает именно то, что я хочу:

Я просто разработал этот метод получения страниц в pdf-страницах … после того, как вы получили число страниц в pdf, я просто добавляю разрыв к тому, чтобы он не проходил в бесконечном цикле здесь …

это не использует воображение:

function getNumPagesInPDF($file) < //http://www.hotscripts.com/forums/php/23533-how-now-get-number-pages-one-document-pdf.html if(!file_exists($file))return null; if (!$fp = @fopen($file,"r"))return null; $max=0; while(!feof($fp)) < $line = fgets($fp,255); if (preg_match('/\/Count 8+/', $line, $matches))< preg_match('/5+/',$matches[0], $matches2); if ($max<$matches2[0]) $max=$matches2[0]; >> fclose($fp); return (int)$max; > 
$pdftext = file_get_contents($caminho1); $num_pag = preg_match_all("/\/Page\W/", $pdftext,$dummy); 

Использование только PHP может привести к установке сложных библиотек, перезапуску Apache и т. Д., И многие чистые PHP-пути (например, открытие потоков и использование регулярных выражений) являются неточными .

Включенный ответ – единственный быстрый и надежный способ, о котором я могу думать. Он использует один исполняемый файл, хотя он не должен быть установлен (либо * nix, либо Windows), и простой PHP-скрипт извлекает результат. Лучше всего, что я еще не видела неправильной настройки!

Его можно найти здесь, в том числе, почему другие подходы «не работают» :

Получить количество страниц в документе PDF

В среде * nix вы можете использовать:

exec('pdftops ' . $filename . ' - | grep showpage | wc -l', $output); 

Где pdftops должен быть установлен по умолчанию.

Или, как предложил Xethron:

pdfinfo filename.pdf | grep Pages: | awk '' 

Источник

PHP Count Number of Pages in PDF File

In this post, i will give you simple example of how to get number of pages in pdf file using php. If you need to get number of pages in pdf using php then i will help you php count number of pages in pdf.

Sometime, we just need to count how many pages are there in pdf file and show it for our admin pane or front-end. So i will give you very simple example of getting calculate number of pages in pdf file using core php. you can also use in php, laravel, codeigniter framework too.

In this example we will create countPages() and it will take a one argument as path of pdf file. so just see bellow example for your solution.

Make Sure you have itsolutionstuff_file.pdf file in your pdf folder.

$path = ‘pdf/itsolutionstuff_file.pdf’;

$totoalPages = countPages($path);

echo $totoalPages;

function countPages($path)

$pdftext = file_get_contents($path);

$num = preg_match_all(«/\/Page\W/», $pdftext, $dummy);

return $num;

>

?>

Hardik Savani

I’m a full-stack developer, entrepreneur and owner of Aatman Infotech. I live in India and I love to write tutorials and tips that can help to other artisan. I am a big fan of PHP, Laravel, Angular, Vue, Node, Javascript, JQuery, Codeigniter and Bootstrap from the early stage. I believe in Hardworking and Consistency.

We are Recommending you

  • PHP Get All Array Keys Starting with Certain String Example
  • How to Convert XML File to Array in PHP?
  • PHP Move File from One Folder to Another Example
  • How to Partially Hide Email Address in PHP?
  • How to Get Difference Between Two Dates in PHP?
  • Laravel 6 Generate PDF File Tutorial
  • How to Remove Multiple Keys from PHP Array?
  • Laravel Merge Multiple PDF Files Example
  • PHP MySQL DataTables Server-side Processing Example
  • Convert HTML to PDF in PHP with Dompdf Example
  • PHP Capture Screenshot of Website from URL Example
  • How to Convert Object into Array in PHP?
  • How to Count Number of Files in a Directory in PHP?
  • How to Remove Null Values from Array in PHP?

Источник

Total PDF Pages Count in PHP Tutorial

Inside this article we will see the concept of counting total pdf pages in php. Article contains classified information which provides total pdf pages count in PHP.

If you are looking for an article which makes you understand to count total pdf pages in PHP then you are at right place to get it.

Sometime, you just need to count how many pages are there in a pdf file and show it for admin panel or front-end. So this article give you very simple example of getting calculate number of pages in pdf file using core php. But you can also use the same concept in php, laravel, codeigniter framework too.

Create an Application – PDF Pages Count

Create a folder with name pdf-page-count at your localhost directory.

Create a file index.php inside this. Consider few PDF files in this folder for understanding.

Folder contains these files –

Open index.php and write this complete code into it.

"; $sample_pdf2_path = 'sample-pdf-file.pdf'; $total_pdf2_Pages = countPages($sample_pdf2_path); echo "PDF 2 Pages: ".$total_pdf2_Pages; // Function to count total number of pages in pdf file function countPages($path) < $pdftext = file_get_contents($path); $num = preg_match_all("/\/Page\W/", $pdftext, $dummy); return $num; >

Concept to count total pdf pages –

// Function to count total number of pages in pdf file function countPages($path) < $pdftext = file_get_contents($path); $num = preg_match_all("/\/Page\W/", $pdftext, $dummy); return $num; >
$total_pdf_Pages = countPages($sample_pdf_path);

Application Testing

Open URL – http://localhost/pdf-page-count/index.php

We hope this article helped you to learn Total PDF Pages Count in PHP Tutorial in a very detailed way.

Online Web Tutor invites you to try Skillshike! Learn CakePHP, Laravel, CodeIgniter, Node Js, MySQL, Authentication, RESTful Web Services, etc into a depth level. Master the Coding Skills to Become an Expert in PHP Web Development. So, Search your favourite course and enroll now.

If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.

Источник

Читайте также:  Clear all javascript variables
Оцените статью