我的 Spring boot Java 应用程序使用 apache pdf box library {version 2.0.6} 来生成 pdf。我希望十进制值右对齐。这意味着所有小数点都应对齐在同一垂直线上。我还附上了屏幕截图。
stream.beginText();
stream.newLineAtOffset(xCordinate, yCordinate);
stream.showText(String.valueOf(item.getQuantity()));
List<String> resultList = processTextData(TextUtil.isEmpty(item.getDescription()) ? "-" : item.getDescription());
int y = 0;
int x = 50;
int tempYcordinate = yCordinate;
for (String string : resultList) {
stream.newLineAtOffset(x, y);
stream.showText(processStringForPdf(string));
x = 0;
y = -8;
}
tempYcordinate = tempYcordinate - (8 * resultList.size());
stream.endText();
stream.beginText();
stream.newLineAtOffset(285, yCordinate);
stream.showText("$" + NumberFormat.getInstance(Locale.US).format(Util.round(item.getUnitPrice())));
stream.newLineAtOffset(65, 0);
stream.showText("$" + NumberFormat.getInstance(Locale.US).format(Util.round(item.getExtPrice())));
stream.endText();
yCordinate = tempYcordinate;
最佳答案
要右对齐文本,您需要计算要显示的文本的宽度并将输出位置对齐到
(right alignment position) - (text width)
在下面找到一个显示原理的小片段。您需要根据需要修改代码段。
import java.io.File;
import java.io.IOException;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.font.PDType1Font;
public class RightAlignDemo {
public static void main(String[] args) throws IOException {
File file = new File("out.pdf");
PDDocument doc = new PDDocument();
PDPage page = new PDPage();
doc.addPage(page);
PDPageContentStream stream = new PDPageContentStream(doc, page);
PDType1Font font = PDType1Font.TIMES_ROMAN;
int fontSize = 12;
stream.setFont(font, fontSize);
double[] values = {0, 0.1, 0.01, 12.12, 123.12, 1234.12, 123456.12};
int columnOneLeftX = 50;
int columnTwoRightX = 170;
int columnThreeOffsetX = 10;
for (int i = 0; i < values.length; i++) {
stream.beginText();
stream.newLineAtOffset(columnOneLeftX, 700 - (i*10));
// show some left aligned non fixed width text
stream.showText("value " + values[i]);
// format the double value with thousands separator and
// two decimals
String text = String.format("%,.2f", values[i]);
// get the width of the formated value
float textWidth = getTextWidth(font, fontSize, text);
// align the position to (right alignment minus text width)
stream.newLineAtOffset(columnTwoRightX - textWidth, 0);
stream.showText(text);
// align the positon back to columnTwoRightX plus offset for
// column three
stream.newLineAtOffset(textWidth + columnThreeOffsetX, 0);
stream.showText("description " + i);
stream.endText();
}
stream.close();
doc.save(file);
doc.close();
}
private static float getTextWidth(PDType1Font font, int fontSize,
String text) throws IOException {
return (font.getStringWidth(text) / 1000.0f) * fontSize;
}
}
PDF输出
关于java - 使用 Apache PDFBox 库对 PDF 中的数值进行右对齐,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48274384/