Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,14 @@

import com.itextpdf.io.font.PdfEncodings;
import com.itextpdf.kernel.colors.DeviceRgb;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.kernel.font.PdfFontFactory.EmbeddingStrategy;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Cell;
import com.itextpdf.layout.element.Paragraph;
import com.itextpdf.layout.element.Table;
import com.itextpdf.layout.font.FontProvider;
import com.itextpdf.layout.font.selectorstrategy.BestMatchFontSelectorStrategy.BestMatchFontSelectorStrategyFactory;
import com.itextpdf.layout.properties.TextAlignment;
import com.itextpdf.layout.properties.UnitValue;
import interview.guide.common.exception.BusinessException;
Expand Down Expand Up @@ -45,17 +44,29 @@ public class PdfExportService {
private final ObjectMapper objectMapper;

/**
* 创建支持中文的字体
* 使用中文字体,并为其缺少的带圈编号等字符提供内嵌回退字体。
*/
private PdfFont createChineseFont() {
try (var fontStream = getClass().getClassLoader().getResourceAsStream("fonts/ZhuqueFangsong-Regular.ttf")) {
private void configureFonts(Document document) {
FontProvider fontProvider = new FontProvider();
fontProvider.setFontSelectorStrategyFactory(new BestMatchFontSelectorStrategyFactory());
registerFont(fontProvider, "fonts/ZhuqueFangsong-Regular.ttf", "report-cjk");
registerFont(fontProvider, "fonts/NotoSansSymbols-Regular.ttf", "report-symbols");
document.setFontProvider(fontProvider);
document.setFontFamily("report-cjk", "report-symbols");
}

private void registerFont(FontProvider fontProvider, String resource, String alias) {
try (var fontStream = getClass().getClassLoader().getResourceAsStream(resource)) {
if (fontStream != null) {
byte[] fontBytes = fontStream.readAllBytes();
log.debug("使用项目内嵌字体: fonts/ZhuqueFangsong-Regular.ttf");
return PdfFontFactory.createFont(fontBytes, PdfEncodings.IDENTITY_H, EmbeddingStrategy.FORCE_EMBEDDED);
if (!fontProvider.getFontSet().addFont(
fontStream.readAllBytes(), PdfEncodings.IDENTITY_H, alias)) {
throw new BusinessException(ErrorCode.EXPORT_PDF_FAILED, "字体文件无效,请联系管理员");
}
log.debug("使用项目内嵌字体: {}", resource);
return;
}

log.error("未找到字体文件: fonts/ZhuqueFangsong-Regular.ttf");
log.error("未找到字体文件: {}", resource);
throw new BusinessException(ErrorCode.EXPORT_PDF_FAILED, "字体文件缺失,请联系管理员");

} catch (BusinessException e) {
Expand Down Expand Up @@ -85,8 +96,7 @@ public byte[] exportResumeAnalysis(ResumeEntity resume, ResumeAnalysisResponse a
Document document = new Document(pdfDoc);

// 使用支持中文的字体
PdfFont font = createChineseFont();
document.setFont(font);
configureFonts(document);

// 标题
Paragraph title = new Paragraph("简历分析报告")
Expand Down Expand Up @@ -170,8 +180,7 @@ public byte[] exportInterviewReport(InterviewSessionEntity session) {
Document document = new Document(pdfDoc);

// 使用支持中文的字体
PdfFont font = createChineseFont();
document.setFont(font);
configureFonts(document);

// 标题
Paragraph title = new Paragraph("模拟面试报告")
Expand Down
Binary file not shown.
94 changes: 94 additions & 0 deletions app/src/main/resources/fonts/OFL-NotoSansSymbols.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
Copyright 2018 The Noto Project Authors (github.com/googlei18n/noto-fonts)

This Font Software is licensed under the SIL Open Font License,
Version 1.1.

This license is copied below, and is also available with a FAQ at:
http://scripts.sil.org/OFL

-----------------------------------------------------------
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
-----------------------------------------------------------

PREAMBLE
The goals of the Open Font License (OFL) are to stimulate worldwide
development of collaborative font projects, to support the font
creation efforts of academic and linguistic communities, and to
provide a free and open framework in which fonts may be shared and
improved in partnership with others.

The OFL allows the licensed fonts to be used, studied, modified and
redistributed freely as long as they are not sold by themselves. The
fonts, including any derivative works, can be bundled, embedded,
redistributed and/or sold with any software provided that any reserved
names are not used by derivative works. The fonts and derivatives,
however, cannot be released under any other type of license. The
requirement for fonts to remain under this license does not apply to
any document created using the fonts or their derivatives.

DEFINITIONS
"Font Software" refers to the set of files released by the Copyright
Holder(s) under this license and clearly marked as such. This may
include source files, build scripts and documentation.

"Reserved Font Name" refers to any names specified as such after the
copyright statement(s).

"Original Version" refers to the collection of Font Software
components as distributed by the Copyright Holder(s).

"Modified Version" refers to any derivative made by adding to,
deleting, or substituting -- in part or in whole -- any of the
components of the Original Version, by changing formats or by porting
the Font Software to a new environment.

"Author" refers to any designer, engineer, programmer, technical
writer or other person who contributed to the Font Software.

PERMISSION & CONDITIONS
Permission is hereby granted, free of charge, to any person obtaining
a copy of the Font Software, to use, study, copy, merge, embed,
modify, redistribute, and sell modified and unmodified copies of the
Font Software, subject to the following conditions:

1) Neither the Font Software nor any of its individual components, in
Original or Modified Versions, may be sold by itself.

2) Original or Modified Versions of the Font Software may be bundled,
redistributed and/or sold with any software, provided that each copy
contains the above copyright notice and this license. These can be
included either as stand-alone text files, human-readable headers or
in the appropriate machine-readable metadata fields within text or
binary files as long as those fields can be easily viewed by the user.

3) No Modified Version of the Font Software may use the Reserved Font
Name(s) unless explicit written permission is granted by the
corresponding Copyright Holder. This restriction only applies to the
primary font name as presented to the users.

4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
Software shall not be used to promote, endorse or advertise any
Modified Version, except to acknowledge the contribution(s) of the
Copyright Holder(s) and the Author(s) or with their explicit written
permission.

5) The Font Software, modified or unmodified, in part or in whole,
must be distributed entirely under this license, and must not be
distributed under any other license. The requirement for fonts to
remain under this license does not apply to any document created using
the Font Software.

TERMINATION
This license becomes null and void if any of the above conditions are
not met.

DISCLAIMER
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
OTHER DEALINGS IN THE FONT SOFTWARE.
12 changes: 12 additions & 0 deletions app/src/main/resources/fonts/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
# PDF fonts

`ZhuqueFangsong-Regular.ttf` is the existing primary font for Chinese report text.

`NotoSansSymbols-Regular.ttf` supplies glyphs missing from the primary font,
including circled numbers such as ①②③. Fonts used in a report are embedded in the
PDF; generation does not require fonts installed on the server or client.

Noto Sans Symbols is licensed under the SIL Open Font License 1.1, included in
`OFL-NotoSansSymbols.txt`. The font is an unmodified copy from
[notofonts/noto-fonts](https://github.com/notofonts/noto-fonts/blob/main/hinted/ttf/NotoSansSymbols/NotoSansSymbols-Regular.ttf),
Git blob `443ca5e0969742a263c9fe77952f1a8c036f82ea`.
Original file line number Diff line number Diff line change
@@ -0,0 +1,159 @@
package interview.guide.infrastructure.export;

import static org.assertj.core.api.Assertions.assertThat;

import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfName;
import com.itextpdf.kernel.pdf.PdfReader;
import com.itextpdf.kernel.pdf.canvas.parser.EventType;
import com.itextpdf.kernel.pdf.canvas.parser.PdfCanvasProcessor;
import com.itextpdf.kernel.pdf.canvas.parser.PdfTextExtractor;
import com.itextpdf.kernel.pdf.canvas.parser.data.IEventData;
import com.itextpdf.kernel.pdf.canvas.parser.data.TextRenderInfo;
import com.itextpdf.kernel.pdf.canvas.parser.listener.IEventListener;
import interview.guide.modules.interview.model.InterviewAnswerEntity;
import interview.guide.modules.interview.model.InterviewSessionEntity;
import interview.guide.modules.interview.model.ResumeAnalysisResponse;
import interview.guide.modules.resume.model.ResumeEntity;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.List;
import java.util.Set;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import tools.jackson.databind.json.JsonMapper;

@DisplayName("PDF 报告导出")
class PdfExportServiceTest {

private final PdfExportService service = new PdfExportService(JsonMapper.builder().build());

@ParameterizedTest
@ValueSource(strings = {"①②③", "④⑤⑥⑦⑧⑨", "⑩⑪⑳", "⓪❶❷❸"})
@DisplayName("面试报告应保留问题、回答和评价中的带圈编号")
void shouldPreserveNumberedSymbolsInInterviewReport(String symbols) throws IOException {
InterviewSessionEntity session = session();
session.setOverallFeedback("总体评价:" + symbols);
session.setStrengthsJson("[\"优势:" + symbols + "\"]");
session.setImprovementsJson("[\"改进:" + symbols + "\"]");
InterviewAnswerEntity answer = new InterviewAnswerEntity();
answer.setQuestionIndex(0);
answer.setQuestion("问题:" + symbols);
answer.setUserAnswer("回答:" + symbols);
answer.setFeedback("评价:" + symbols);
answer.setReferenceAnswer("先归因,再优化:" + symbols);
answer.setScore(85);
session.setAnswers(List.of(answer));

byte[] report = service.exportInterviewReport(session);

assertThat(extractText(report)).contains(
"总体评价:" + symbols, "优势:" + symbols, "改进:" + symbols,
"问题:" + symbols, "回答:" + symbols, "评价:" + symbols,
"先归因,再优化:" + symbols);
assertFontsEmbedded(report);
}

@Test
@DisplayName("带圈编号后的中英文和数字应继续使用原来的中文字体")
void shouldKeepPrimaryFontAfterNumberedSymbols() throws IOException {
InterviewSessionEntity session = session();
session.setOverallFeedback("①Java②123③中文");

byte[] report = service.exportInterviewReport(session);
assertThat(extractText(report)).contains("①Java②123③中文");

try (PdfDocument pdf = new PdfDocument(new PdfReader(new ByteArrayInputStream(report)))) {
var listener = new IEventListener() {
@Override
public void eventOccurred(IEventData data, EventType type) {
if (type != EventType.RENDER_TEXT) {
return;
}
for (TextRenderInfo character : ((TextRenderInfo) data).getCharacterRenderInfos()) {
if (character.getText().matches("[A-Za-z0-9中文]")) {
assertThat(character.getFont().getFontProgram().getFontNames().getFontName())
.endsWith("ZhuqueFangsong-Regular");
}
}
}

@Override
public Set<EventType> getSupportedEvents() {
return Set.of(EventType.RENDER_TEXT);
}
};
for (int page = 1; page <= pdf.getNumberOfPages(); page++) {
new PdfCanvasProcessor(listener).processPageContent(pdf.getPage(page));
}
}
}

@Test
@DisplayName("简历分析报告也应保留带圈编号及普通中英文内容")
void shouldPreserveNumberedSymbolsInResumeAnalysis() throws IOException {
ResumeEntity resume = new ResumeEntity();
resume.setOriginalFilename("Java简历.pdf");
ResumeAnalysisResponse analysis = new ResumeAnalysisResponse(85,
new ResumeAnalysisResponse.ScoreDetail(10, 12, 18, 8, 37),
"摘要:①Java,②Spring,③API", List.of("优势:①②③"),
List.of(new ResumeAnalysisResponse.Suggestion("项目经验", "高",
"问题:①②③", "建议:①先归因,②再优化,③验证")), null);

byte[] report = service.exportResumeAnalysis(resume, analysis);

assertThat(extractText(report)).contains("简历分析报告", "Java简历.pdf", "85 / 100",
"摘要:①Java,②Spring,③API", "优势:①②③", "问题:①②③",
"建议:①先归因,②再优化,③验证");
assertFontsEmbedded(report);
}

@Test
@DisplayName("普通报告应继续保留中文、英文、箭头和原有 emoji 清理行为")
void shouldPreserveExistingTextAndAllowRepeatedExports() throws IOException {
InterviewSessionEntity session = session();
session.setOverallFeedback("中文 Java API → 验证😀");

for (int i = 0; i < 2; i++) {
byte[] report = service.exportInterviewReport(session);
assertThat(extractText(report)).contains("模拟面试报告", "中文 Java API → 验证")
.doesNotContain("😀");
assertFontsEmbedded(report);
}
}

private InterviewSessionEntity session() {
InterviewSessionEntity session = new InterviewSessionEntity();
session.setSessionId("pdf-symbol-regression");
session.setTotalQuestions(1);
session.setStatus(InterviewSessionEntity.SessionStatus.EVALUATED);
return session;
}

private String extractText(byte[] bytes) throws IOException {
try (PdfDocument pdf = new PdfDocument(new PdfReader(new ByteArrayInputStream(bytes)))) {
StringBuilder text = new StringBuilder();
for (int page = 1; page <= pdf.getNumberOfPages(); page++) {
text.append(PdfTextExtractor.getTextFromPage(pdf.getPage(page)));
}
return text.toString();
}
}

private void assertFontsEmbedded(byte[] bytes) throws IOException {
try (PdfDocument pdf = new PdfDocument(new PdfReader(new ByteArrayInputStream(bytes)))) {
for (int page = 1; page <= pdf.getNumberOfPages(); page++) {
var fonts = pdf.getPage(page).getResources().getResource(PdfName.Font);
assertThat(fonts).isNotNull();
for (PdfName name : fonts.keySet()) {
var font = fonts.getAsDictionary(name);
var descendants = font.getAsArray(PdfName.DescendantFonts);
var descriptor = descendants.getAsDictionary(0).getAsDictionary(PdfName.FontDescriptor);
assertThat(descriptor.getAsStream(PdfName.FontFile2)).isNotNull();
}
}
}
}
}