本文介绍如何使用spire.pdf for java在pdf文档中添加多级列表。
import com.spire.pdf.pdfdocument;
import com.spire.pdf.pdfnumberstyle;
import com.spire.pdf.pdfpagebase;
import com.spire.pdf.pdfpagesize;
import com.spire.pdf.graphics.*;
import com.spire.pdf.lists.pdflistitem;
import com.spire.pdf.lists.pdforderedmarker;
import com.spire.pdf.lists.pdfsortedlist;
import java.awt.*;
import java.awt.geom.point2d;
public class createmultilevellist {
public static void main(string[] args) {
//创建pdfdocument对象
pdfdocument doc = new pdfdocument();
//设置页边距
pdfmargins margin = new pdfmargins(60, 60, 40, 40);
//添加一页
pdfpagebase page = doc.getpages().add(pdfpagesize.a4, margin);
//初始化x,y坐标
float x = 0;
float y = 15;
//创建两个画刷
pdfbrush blackbrush = pdfbrushes.getblack();
pdfbrush purplebrush = pdfbrushes.getpurple();
//创建两个字体
pdftruetypefont titlefont = new pdftruetypefont(new font("微软雅黑",font.bold,9),true);
pdftruetypefont listfont = new pdftruetypefont(new font("微软雅黑",font.plain,9),true);
//在指定位置绘制标题
string title = "xhtml常见问题 :";
page.getcanvas().drawstring(title, titlefont, blackbrush, x, y);
y = y (float) titlefont.measurestring(title).getheight();
y = y 5;
//创建两个ordered makers,用于设置有序列表的符号
pdforderedmarker marker1 = new pdforderedmarker(pdfnumberstyle.upper_roman, listfont);
pdforderedmarker marker2 = new pdforderedmarker(pdfnumberstyle.numeric, listfont);
//创建一个父列表
string parentlistcontent = "xhtml 1.0简介\n"
"标签和属性语法介绍";
pdfsortedlist parentlist = new pdfsortedlist(parentlistcontent);
parentlist.setfont(listfont);
parentlist.setindent(8);
parentlist.setbrush(purplebrush);
parentlist.setmarker(marker1);
//创建一个列表 - "sublist_1"
string sublistcontent_1 = "什么是xhtml?\n"
"xhmtl文档是什么样的?\n"
"xhtml和html之间有什么关系?\n"
"xhtml和xml之间有什么关系?";
pdfsortedlist sublist_1 = new pdfsortedlist(sublistcontent_1);
sublist_1.setindent(16);
sublist_1.setfont(listfont);
sublist_1.setbrush(purplebrush);
sublist_1.setmarker(marker2);
//创建另一个列表 -"sublist_2"
string sublistcontent_2 = "什么是xhtml的元素?\n"
"如何在xhtml文档中添加注释?\n"
"如何为xhtml元素写一个开始标签?";
pdfsortedlist sublist_2 = new pdfsortedlist(sublistcontent_2);
sublist_2.setindent(16);
sublist_2.setfont(listfont);
sublist_2.setbrush(purplebrush);
sublist_2.setmarker(marker2);
//将sublist_1设置为父列表第一个元素下的子列表
pdflistitem item_1 = parentlist.getitems().get(0);
item_1.setsublist(sublist_1);
//将sublist_2设置为父列表第二个元素下的子列表
pdflistitem item_2 = parentlist.getitems().get(1);
item_2.setsublist(sublist_2);
//绘制父列表到指定位置
pdftextlayout textlayout = new pdftextlayout();
textlayout.setbreak(pdflayoutbreaktype.fit_page);
textlayout.setlayout(pdflayouttype.paginate);
parentlist.draw(page,new point2d.float(x,y),textlayout);
//保存文档
doc.savetofile("multilevellist.pdf");
}
}