package com.custom.webui.util;
|
|
import org.apache.pdfbox.pdmodel.PDDocument;
|
import org.apache.pdfbox.pdmodel.PDPage;
|
import org.apache.pdfbox.pdmodel.PDPageContentStream;
|
import org.apache.pdfbox.pdmodel.common.PDRectangle;
|
import org.apache.pdfbox.pdmodel.font.PDType0Font;
|
|
import java.io.Closeable;
|
import java.io.IOException;
|
import java.util.ArrayList;
|
import java.util.HashMap;
|
import java.util.List;
|
import java.util.Map;
|
|
/**
|
* 极简的 PDF 排版器:把一段段文字按 A4 页面排下来,自动换行、自动翻页、带页码。
|
*
|
* <h2>为什么不用现成的排版库</h2>
|
* openhtmltopdf / iText 这类库都要额外引入依赖,而本项目只需要
|
* 「标题 + 元信息 + 若干条消息」这一种版式,自己画反而更可控,
|
* 也避免了为导出一个功能背上几 MB 的依赖和许可证问题。
|
*
|
* <h2>三个必须自己处理的细节</h2>
|
* <ol>
|
* <li><b>字形缺失</b>:字体里没有的字符(emoji、罕见符号)直接写进去会抛
|
* {@code IllegalArgumentException: No glyph for U+1F600},
|
* 整个导出就失败了。这里统一替换成 {@code □} 并缓存判断结果。</li>
|
* <li><b>换行</b>:中文没有空格,不能按单词断行。这里按**字符**宽度累加,
|
* 同时对「不能出现在行首」的标点(,。!?等)做悬挂处理,
|
* 避免出现「一行结尾孤零零一个逗号」。</li>
|
* <li><b>页码</b>:内容写完后才知道总页数,所以页码统一在
|
* {@link #close()} 里补画(用 APPEND 模式重新打开每一页)。</li>
|
* </ol>
|
*/
|
public class ChatPdfWriter implements Closeable {
|
|
private static final float PAGE_WIDTH = PDRectangle.A4.getWidth();
|
private static final float PAGE_HEIGHT = PDRectangle.A4.getHeight();
|
private static final float MARGIN = 56f;
|
private static final float CONTENT_WIDTH = PAGE_WIDTH - MARGIN * 2;
|
private static final float CURSOR_TOP = PAGE_HEIGHT - MARGIN;
|
private static final float CURSOR_BOTTOM = MARGIN + 12f;
|
|
/** 不允许出现在行首的标点(避头尾规则) */
|
private static final String NO_LINE_START = ",。、;:!?)》」』】…—·%℃";
|
|
/** 缺字形时的替代符 */
|
private static final char REPLACEMENT = '□';
|
|
private final PDDocument document;
|
private final PdfFontSupport.PdfFontHandle handle;
|
private final PDType0Font font;
|
private final List<PDPage> pages = new ArrayList<>();
|
|
/** 码位 -> 字体里有没有这个字形。判定要走 cmap 查询,缓存一下省时间 */
|
private final Map<Integer, Boolean> glyphCache = new HashMap<>();
|
|
private PDPageContentStream stream;
|
private float cursorY;
|
private boolean finished;
|
|
public ChatPdfWriter(PDDocument document, PdfFontSupport.PdfFontHandle handle) throws IOException {
|
this.document = document;
|
this.handle = handle;
|
this.font = handle.font();
|
newPage();
|
}
|
|
// ------------------------------------------------------------------
|
// 对外的写入接口(按语义命名,比通用的 draw(text, size) 更能防止用错字号)
|
// ------------------------------------------------------------------
|
|
/** 文档标题 */
|
public void writeTitle(String text) throws IOException {
|
for (String line : wrap(text, 16f)) {
|
writeLine(line, 16f, 0.11f, 0.11f, 0.13f, 24f);
|
}
|
}
|
|
/** 元信息行(导出时间、消息数等),小字灰色 */
|
public void writeMeta(String text) throws IOException {
|
for (String line : wrap(text, 9f)) {
|
writeLine(line, 9f, 0.42f, 0.45f, 0.50f, 14f);
|
}
|
}
|
|
/** 消息头(「我 · 2026-10-09 10:32」这类) */
|
public void writeMessageHeader(String text) throws IOException {
|
for (String line : wrap(text, 10f)) {
|
// 与前一条消息留出间距,靠调用方保证「先 spacing 再 header」不稳妥,
|
// 这里统一在消息头之前多留 8pt
|
ensureSpace(8f + 16f + 14f);
|
cursorY -= 8f;
|
writeLine(line, 10f, 0.12f, 0.35f, 0.60f, 16f);
|
}
|
}
|
|
/** 正文段落,保留原有换行 */
|
public void writeParagraph(String text) throws IOException {
|
for (String line : wrap(text, 10.5f)) {
|
writeLine(line, 10.5f, 0.16f, 0.17f, 0.20f, 15.5f);
|
}
|
}
|
|
/** 一条分隔线(用于标题与正文之间) */
|
public void writeRule() throws IOException {
|
ensureSpace(12f);
|
stream.setNonStrokingColor(0.80f, 0.82f, 0.85f);
|
stream.addRect(MARGIN, cursorY - 4f, CONTENT_WIDTH, 0.8f);
|
stream.fill();
|
cursorY -= 12f;
|
}
|
|
/** 段落之间的空白 */
|
public void writeSpacing(float height) throws IOException {
|
ensureSpace(height);
|
cursorY -= height;
|
}
|
|
// ------------------------------------------------------------------
|
// 内部实现
|
// ------------------------------------------------------------------
|
|
private void writeLine(String text, float size, float r, float g, float b, float lineHeight)
|
throws IOException {
|
ensureSpace(lineHeight);
|
if (!text.isEmpty()) {
|
stream.setNonStrokingColor(r, g, b);
|
stream.beginText();
|
stream.setFont(font, size);
|
stream.newLineAtOffset(MARGIN, cursorY - size);
|
stream.showText(text);
|
stream.endText();
|
}
|
cursorY -= lineHeight;
|
}
|
|
/**
|
* 按宽度折行。
|
*
|
* <p>按**字符**而不是单词断行:中文没有词间空格,按单词断会得到一整段不断行的文本。
|
* 同时做两件小事:
|
* <ul>
|
* <li>原始文本里的换行/tab 得到保留(tab 展开成 4 个空格)</li>
|
* <li>不让「,。!?」这类标点出现在行首</li>
|
* </ul>
|
*/
|
private List<String> wrap(String raw, float size) {
|
List<String> lines = new ArrayList<>();
|
if (raw == null || raw.isEmpty()) {
|
lines.add("");
|
return lines;
|
}
|
|
for (String paragraph : sanitize(raw).split("\n", -1)) {
|
if (paragraph.isEmpty()) {
|
lines.add("");
|
continue;
|
}
|
StringBuilder current = new StringBuilder();
|
float width = 0f;
|
|
int i = 0;
|
while (i < paragraph.length()) {
|
int cp = paragraph.codePointAt(i);
|
String ch = new String(Character.toChars(cp));
|
float chWidth = widthOf(ch, size);
|
|
boolean overflow = width + chWidth > CONTENT_WIDTH && current.length() > 0;
|
// 避头尾:不因为标点而断行,宁可让它稍微出界(悬挂标点)
|
boolean isNoStart = ch.length() == 1 && NO_LINE_START.indexOf(ch.charAt(0)) >= 0;
|
|
if (overflow && !isNoStart) {
|
lines.add(current.toString());
|
current.setLength(0);
|
width = 0f;
|
}
|
current.append(ch);
|
width += chWidth;
|
i += Character.charCount(cp);
|
}
|
lines.add(current.toString());
|
}
|
return lines;
|
}
|
|
private float widthOf(String text, float size) {
|
try {
|
return font.getStringWidth(text) / 1000f * size;
|
} catch (IOException e) {
|
return size; // 估算即可,不该因为测量失败而中断导出
|
}
|
}
|
|
/**
|
* 清洗文本:控制字符、tab、以及**字体里没有的字符**。
|
*
|
* <p>字体缺字形这一点是必须处理的:Arial Unicode 这类字体覆盖了中日韩,
|
* 但不含 emoji(U+1F600 等)。PDFBox 遇到缺字形会抛异常,
|
* 表现就是「对话里有表情符号,整个 PDF 导出就失败」——
|
* 一个 emoji 毁掉整份导出,显然不可接受,所以替换成方框继续导。
|
*
|
* <p>字形判断走字体句柄的 cmap 查询,**不能**用
|
* {@code PDType0Font.hasGlyph()}:实测它对本该存在的全角逗号也会返回
|
* false,那样中文标点会被整片替换成方框(详见 {@link PdfFontSupport})。
|
*/
|
private String sanitize(String raw) {
|
StringBuilder sb = new StringBuilder(raw.length() + 16);
|
int i = 0;
|
while (i < raw.length()) {
|
int cp = raw.codePointAt(i);
|
i += Character.charCount(cp);
|
|
if (cp == '\r') {
|
continue;
|
}
|
if (cp == '\t') {
|
sb.append(" ");
|
continue;
|
}
|
if (cp != '\n' && Character.isISOControl(cp)) {
|
continue;
|
}
|
if (cp == '\n' || hasGlyph(cp)) {
|
sb.appendCodePoint(cp);
|
} else {
|
sb.append(REPLACEMENT);
|
}
|
}
|
return sb.toString();
|
}
|
|
private boolean hasGlyph(int codePoint) {
|
Boolean cached = glyphCache.get(codePoint);
|
if (cached != null) {
|
return cached;
|
}
|
boolean has = handle.hasGlyph(codePoint);
|
glyphCache.put(codePoint, has);
|
return has;
|
}
|
|
private void ensureSpace(float needed) throws IOException {
|
if (cursorY - needed < CURSOR_BOTTOM) {
|
newPage();
|
}
|
}
|
|
private void newPage() throws IOException {
|
if (stream != null) {
|
stream.close();
|
}
|
PDPage page = new PDPage(PDRectangle.A4);
|
document.addPage(page);
|
pages.add(page);
|
|
// compress=true 让内容流走 Flate 压缩;resetContext=true 保证每页图形状态独立
|
stream = new PDPageContentStream(document, page,
|
PDPageContentStream.AppendMode.APPEND, true, true);
|
cursorY = CURSOR_TOP;
|
}
|
|
@Override
|
public void close() throws IOException {
|
if (finished) {
|
return;
|
}
|
finished = true;
|
if (stream != null) {
|
stream.close();
|
stream = null;
|
}
|
writeFooters();
|
}
|
|
/**
|
* 补画页码。
|
*
|
* <p>必须在全部内容写完之后做:页码要落在「第 N 页 / 共 M 页」上,
|
* 而 M 只有写到最后才知道。用 APPEND 模式重新打开每一页的内容流即可。
|
*/
|
private void writeFooters() throws IOException {
|
int total = pages.size();
|
for (int index = 0; index < total; index++) {
|
String text = "第 " + (index + 1) + " 页 / 共 " + total + " 页";
|
float size = 8f;
|
float width = widthOf(text, size);
|
try (PDPageContentStream footer = new PDPageContentStream(
|
document, pages.get(index), PDPageContentStream.AppendMode.APPEND, true, true)) {
|
footer.setNonStrokingColor(0.62f, 0.65f, 0.70f);
|
footer.beginText();
|
footer.setFont(font, size);
|
footer.newLineAtOffset((PAGE_WIDTH - width) / 2f, MARGIN / 2f);
|
footer.showText(text);
|
footer.endText();
|
}
|
}
|
}
|
}
|