要求:附上了屏幕截图。我必须在pdf中写2行文本,然后画一条线,然后再次开始写一些文本。
因此,我的算法通过:
contentStream = new PDPageContentStream(doc, page);
contentStream.setFont(font, fontSize);
contentStream.beginText();
Run Code Online (Sandbox Code Playgroud)
创建了一个新的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
Run Code Online (Sandbox Code Playgroud)
我必须结束此文本模式,因为下面的三行代码(绘制一条线)不会在文本模式下执行:
contentStream.moveTo(startX, yCordinate);
contentStream.lineTo(endX, yCordinate);
contentStream.stroke();
Run Code Online (Sandbox Code Playgroud)
现在在这行代码之后,如果我写:
contentStream.beginText();
contentStream.showText("Name: XXXXX");
Run Code Online (Sandbox Code Playgroud)
名称显示在页面的左下角。我希望此线在下图所示的线之后。
不幸的是,问题中的代码相当不完整,没有特别显示每个文本对象中文本矩阵的初始化,并且还具有许多未定义的变量。
因此,这里以一段代码为例,产生文本-行-文本输出:
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");
Run Code Online (Sandbox Code Playgroud)
(TextAndGraphics.java测试testDrawTextLineText)
此代码导致:
如果需要不同的距离,则必须yCordinate -= ...在绘制图形线之前和之后调整线条。