gpt4 book ai didi

java - pdfBox 向 pdf 添加不同的行

转载 作者:行者123 更新时间:2023-12-01 14:07:25 24 4
gpt4 key购买 nike

我正在研究生成一个 pdf 文档。目前我正在尝试不同的方法。我想在 pdf 文档中获得不止一行。使用 HelloWorld我想出的代码示例...

package org.apache.pdfbox.examples.pdmodel;

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.PDFont;
import org.apache.pdfbox.pdmodel.font.PDType1Font;

/**
* Creates a "Hello World" PDF using the built-in Helvetica font.
*
* The example is taken from the PDF file format specification.
*/
public final class HelloWorld
{
private HelloWorld()
{
}

public static void main(String[] args) throws IOException
{

String filename = "line.pdf";
String message = "line";

PDDocument doc = new PDDocument();
try
{
PDPage page = new PDPage();
doc.addPage(page);

PDFont font = PDType1Font.HELVETICA_BOLD;

PDPageContentStream contents = new PDPageContentStream(doc, page);
contents.beginText();
contents.setFont(font, 12);
// Loop to create 25 lines of text
for (int y = 0; y< 25; y++) {
int ty = 700 + y * 15;
contents.newLineAtOffset(100, ty);
//contents.newLineAtOffset(125, ty);
//contents.showText(Integer.toString(i));
contents.showText(message + " " + Integer.toString(i));
System.out.println(message + " " + Integer.toString(i));
}
contents.endText();
contents.close();

doc.save(filename);
}
finally
{
doc.close();
System.out.println("HelloWorld finished after 'doc.close()'.");
}
}
}

但是查看我生成的文档,我只看到“第 0 行”一次,而没有看到其他行。我做错了什么?

PDF document with only one line

最佳答案

您的问题是您认为 PDPageContentStream.newLineAtOffset 使用绝对坐标。情况并非如此,它使用相对坐标,参见。 JavaDocs:

/**
* The Td operator.
* Move to the start of the next line, offset from the start of the current line by (tx, ty).
*
* @param tx The x translation.
* @param ty The y translation.
* @throws IOException If there is an error writing to the stream.
* @throws IllegalStateException If the method was not allowed to be called at this time.
*/
public void newLineAtOffset(float tx, float ty) throws IOException

所以您的附加行远离可见页面区域。

因此,您可能想要这样的东西:

...
contents.beginText();
contents.setFont(font, 12);
contents.newLineAtOffset(100, 700);
// Loop to create 25 lines of text
for (int i = 0; i < 25; i++) {
contents.showText(message + " " + Integer.toString(i));
System.out.println(message + " " + Integer.toString(i));
contents.newLineAtOffset(0, -15);
}
contents.endText();
...

这里从 100、700 开始,每行向下移动 15。

关于java - pdfBox 向 pdf 添加不同的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36712642/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com