要求:附上屏幕截图。我必须在pdf中写两行文字,然后画一条线,然后再开始写一些文字。
因此,我的算法经过:
contentStream = new PDPageContentStream(doc, page);
contentStream.setFont(font, fontSize);
contentStream.beginText();
创建了一个新的PDPageContentStream并触发了函数beginText()。我能够写出附加图像中显示的上部文本部分。
以下是上部文本和行的以下代码行:
contentStream.showText("Entry Form – Header");
yCordinate -= fontHeight; //This line is to track the yCordinate
contentStream.newLineAtOffset(0, -leading);
yCordinate -= leading;
contentStream.showText("Date Generated: " + dateFormat.format(date));
yCordinate -= fontHeight;
contentStream.newLineAtOffset(0, -leading);
yCordinate -= leading;
contentStream.endText(); // End of text mode
我必须结束此文本模式,因为以下3行代码(绘制一行)不会在文本模式下执行:
contentStream.moveTo(startX, yCordinate);
contentStream.lineTo(endX, yCordinate);
contentStream.stroke();
现在在这行代码之后,如果我写:
contentStream.beginText();
contentStream.showText("Name: XXXXX");
名称显示在页面的左下角。我希望这条线在绘制的线之后接下来,如下图所示。
答案 0 :(得分:5)
不幸的是,问题中的代码相当不完整,并没有特别显示每个文本对象中文本矩阵的初始化,还有许多未定义的变量。
因此,这里以一段代码为例,产生文本行 - 文本输出:
PDFont font = PDType1Font.HELVETICA;
float fontSize = 14;
float fontHeight = fontSize;
float leading = 20;
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy.MM.dd");
Date date = new Date();
PDDocument doc = new PDDocument();
PDPage page = new PDPage();
doc.addPage(page);
PDPageContentStream contentStream = new PDPageContentStream(doc, page);
contentStream.setFont(font, fontSize);
float yCordinate = page.getCropBox().getUpperRightY() - 30;
float startX = page.getCropBox().getLowerLeftX() + 30;
float endX = page.getCropBox().getUpperRightX() - 30;
contentStream.beginText();
contentStream.newLineAtOffset(startX, yCordinate);
contentStream.showText("Entry Form – Header");
yCordinate -= fontHeight; //This line is to track the yCordinate
contentStream.newLineAtOffset(0, -leading);
yCordinate -= leading;
contentStream.showText("Date Generated: " + dateFormat.format(date));
yCordinate -= fontHeight;
contentStream.endText(); // End of text mode
contentStream.moveTo(startX, yCordinate);
contentStream.lineTo(endX, yCordinate);
contentStream.stroke();
yCordinate -= leading;
contentStream.beginText();
contentStream.newLineAtOffset(startX, yCordinate);
contentStream.showText("Name: XXXXX");
contentStream.endText();
contentStream.close();
doc.save("textLineText.pdf");
(TextAndGraphics.java test testDrawTextLineText
)
此代码导致:
如果你想要不同的距离,你必须在绘制图形线之前和之后调整yCordinate -= ...
线。