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);
|
}
|
}
|