【发布时间】:2023-03-28 17:42:01
【问题描述】:
我在使用 Itext pdf 时遇到问题。问题是,在选择了一个选项并且指针聚焦在 pdf 的另一个元素上之后,TextField 中的文本以某种方式被截断或一些字母漂浮在上面。解决方案是什么? 显示正在发生的事情的图像 代码块是
@Override
public void writePdfElement(RankingQuestionDTO input, Document document, PdfWriter writer, PdfPTable baseTable) {
try{
PdfPTable table = new PdfPTable(2);
PdfPCell cell;
document.add(new Paragraph(input.getText(), stylesService.getHeaderFont()));
//Add rows with selectors
PdfFormField selectGroup = PdfFormField.createTextField(writer, true, false, 10);
selectGroup.setFieldName(String.format("%s", input.getUuid()));
ArrayList<RankingAnswerDTO> possibleAnswers = input.getPossibleAnswers();
for(int i = 0; i <input.getPossibleAnswers().size(); i++) {
cell = new PdfPCell();
cell.setPhrase(getPolishTablePhrase(input.getText()));
cell.setPadding(stylesService.getPaddingCell());
table.addCell(cell);
cell = new PdfPCell();
cell.setPadding(stylesService.getPaddingCell());
cell.setCellEvent(new SelectCellEvent(String.format("%s",i), selectGroup, writer, stylesService,
possibleAnswers));
cell.setMinimumHeight(stylesService.getMinimumHeight());
table.addCell(cell);
}
baseTable.addCell(table);
document.add(baseTable);
writer.addAnnotation(selectGroup);
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void cellLayout(PdfPCell cell, Rectangle position,
PdfContentByte[] canvases) {
Rectangle rect = stylesService.getSelectFiledRectangle(position, sizeOfRect);
// define the select box
TextField tf = new TextField(writer, rect, name);
try {
tf.setFont(BaseFont.createFont(BaseFont.TIMES_ROMAN, BaseFont.CP1250, true));
} catch (DocumentException | IOException e) {
e.printStackTrace();
}
tf.setBackgroundColor(stylesService.getBackgroundColor());
tf.setBorderColor(stylesService.getBorderColor());
tf.setBorderStyle(PdfBorderDictionary.STYLE_BEVELED);
tf.setVisibility(TextField.VISIBLE_BUT_DOES_NOT_PRINT);
tf.setBorderColor(BaseColor.GRAY);
tf.setBorderWidth(stylesService.getFloatBorderWidth());
tf.setFontSize(stylesService.getFieldFloatFont());
tf.setChoices(select);
tf.setChoiceExports(ranks);
tf.setAlignment(Element.ALIGN_CENTER);
tf.setOptions(TextField.MULTILINE);
tf.setRotation(0);
// add the select box as a field
try {
selectGroup.addKid(tf.getComboField());
} catch (Exception e) {
throw new ExceptionConverter(e);
}
}
问题在于字体设置。 以下方法效果很好
private void initializeBaseFont() {
try {
baseFont = BaseFont.createFont("c:/windows/fonts/arial.ttf", BaseFont.CP1250, BaseFont.EMBEDDED);
} catch (Exception e) {
e.printStackTrace();
}
}
代替
tf.setFont(BaseFont.createFont(BaseFont.TIMES_ROMAN, BaseFont.CP1250, true));
【问题讨论】: