内容未添加到 pdf 页面

Content not being added to pdf page

我编写这个程序是为了从 ArrayList 中读取字符串值,并使用 pdfbox 将它们写入 pdf 文件。 除了字符串 List of Strings 没有其他字符串不是 added.Here 的代码:

import java.io.IOException;
import java.util.ArrayList;

import org.apache.pdfbox.contentstream.PDContentStream;
import org.apache.pdfbox.pdmodel.*;

public class pdfBoxTest {

    public static void main(String[] args) {
        ArrayList<String> r = new ArrayList<String>();
        r.add("Jack and ");r.add("Jill ");r.add("Went up");r.add(" the hill");
        try{
            PDDocument file = new PDDocument();
            PDPage page = new PDPage();
            file.addPage(page);

                PDPageContentStream data = new PDPageContentStream(file, page);
                data.beginText();
                data.setFont(PDType1Font.HELVETICA, 20);
                float x=220,y=750;
                data.newLineAtOffset(x, y);
                data.showText("List of Strings");
                for(int i=0;i<r.size();i++){                    
                    String line=r.get(i);
                    System.out.println(line);
                    data.newLineAtOffset(x, y);
                    data.showText(line);
                    y+=100;
                }

                data.close();
                file.save("res.pdf");
                file.close();
        }
         catch (IOException e) { e.printStackTrace();   }

      }

    }

引入这一行时:

data.beginText();

您开始在 PDF 中创建文本对象。

但是,您还需要这一行:

data.endText();

这样就完成了文本对象。您没有完整的文本对象,这会导致奇怪的结果。

此外,您似乎并不知道PDF中的坐标系。请参阅以下常见问题条目:

更改此行:

y+=100;

为此:

y-=100;

您从 float x=220,y=750; 开始 我不知道 PdfBox 中的默认页面大小,但我们假设它是 A4 页面。在这种情况下,页面尺寸为 595(宽度)乘以 842(高度)用户单位,并且 float x=220,y=750; 或多或少位于中间(水平)和靠近顶部(垂直)。

当您将 100 添加到 y 时,您将得到 y = 850,这意味着您将离开页面的可见区域(因为 850 高于 842)。您正在添加文本,文本在您正在创建的内容流中,但文本不可见,因为它在页面的 /MediaBox 之外。

最后:newLineAtOffset()方法不会将内容移动到你定义的坐标,而是另起一行,并使用参数作为当前位置的偏移量。 因此,即使您按照我解释的方式更改 y,您也会将内容移动到与 (x, y) 坐标位置完全不同的位置。

底线: PdfBox 要求您了解 PDF 语法。如果您不知道 PDF 语法(从您的问题中可以清楚地看出),您应该考虑使用 iText。 (免责声明:我是 iText Group 的 CTO。)

OP 的详细错误(由 mkl 编辑)

与 OP 所期望的相反,方法调用 data.newLineAtOffset(x, y) 接受 绝对坐标 instead 期望 相对于前一行开始的坐标 :

/**
 * 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

因此,考虑到 OP 尝试使用 y 坐标向下变化 100,循环中该方法的调用应该是

data.newLineAtOffset(0, -100);