使用 Perl 按页数递增的顺序对多个 PDF 文件进行排序

Sort a number of PDF files in increasing order of page count using Perl

谁能提出一个逻辑,如何根据每个 PDF 文件的页数对文件夹中的 n 个 PDF 文件进行排序,并在文本文件中写出 PDF 文件的排序列表?

例如

file1.pdf - 50 pages
file2.pdf - 30 pages
file3.pdf - 75 pages
file4.pdf - 20 pages
.
.
file34.pdf - 7 pages
file35.pdf - 75 pages

将每个文件与其余文件进行比较和排序不是最佳解决方案。 我的另一个想法是用页数重命名文件并以某种方式对其进行排序以按排序顺序写出。

请建议是否有任何库可以执行此操作。我正在寻找基于 Perl 的解决方案。

使用 ImageMagick 的 identify 命令

identify -format "%n %f\n" *.pdf | sort -n

输出

16 a.pdf
29 b.pdf

或者使用 pdfinfo 可能更快:

for f in *.pdf; do
  pages=$(pdfinfo "$f" | awk '/Pages:/{print }')
  echo $pages $f
done | sort -n

我不明白为什么这是个问题 -- 这是一项非常微不足道的任务。你知道任何 Perl 吗?除非您有数万亿个 PDF 文件,否则无需担心效率,我不明白您所说的 "Comparison of each file with the rest and sorting is not an optimal solution".

是什么意思

我建议您安装 PDF::API2 以提取每个文档中的页数。然后只需要构建一个散列并对其进行排序即可。是否 "optimal" 无关紧要,因为它只需要一点时间。

这个示例程序展示了这个想法。我使用了我的 Windows 系统之一的文档目录。

use strict;
use warnings;
use 5.010;
use autodie;

use PDF::API2;
use List::Util 'max';

chdir '\\SAMURAI\C\ProgramData\Altova\SharedBetweenVersions\Apache FOP 1.1 JDK 1.4\docs.0';

my @files = glob '*.pdf';
my $width = max map length, @files;
my %page_counts;

for my $file (@files) {
  my $pdf = PDF::API2->open($file);
  $page_counts{$file} = $pdf->pages;
}

for my $file (sort { $page_counts{$a} <=> $page_counts{$b} } keys %page_counts) {
  printf "%-*s - %d pages\n", $width, $file, $page_counts{$file};
}

输出

index.pdf                - 2 pages
accessibility.pdf        - 3 pages
compiling.pdf            - 3 pages
releaseNotes_1.0.pdf     - 3 pages
pdfa.pdf                 - 3 pages
pdfx.pdf                 - 3 pages
upgrading.pdf            - 3 pages
anttask.pdf              - 4 pages
pdfencryption.pdf        - 4 pages
metadata.pdf             - 4 pages
hyphenation.pdf          - 5 pages
knownissues_overview.pdf - 5 pages
servlets.pdf             - 6 pages
running.pdf              - 6 pages
extensions.pdf           - 6 pages
intermediate.pdf         - 7 pages
events.pdf               - 8 pages
graphics.pdf             - 8 pages
configuration.pdf        - 9 pages
fonts.pdf                - 9 pages
changes_1.0.pdf          - 10 pages
embedding.pdf            - 11 pages
output.pdf               - 21 pages