使用itextpdf操作pdf的实例讲解

时间:2022-03-08 09:46:04

使用maven引入jar

?
1
2
3
4
5
6
7
8
9
10
<dependency>
  <groupId>com.itextpdf</groupId>
  <artifactId>itextpdf</artifactId>
  <version>5.2.0</version>
</dependency>
<dependency>
  <groupId>com.itextpdf</groupId>
  <artifactId>itext-asian</artifactId>
  <version>5.2.0</version>
</dependency>

创建exportToPDF工具类

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
package com.os.core.util.file.exportPdf;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.FontSelector;
import com.itextpdf.text.pdf.PdfWriter;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
/**
 * Created by PengSongHe on 2016/10/20 0020.
 */
public class exportToPDF {
  public static void main(String[] args) {
    try {
      Document document = new Document();//默认A4
      PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("d:/HelloWorld.pdf"));
      writer.setPdfVersion(PdfWriter.PDF_VERSION_1_7);
      document.addCreationDate();
      document.addCreator("飞翔家族");
      document.addTitle("export pdf");
      document.addKeywords("export");
      document.addSubject("飞翔家族 export pdf");
      document.open();
//处理中文,需要itextasian.jar支持
      FontSelector selector = new FontSelector();
      selector.addFont(FontFactory.getFont(FontFactory.TIMES_ROMAN, 12));
      selector.addFont(FontFactory.getFont("STSongStd-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED));
      Phrase phrase = selector.process("HelloWord!你好。\u4fdd\u5b58");
      document.add(new Paragraph(phrase));
      //添加新页
      //document.newPage();
      //writer.setPageEmpty(false);
      //document.add(new Paragraph("New page"));
      document.close();
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (DocumentException e) {
      e.printStackTrace();
    }
  }
}

以上这篇使用itextpdf操作pdf的实例讲解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持服务器之家。

原文链接:http://blog.csdn.net/psh18513234633/article/details/78893818