iText初探之HelloWorld (一)

       如今应用程序中生成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文件效果。
      

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值