引入依赖
<!--pdf-->
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>pdfbox</artifactId>
<version>2.0.24</version>
</dependency>
代码工具类
package com.example.util;
import org.apache.pdfbox.pdmodel.PDDocument;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
/**
* PDF工具类
*/
public class PdfUtil {
/**
* 获取PDF文件的总页数
*
* @param pdfUrl
* @return
*/
public static int getPdfTotalPage(String pdfUrl) {
if (pdfUrl == null || "".equals(pdfUrl)) {
return 0;
}
int pages = 0;
URL url = null;
InputStream inputStream = null;
PDDocument pdDocument = null;
// 尝试打开文件流
try {
url = new URL(pdfUrl);
} catch (MalformedURLException e) {
e.printStackTrace();
}
if (url != null) {
try {
inputStream = url.openStream();
} catch (IOException e) {
e.printStackTrace();
}
}
// 读取pdf的页数
if (inputStream != null) {
try {
pdDocument = PDDocument.load(inputStream);
pages = pdDocument.getNumberOfPages();
} catch (IOException e) {
e.printStackTrace();
}
}
// 善后工作
if (pdDocument != null) {
try {
pdDocument.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return pages;
}
}
测试类
package com.example.util;
import org.junit.jupiter.api.Test;
import java.io.IOException;
public class PdfUtilTest {
@Test
public void getPdfTotalPage() throws IOException {
String pdfUrl = "https://pdf.dfcfw.com/pdf/H3_AP202402231623204056_1.pdf?1708699798000.pdf";
int pdfTotalPage = PdfUtil.getPdfTotalPage(pdfUrl);
System.out.println(pdfTotalPage); // 17
}
}