import com.itextpdf.text.Document; import com.itextpdf.text.DocumentException; import com.itextpdf.text.Paragraph; import com.itextpdf.text.pdf.PdfWriter;
import java.io.FileOutputStream; import java.io.IOException;
public class ItextPdfGenerator { public static void main(String[] args) { // 创建文档对象 Document document = new Document();
try {
// 创建PdfWriter实例,将文档写入指定文件
PdfWriter.getInstance(document, new FileOutputStream("itext_example.pdf"));
// 打开文档
document.open();
// 向文档添加内容
document.add(new Paragraph("Hello, this is a PDF generated by iText!"));
document.add(new Paragraph("This is another line in the PDF document."));
// 添加空白行
document.add(new Paragraph(" "));
// 添加带样式的文本
Paragraph styledParagraph = new Paragraph("This is a styled paragraph.");
styledParagraph.setAlignment(Paragraph.ALIGN_CENTER);
document.add(styledParagraph);
System.out.println("PDF created successfully!");
} catch (DocumentException | IOException e) {
e.printStackTrace();
} finally {
// 关闭文档
document.close();
}
}
}