- 使用
pdfwriter创建writer对象,使用document创建文档:
// 创建新的PDF文档
PdfWriter writer = new PdfWriter("order_report.pdf");
PdfDocument pdfDoc = new PdfDocument(writer);
Document document = new Document(pdfDoc);
// 设置字体为支持中文的字体,此处为宋体
PdfFont titleFont = PdfFontFactory.createFont("STSong-Light", "UniGB-UCS2-H");
PdfFont normalFont = PdfFontFactory.createFont("STSong-Light", "UniGB-UCS2-H");
- 使用
Paragraph创建段落,使用docment.add(...)加入文档:
Paragraph title = new Paragraph("加菲尔德餐厅订单报告")
.setFont(titleFont)
.setFontSize(16)
.setTextAlignment(TextAlignment.CENTER);
document.add(title);
// 添加空行
document.add(new Paragraph(" "));
// 写入订单详细信息
document.add(new Paragraph("订单详情:").setFont(normalFont));
for (OrderItem item : orderItems) {
Paragraph content = new Paragraph(
"name: " + item.getFood().getName() +
", quantity: " + item.getQuantity() +
", price: $" + String.format("%.2f", item.getFood().getPrice()) +
", total: $" + String.format("%.2f", item.getTotalPrice()) +
", calories: " + item.getTotalCalories() + "kcal")
.setFont(normalFont);
document.add(content);
}
// 关闭文档
document.close();