文檔中的設定有序或無序清單是一種反應内容上下級關系或者内容相同屬性的方式,與單純的文字叙述相比,它能有效增強文檔内容的條理性,突出重點。是以,本文将分享通過Java程式設計在PDF文檔中設定有序或無序清單的方法。
使用工具:Free Spire.PDF for Java V2.2.2(免費版)
Jar檔案導入:
Step1:在Java程式中建立一個檔案夾可命名為Lib。并将下載下傳包中的jar檔案(如下圖)複制到建立的檔案夾下。

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 formatted1 = "行政部\n開發部\n銷售部\n後勤處\n保衛處";
String formatted2 = "飲料\n調味品\n糖果\n奶制品\n肉類\n蔬菜\n海鮮";
//畫無序清單
PdfListBase list = new PdfUnorderedList(formatted2);
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(formatted1);
sortedList.setFont(font);
sortedList.setIndent(8);
sortedList.setTextIndent(5);
sortedList.setBrush(brush);
sortedList.draw(page, 0, y);
//儲存文檔
doc.saveToFile("list.pdf");
doc.close();
}
}
清單設定效果:
(本文完)