|
|
@@ -7,10 +7,13 @@ import org.apache.pdfbox.multipdf.PDFMergerUtility;
|
|
|
import org.apache.pdfbox.pdmodel.PDDocument;
|
|
|
import org.apache.pdfbox.pdmodel.PDPage;
|
|
|
import org.apache.pdfbox.pdmodel.PDPageContentStream;
|
|
|
+import org.apache.pdfbox.pdmodel.font.PDFont;
|
|
|
+import org.apache.pdfbox.pdmodel.font.PDType0Font;
|
|
|
|
|
|
import java.io.ByteArrayInputStream;
|
|
|
import java.io.ByteArrayOutputStream;
|
|
|
import java.io.IOException;
|
|
|
+import java.io.InputStream;
|
|
|
|
|
|
/**
|
|
|
* PDF 合并工具类:将模板 PDF 与 manualUrl 对应的附件合并,并添加页间分割线
|
|
|
@@ -67,6 +70,13 @@ public class PdfMergeUtils {
|
|
|
log.error("[buildInspectionPlanPdf] 添加页间分割线失败: {}", e.getMessage());
|
|
|
}
|
|
|
|
|
|
+ // 添加页码(排除第一页)
|
|
|
+ try {
|
|
|
+ mergedBytes = addPageNumbers(mergedBytes);
|
|
|
+ } catch (Exception e) {
|
|
|
+ log.error("[buildInspectionPlanPdf] 添加页码失败: {}", e.getMessage());
|
|
|
+ }
|
|
|
+
|
|
|
return mergedBytes;
|
|
|
}
|
|
|
|
|
|
@@ -94,4 +104,50 @@ public class PdfMergeUtils {
|
|
|
return outputStream.toByteArray();
|
|
|
}
|
|
|
}
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 为 PDF 添加页码(排除第一页),格式:第X页 共X页
|
|
|
+ */
|
|
|
+ private static byte[] addPageNumbers(byte[] pdfBytes) throws IOException {
|
|
|
+ try (PDDocument document = PDDocument.load(new ByteArrayInputStream(pdfBytes))) {
|
|
|
+ // 加载中文字体
|
|
|
+ PDFont font = loadChineseFont(document);
|
|
|
+
|
|
|
+ int totalPages = document.getNumberOfPages();
|
|
|
+ // 从第二页开始添加页码(index=1),第一页不添加。页码从 1 开始计数(总页数不含第一页)
|
|
|
+ int numberedTotal = totalPages - 1;
|
|
|
+ for (int i = 1; i < totalPages; i++) {
|
|
|
+ PDPage page = document.getPage(i);
|
|
|
+ try (PDPageContentStream contentStream = new PDPageContentStream(document, page,
|
|
|
+ PDPageContentStream.AppendMode.APPEND, true, true)) {
|
|
|
+ float pageWidth = page.getMediaBox().getWidth();
|
|
|
+ float fontSize = 9f;
|
|
|
+ // 页码位置:底部居中
|
|
|
+ float y = 28f;
|
|
|
+ String pageText = "第" + i + "页 共" + numberedTotal + "页";
|
|
|
+ float textWidth = font.getStringWidth(pageText) / 1000 * fontSize;
|
|
|
+ contentStream.beginText();
|
|
|
+ contentStream.setFont(font, fontSize);
|
|
|
+ contentStream.newLineAtOffset(pageWidth / 2 - textWidth / 2, y);
|
|
|
+ contentStream.showText(pageText);
|
|
|
+ contentStream.endText();
|
|
|
+ }
|
|
|
+ }
|
|
|
+ ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
|
|
|
+ document.save(outputStream);
|
|
|
+ return outputStream.toByteArray();
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 从 classpath 加载中文字体
|
|
|
+ */
|
|
|
+ private static PDFont loadChineseFont(PDDocument document) throws IOException {
|
|
|
+ InputStream fontStream = PdfMergeUtils.class.getClassLoader()
|
|
|
+ .getResourceAsStream("fonts/simsun.ttf");
|
|
|
+ if (fontStream != null) {
|
|
|
+ return PDType0Font.load(document, fontStream);
|
|
|
+ }
|
|
|
+ throw new IOException("未找到中文字体资源 fonts/simsun.ttf");
|
|
|
+ }
|
|
|
}
|