Java生成PDF文档一

什么是iText?

iText是著名的开放源码的站点sourceforge一个项目,是用于生成PDF文档的一个java类库。通过iText不仅可以生成PDF或rtf的文档,而且可以将XML、Html文件转化为PDF文件。 

iText 官网:http://itextpdf.com/

iText 开发文档: http://developers.itextpdf.com/developers-home

iText目前有两套版本iText5和iText7。iText5应该是网上用的比较多的一个版本。iText5因为是很多开发者参与贡献代码,因此在一些规范和设计上存在不合理的地方。iText7是后来官方针对iText5的重构,两个版本差别还是挺大的。不过在实际使用中,一般用到的都比较简单,所以不用特别拘泥于使用哪个版本。比如我们在http://mvnrepository.com/中搜索iText,出来的都是iText5的依赖。

如果对您有帮助 ,请多多支持.多少都是您的心意与支持,一分也是爱,再次感谢!!!打开支付宝首页搜“556723462”领红包,领到大红包的小伙伴赶紧使用哦!

 支付宝赞赏:记得点击下面的余额宝,红包可能要大些。

注意:余额宝红包有效期三天(72小时) 在有效期内
余额宝红包使用完或过期才能有机会领取下个余额宝红包,感谢大家的支持!您的支持,我会继续分享更多的文章,欢迎关注!

一:创建maven项目,加入依赖

<dependency>
			<groupId>com.itextpdf</groupId>
			<artifactId>itextpdf</artifactId>
			<version>5.4.2</version>
		</dependency>
		<!--pdf itext 的jar依赖  -->
		<dependency>
			<groupId>com.itextpdf</groupId>
			<artifactId>itext-asian</artifactId>
			<version>5.2.0</version>
		</dependency>

二:生成不带中文的pdf与带中文的pdf,因iText是不支持中文字体的,所以需要下载你所需要的字体。

package com.demo2;

import java.io.FileOutputStream;

import com.itextpdf.text.Document;
import com.itextpdf.text.Font;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfWriter;

public class Test1 {
	public static void main(String[] args) {
		test1();// 调用
		test2();// 调用
	}

	// 生成pdf
	public static void test1() {
		Document document = new Document();
		try {
			PdfWriter.getInstance(document, new FileOutputStream("target/1.pdf"));
			document.open();
			document.add(new Paragraph("hello word"));
			document.close();
		} catch (Exception e) {
			System.out.println("file create exception");
		}
	}

	// 生成带中文的pdf
	public static void test2() {
		BaseFont bf;
		Font font = null;
		try {
			bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);// 创建字体
			font = new Font(bf, 12);// 使用字体
		} catch (Exception e) {
			e.printStackTrace();
		}
		Document document = new Document();
		try {
			PdfWriter.getInstance(document, new FileOutputStream("target/2.pdf"));
			document.open();
			document.add(new Paragraph("hello word 你好 世界", font));// 引用字体
			document.close();
		} catch (Exception e) {
			System.out.println("file create exception");
		}
	}

}

三:对应生成的效果如下:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值