刘光辉
4 小时以前 06f314545ac3514d7ce28939920866ae8188d31c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
package jnpf.dmsService;
 
import org.apache.pdfbox.Loader;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.springframework.stereotype.Service;
 
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Locale;
 
/**
 * Reads the intrinsic PDF page count.
 *
 * <p>Word must be paginated by OnlyOffice: its saved page-count property may be stale.</p>
 */
@Service
public class DmsDocumentPageCountService {
 
    public int getPageCount(Path file, String fileName) throws IOException {
        if (file == null || !Files.isRegularFile(file)) {
            throw new IOException("文件不存在或不是普通文件");
        }
        String resolvedFileName = fileName == null || fileName.trim().isEmpty()
                ? file.getFileName().toString() : fileName;
        switch (extension(resolvedFileName)) {
            case "pdf":
                return readPdfPageCount(file);
            case "doc":
            case "docx":
                throw new IOException("Word 文件页数必须通过 OnlyOffice 重新排版统计");
            default:
                throw new IOException("页数查询仅支持 doc、docx、pdf 文件");
        }
    }
 
    private int readPdfPageCount(Path file) throws IOException {
        try (PDDocument document = Loader.loadPDF(file.toFile())) {
            return document.getNumberOfPages();
        }
    }
 
    private String extension(String fileName) {
        int separator = fileName.lastIndexOf('.');
        return separator < 0 ? "" : fileName.substring(separator + 1).toLowerCase(Locale.ROOT);
    }
}