|
|
@@ -75,7 +75,7 @@ public class PdfServiceImpl implements PdfService {
|
|
|
private String grapecityUrl;
|
|
|
|
|
|
@Override
|
|
|
- public byte[] addPageNumbersToPdf(byte[] pdfBytes) throws IOException {
|
|
|
+ public byte[] addPageNumbersToPdf(byte[] pdfBytes, int skipPages) throws IOException {
|
|
|
try (ByteArrayInputStream inputStream = new ByteArrayInputStream(pdfBytes);
|
|
|
ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
|
|
|
|
|
|
@@ -83,7 +83,13 @@ public class PdfServiceImpl implements PdfService {
|
|
|
|
|
|
int totalPages = document.getNumberOfPages();
|
|
|
|
|
|
- // 预加载字体,避免在循环中重复加载
|
|
|
+ // 容错:跳过页码大于或等于总页码时,直接返回原文件
|
|
|
+ if (skipPages >= totalPages) {
|
|
|
+ document.close();
|
|
|
+ return pdfBytes;
|
|
|
+ }
|
|
|
+
|
|
|
+ // 预加载字体
|
|
|
PDType0Font songtiFont = null;
|
|
|
try {
|
|
|
InputStream resourceAsStream = WordToPdfUtils.class.getClassLoader().getResourceAsStream("fonts/simsun.ttf");
|
|
|
@@ -96,7 +102,9 @@ public class PdfServiceImpl implements PdfService {
|
|
|
throw new IOException("加载宋体字体失败: " + e.getMessage(), e);
|
|
|
}
|
|
|
|
|
|
- for (int i = 0; i < totalPages; i++) {
|
|
|
+ int numberedTotal = totalPages - skipPages;
|
|
|
+
|
|
|
+ for (int i = skipPages; i < totalPages; i++) {
|
|
|
PDPage page = document.getPage(i);
|
|
|
try (PDPageContentStream contentStream = new PDPageContentStream(document, page,
|
|
|
PDPageContentStream.AppendMode.APPEND, true, true)) {
|
|
|
@@ -107,9 +115,8 @@ public class PdfServiceImpl implements PdfService {
|
|
|
|
|
|
// 设置页码位置(右下角)
|
|
|
float pageWidth = page.getMediaBox().getWidth();
|
|
|
-
|
|
|
- contentStream.newLineAtOffset(pageWidth / 2 - 50, 20); // 距离右边50,底部20
|
|
|
- contentStream.showText(String.format("第 %d 页 共 %d 页", i + 1, totalPages));
|
|
|
+ contentStream.newLineAtOffset(pageWidth / 2 - 50, 20);
|
|
|
+ contentStream.showText(String.format("第 %d 页 共 %d 页", i - skipPages + 1, numberedTotal));
|
|
|
contentStream.endText();
|
|
|
}
|
|
|
}
|