如今应用程序中生成PDF的功能很常用,然而Java本身并不好实现这个功能,因为Java本身并没有提供处理PDF的API。可是开源框架iText提供了非常丰富的功能API。
iText是一个开源的框架,它可以让你的应用程序你动态的创建PDF。
首先,要想使用它,我们得获取它的jar包。可以在这里下载lib库以及src文件:
https://github.com/itext/itextpdf/releases/tag/5.5.9
下面是一个简单的例子
package com.sy.pdf;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import com.itextpdf.text.Chapter;
import com.itextpdf.text.Chunk;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Font;
import com.itextpdf.text.FontFactory;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfWriter;
/**
* Example written by Bruno Lowagie in answer to:
* http://stackoverflow.com/questions/28431148/itext-chapter-font-overrides-paragraph-font
*/
public class ChapterAndTitle {
public static final String DEST = "results/objects/chapter_title.pdf";
public static void main(String[] args) throws IOException, DocumentException {
File file = new File(DEST);
file.getParentFile().mkdirs();
new ChapterAndTitle().createPdf(DEST);
}
public void createPdf(String dest) throws IOException, DocumentException {
Document document = new Document();
PdfWriter.getInstance(document, new FileOutputStream(dest));
document.open();
Font chapterFont = FontFactory.getFont(FontFactory.HELVETICA, 16, Font.BOLDITALIC);
Font paragraphFont = FontFactory.getFont(FontFactory.HELVETICA, 12, Font.NORMAL);
//这是可以添加到文档中的最小的文本的一部分。
Chunk chunk = new Chunk("This is the title", chapterFont);
//章节Chapter 段落Paragraph
Chapter chapter = new Chapter(new Paragraph(chunk), 1);
chapter.setNumberDepth(0);
chapter.add(new Paragraph("This is the paragraph", paragraphFont));
document.add(chapter);
document.close();
System.out.println("生成pdf文件成功------->" + dest);
}
}
执行完这段代码后就在项目路径results/objects下生成chapter_title.pdf文件。
下面就是生成的PDF文件效果。