从零开始学习使用iText PDF(1):生成第一个PDF文件

来源:互联网 发布:网络问政先进经验 编辑:程序博客网 时间:2024/05/29 19:01

前言:因为项目需要生成PDF文件,所以去找了一下能够生成PDF的Java工具,看到了iText可以说好评如潮,于是想找来教程学习一番,但是晚上的教程要么是太过基础,要么是直接甩一大票代码,实在是难受,于是自己写一份希望对初学者有些帮助。由于个人水平有限,有误指出请多多指正。

  • 代码已上传至码云:zZ丨 / iTextDemo
  • 字体文件和生成的PDF在src/main/resources文件夹中

  1. 获取工具

    既然是用的第三方工具,当然要先拿到jar包再说,这里介绍两种方式:

    1. Maven
      使用Maven的话可以参考官方提供的方式:Maven Dependencies
      总结一下就是添加以下依赖:

      <dependency>    <groupId>com.itextpdf</groupId>    <artifactId>itextpdf</artifactId>    <version>5.5.12</version></dependency>
    2. 直接引入jar包

      • 官方下载地址:https://repo.itextsupport.com/releases/com/itextpdf/itextpdf/5.5.12/itextpdf-5.5.12.jar
      • 我也将jar包传到CSDN资源库了:http://download.csdn.net/download/zz_life/10137577
  2. 生成第一个PDF文件
    第一个程序当然是从hello world做起啦

    import java.io.File;import java.io.FileNotFoundException;import java.io.FileOutputStream;import com.itextpdf.text.Document;import com.itextpdf.text.DocumentException;import com.itextpdf.text.Paragraph;import com.itextpdf.text.pdf.PdfWriter;public class HelloWorld {    public static void main(String[] args) throws FileNotFoundException, DocumentException {        // 生成File所在文件夹        String filename = "D:/iTextDemo/HelloWorld.pdf";        File file = new File(filename);        file.getParentFile().mkdirs();        // 生成PDF文档        Document document = new Document();        PdfWriter.getInstance(document, new FileOutputStream(filename));        document.open();        document.add(new Paragraph("Hello World!"));        document.close();    }}

    运行一下,就能在”D:/iTextDemo”目录下找到生成的第一个文件HelloWorld.pdf了。

  3. 解释一下第一个例子
    先能运行,然后分析其中的原理:
    Document类:等于是一个PDF文件,类似于File的存在。
    PdfWriter类:看名字就知道啦,Writer,用于写文件。
    Paragraph类:类名翻译过来是“段落”,一般是代表一段文字(小学学的“自然段”),其实也可以包含一些非文字的内容,这个下次再说。

    所以HelloWorld中的关键代码加上注释就是这样的:

    // 生成一个默认属性的PDF文件Document document = new Document();// 定义一个输出流,将内容写入到filename中PdfWriter.getInstance(document, new FileOutputStream(filename));// 开始写文件document.open();// 加入一段话“Hello World!”document.add(new Paragraph("Hello World!"));// 结束写入document.close();
  4. 解决中文问题
    在上面的例子中,如果将“Hello World!”换成中文的话,你会发现生成的文件中什么都没有,这是因为iText原本是不支持中文的,解决中文的方法有很多,这里只介绍一种最直接简单的:

    public class ChineseDisplay {    public static void main(String[] args) throws DocumentException, IOException {        // 生成File所在文件夹        String filename = "D:/iTextDemo/ChineseDisplay.pdf";        File file = new File(filename);        file.getParentFile().mkdirs();        // 中文字体        BaseFont fontChinese = BaseFont.createFont("C:/Windows/Fonts/STSONG.TTF", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);        Document document = new Document();        PdfWriter.getInstance(document, new FileOutputStream(filename));        document.open();        document.add(new Paragraph("你好,世界!", new Font(fontChinese, 12)));        document.close();    }}

    只比HelloWorld的例子多了一步生成Font,便解决了中文问题。(当然需要系统中有STSONG.TTF这个文件,在Windows7系统中这个文件的名字是“华文宋体 常规”)

  5. 学以致用,写封信吧
    有三个知识点:
    • Paragraph.setIndentationLeft(float indentation):整体缩进
    • Paragraph.setFirstLineIndent(float firstLineIndent):首行缩进
    • Paragraph.setAlignment(int alignment):设置对齐方式,Paragraph常用的对齐方式有3种
      • Element.ALIGN_LEFT:左对齐
      • Element.ALIGN_CENTER:居中
      • Element.ALIGN_RIGHT:右对齐
public class Letter {    public static void main(String[] args) throws DocumentException, IOException {        // 生成File所在文件夹        String filename = "D:/iTextDemo/Letter.pdf";        File file = new File(filename);        file.getParentFile().mkdirs();        // 中文字体        BaseFont fontChinese = BaseFont.createFont("C:/Windows/Fonts/STSONG.TTF", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);        Document document = new Document();        PdfWriter.getInstance(document, new FileOutputStream(filename));        document.open();        Font normalFont = new Font(fontChinese, 12);        Paragraph to = new Paragraph("亲爱的李雷:", normalFont);        document.add(to);        Paragraph hello = new Paragraph("你好!", normalFont);        hello.setIndentationLeft(24); // 整体缩进        document.add(hello);        Paragraph content = new Paragraph("我现在正在学习iText,正好写一封信给你,为了整点内容凑个换行,我这个不怎么擅长写作文的人也是拼了。", normalFont);        content.setFirstLineIndent(24); // 首行缩进        document.add(content);        Paragraph from = new Paragraph("韩梅梅\n2017年11月29日", normalFont);        from.setAlignment(Element.ALIGN_RIGHT); // 居右显示        document.add(from);        document.close();    }}
原创粉丝点击