我使用 iText 列来布局字母。这是我工作中的一个例子。请注意,我只是将它输入到 Stack Overflow,我还没有编译或测试它。
想象一个文件,其中一行中的两个换行符表示一个段落,文本由文本编辑器换行。下面的类有一个名为 generate 的方法,它读取文件并发出一个 US Letter 大小的 PDF,顶部和底部的边距为 1 英寸,每侧边距为 1 1/2 英寸。
/** Generates a letter. */
public class LetterGenerator
{
/** One inch is 72 points. */
private final static int INCH = 72;
/** Generate a letter. */
public void generate() throws DocumentException, IOException
{
BufferedReader in = new BufferedReader(new FileReader("letter.txt"));
Document document = new Document(PageSize.LETTER);
PdfWriter.getInstance(document, new FileOutputStream("letter.pdf"));
PdfContentByte cb = writer.getDirectContent();
ColumnText ct = new ColumnText(cb);
String para;
int spacingBefore = 0;
while ((para = in.readLine()) != null)
{
line = line.trim();
if (line.length() != 0)
{
// Shekhar, do your place-holder replacement here.
Paragraph p = new Paragraph(line);
p.setSpacingBefore(spacingBefore);
ct.addElement(p);
spacingBefore = 8;
}
}
ct.setSimpleColumn(INCH, INCH * 1.5f, 7.5f * INCH, 9.5f * INCH);
int status = ColumnText.START_COLUMN;
while ((status & ColumnText.NO_MORE_TEXT) == 0)
{
status = ct.go();
ct.setYLine(PageSize.LETTER.getHeight() - INCH);
ct.setSimpleColumn(INCH, INCH * 1.5f, 7.5f * INCH, 9.5f * INCH);
document.newPage();
}
document.close();
}
}
对于我的一生,我不记得我为什么要重置 Y 线。
iText 是一个不错的库。通过阅读 iText in Action 书中的教程,我学到了我所知道的大部分内容。
http://developers.itextpdf.com/examples/
不幸的是,我从来没有抽空买这本书。