Java IText:段落
时间:2020-01-09 10:36:09 来源:igfitidea点击:
IText中的com.itextpdf.text.Paragraph类表示文本的"段落"。在段落中,我们可以设置段落前后的段落对齐方式,缩进和间距。
这是一个简单的代码示例:
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Paragraph;
public class DocumentExample {
public static void main(String[] args) {
Document document = new Document();
try {
PdfWriter.getInstance(document,
new FileOutputStream("Paragraph.pdf"));
document.open();
Paragraph paragraph = new Paragraph();
for(int i=0; i<10; i++){
Chunk chunk = new Chunk(
"This is a sentence which is long " + i + ". ");
paragraph.add(chunk);
}
document.add(paragraph);
document.close();
} catch (DocumentException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
注意句子6是如何很好地位于其自己的行上的。
行间距
如果添加的文本超出文档的右边缘,则段落对象知道如何添加行距。行距以用户单位度量。每英寸有72个单位。默认间距是字体高度的1.5倍。我们可以通过将间距作为参数传递给Paragraph构造函数来更改行距,如下所示:
Paragraph paragraph = new Paragraph(50);
段落前后的间距
我们还可以设置段落前后的间距。这是我们在代码中的操作方法:
paragraph.setSpacingAfter(50); paragraph.setSpacingBefore(50);
对齐
我们可以使用setAlignment()方法设置段落的对齐方式。设置文本在页面的哪一侧对齐。这是一个例子:
paragraph.setAlignment(Element.ALIGN_LEFT); paragraph.setAlignment(Element.ALIGN_CENTER); paragraph.setAlignment(Element.ALIGN_RIGHT);
缩进
我们可以设置段落的左右缩进。这会将段落内容从页面边缘移开。这是执行此操作的代码:
paragraph.setIndentationLeft(50); paragraph.setIndentationRight(50);
较大的段落示例
这是一个较大的段落示例,在文档中添加了两个段落。第一段使用默认的左对齐和缩进。第二段是居中对齐的,并使用50个用户单位作为左右缩进。
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.PdfWriter;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
/**
*/
public class Paragraph2Example {
public static void main(String[] args) {
Document document = new Document();
try {
PdfWriter.getInstance(document,
new FileOutputStream("Paragraph2.pdf"));
document.open();
Paragraph paragraph1 = new Paragraph();
Paragraph paragraph2 = new Paragraph();
paragraph2.setSpacingAfter(25);
paragraph2.setSpacingBefore(25);
paragraph2.setAlignment(Element.ALIGN_CENTER);
paragraph2.setIndentationLeft(50);
paragraph2.setIndentationRight(50);
for(int i=0; i<10; i++){
Chunk chunk = new Chunk(
"This is a sentence which is long " + i + ". ");
paragraph1.add(chunk);
paragraph2.add(chunk);
}
document.add(paragraph1);
document.add(paragraph2);
document.close();
} catch (DocumentException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}

