本教程将展示如何使用spire.pdf for java在pdf文档中添加有序列表和无序列表。
import com.spire.pdf.*;
import com.spire.pdf.graphics.*;
import com.spire.pdf.lists.*;
import java.awt.*;
import java.awt.geom.*;
public class list {
public static void main(string[] args) {
//创建pdfdocument对象
pdfdocument doc = new pdfdocument();
//设置边距
pdfunitconvertor unitcvtr = new pdfunitconvertor();
pdfmargins margin = new pdfmargins();
margin.settop(unitcvtr.convertunits(2.54f, pdfgraphicsunit.centimeter, pdfgraphicsunit.point));
margin.setbottom(margin.gettop());
margin.setleft(unitcvtr.convertunits(3.17f, pdfgraphicsunit.centimeter, pdfgraphicsunit.point));
margin.setright(margin.getleft());
//添加新的一页
pdfpagebase page = doc.getpages().add(pdfpagesize.a4, margin);
//画标题
float y = 10;
pdfbrush brush1 = pdfbrushes.getblack();
pdftruetypefont font1 = new pdftruetypefont(new font("arial unicode ms", font.bold, 16), true);
pdfstringformat format1 = new pdfstringformat(pdftextalignment.center);
page.getcanvas().drawstring("这是标题", font1, brush1, page.getcanvas().getclientsize().getwidth() / 2, y, format1);
y = y (float) font1.measurestring("这是标题", format1).getheight();
y = y 5;
//设置列表格式和列表文字
rectangle2d rctg = new rectangle2d.float();
rctg.setframe(new point(0, 0), page.getcanvas().getclientsize());
pdflineargradientbrush brush =
new pdflineargradientbrush(rctg, new pdfrgbcolor(new pdfrgbcolor(new color(0,0,128))), new pdfrgbcolor(new color(255,69,0)), pdflineargradientmode.vertical);
pdftruetypefont font = new pdftruetypefont(new font("arial unicode ms", font.bold, 12), true);
string formatted = "饮料\n调味品\n糖果\n奶制品\n谷物\n肉类\n蔬菜\n海鲜";
//画无序列表
pdflistbase list = new pdfunorderedlist(formatted);
list.setfont(font);
list.setindent(8);
list.settextindent(5);
list.setbrush(brush);
pdflayoutresult result = list.draw(page, 0, y);
y = (float) (result.getbounds().getheight() result.getbounds().gety());
//画有序列表
pdfsortedlist sortedlist = new pdfsortedlist(formatted);
sortedlist.setfont(font);
sortedlist.setindent(8);
sortedlist.settextindent(5);
sortedlist.setbrush(brush);
sortedlist.draw(page, 0, y);
//保存文档
doc.savetofile("list.pdf");
doc.close();
}
}
执行结果如下图: