目录
坐标概念
想要做好文本样式,首先需要理解Pdfbox的坐标概念。
可以看到默认的(0,0)是页面的左下角,如果要计算页面开始布局的坐标,就需要左上角的位置。
这个时候还需要理解一个概念--box。Pdfbox默认做了多种盒子的布局,目前我们只需要理解
MediaBox就行,简单理解就是纸张尺寸。
try (PDDocument pdDocument = new PDDocument()) {
PDPage pdPage = new PDPage();
pdDocument.addPage(pdPage);
PDRectangle mediaBox = pdPage.getMediaBox();
// 页边距
float marginY = 88;
// 真实宽度
float width = mediaBox.getWidth() - 2 * marginX;
// 开始x坐标
float startX = mediaBox.getLowerLeftX() + marginX;
// 开始y坐标
float startY = mediaBox.getUpperRightY() - marginY;
} catch (IOException e) {
log.error("", e);
}
可以看到通过MediaBox,可以初步定为到页面长和宽,以及开始坐标。
如何换行
PDDocument doc = null;
try
{
doc = new PDDocument();
PDPage page = new PDPage();
doc.addPage(page);
PDPageContentStream contentStream = new PDPageContentStream(doc, page);
PDFont pdfFont = PDType1Font.HELVETICA;
float fontSize = 25;
float leading = 1.5f * fontSize;
PDRectangle mediabox = page.getMediaBox();
float margin = 72;
float width = mediabox.getWidth() - 2*margin;
float startX = mediabox.getLowerLeftX() + margin;
float startY = mediabox.getUpperRightY() - margin;
String text = "I am trying to create a PDF file with a lot of text contents in the document. I am using PDFBox";
List<String> lines = new ArrayList<String>();
int lastSpace = -1;
while (text.length() > 0)
{
int spaceIndex = text.indexOf(' ', lastSpace + 1);
if (spaceIndex < 0)
spaceIndex = text.length();
String subString = text.substring(0, spaceIndex);
float size = fontSize * pdfFont.getStringWidth(subString) / 1000;
System.out.printf("'%s' - %f of %f\n", subString, size, width);
if (size > width)
{
if (lastSpace < 0)
lastSpace = spaceIndex;
subString = text.substring(0, lastSpace);
lines.add(subString);
text = text.substring(lastSpace).trim();
System.out.printf("'%s' is line\n", subString);
lastSpace = -1;
}
else if (spaceIndex == text.length())
{
lines.add(text);
System.out.printf("'%s' is line\n", text);
text = "";
}
else
{
lastSpace = spaceIndex;
}
}
contentStream.beginText();
contentStream.setFont(pdfFont, fontSize);
contentStream.newLineAtOffset(startX, startY);
for (String line: lines)
{
contentStream.showText(line);
contentStream.newLineAtOffset(0, -leading);
}
contentStream.endText();
contentStream.close();
doc.save(new File(RESULT_FOLDER, "break-long-string.pdf"));
}
finally
{
if (doc != null)
{
doc.close();
}
}