java导出pdf

概要

java利用itextpdf导出pdf

maven包进入

		<dependency>
			<groupId>com.itextpdf</groupId>
			<artifactId>itextpdf</artifactId>
			<version>5.5.13.3</version>
		</dependency>
		<dependency>
			<groupId>com.itextpdf</groupId>
			<artifactId>itext-asian</artifactId>
			<version>5.2.0</version>
		</dependency>

工具类

import com.itextpdf.text.*;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfWriter;
import org.apache.commons.lang3.StringUtils;

import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class PdfUtils {

	Font fontHead = null;

	Font fontKey = null;

	Font fontValue = null;

	Document document = null;

	PdfWriter writer = null;

	public PdfUtils(String path) throws DocumentException, IOException {
		BaseFont bf = BaseFont.createFont("/simfang.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);// 仿宋
		fontHead = new Font(bf, 20, Font.BOLD);
		fontKey = new Font(bf, 16, Font.NORMAL);
		fontValue = new Font(bf, 16, Font.UNDERLINE);

		document = new Document();
		writer = PdfWriter.getInstance(document, new FileOutputStream(path));
		document.open();
	}

	public void writeHeading(String title) throws DocumentException {
		Paragraph heading = new Paragraph(title, fontHead);
		heading.setAlignment(Element.ALIGN_CENTER);
		document.add(heading);
	}

	public void writePara(String content) throws DocumentException, IOException {
		writePara(content, null, null, null, null);
	}

	public void writePara(String content, Float indent, Boolean isRightAlign, Float fitWidth, Float leading)
			throws DocumentException, IOException {
		if (StringUtils.isNotEmpty(content)) {
			content = content.replace("null", "");
		}
		Paragraph p;
		if (content.contains("%")) {
			p = new Paragraph("");

			String[] split = content.split("%");
			for (int i = 0; i < split.length; i++) {
				Phrase phrase = new Phrase(split[i], i % 2 == 0 ? fontKey : fontValue);
				if (split[i].startsWith("#img#")) {
					phrase = new Phrase("", fontKey);
					if (split[i].length() > 5) {
						String imgPath = split[i].substring(5);
						if (StringUtils.isNotEmpty(imgPath) && !imgPath.equals("null")) {
							Image img = Image.getInstance(new URL(imgPath));
							if (fitWidth != null) {
								float realWidth = img.getWidth();
								float realHeight = img.getHeight();
								float targetHeight = realHeight * fitWidth / realWidth;
								img.scaleToFit(fitWidth, targetHeight);
							}
							Chunk chunk = new Chunk(img, 0, -10, false);
							phrase.add(chunk);
						}
					}
					else {
						Chunk chunk = new Chunk("          ");
						phrase.add(chunk);
					}
				}
				p.add(phrase);
			}
		}
		else {
			p = new Paragraph(content, fontKey);
		}
		if (indent != null) {
			p.setFirstLineIndent(indent);
		}
		if (isRightAlign != null && isRightAlign == true) {
			p.setAlignment(Element.ALIGN_RIGHT);
		}
		// p.setSpacingBefore(4);空2汉字
		if (leading != null) {
			p.setLeading(leading);
		}

		document.add(p);
	}

	public void end() throws IOException, InterruptedException {
		document.close();
	}

}

使用示例

String getEntrustFile(PdfFileReq pdfFileReq) {
		String testFile = "";
		try {
			String nfName = FileUtil.getTmpDir().getAbsolutePath() + File.separator + UUID.randomUUID() + ".pdf";
			PdfUtils pdf = new PdfUtils(nfName);
			pdf.writeHeading("*****授权委托书");
			pdf.writePara("一、委托人信息");
			pdf.writePara("委托人姓名:%" + pdfFileReq.getName());
			pdf.writePara("委托人身份证号:%" + pdfFileReq.getIdCard());
			pdf.writePara("委托人联系号码:%" + pdfFileReq.getPhone());
			pdf.writePara("委托人联系地址:%" + pdfFileReq.getAddress());
			...
			pdf.writePara("四、委托人声明");
			pdf.writePara("委托人在此声明,本委托事项未涉及任何违法、违规行为。如因委托事项引发的法律纠纷、责任追究等事项,应由委托人自行承担相应责任。");
			pdf.writePara("\n");
			pdf.writePara("受托人签字:%" + pdfFileReq.getTenantName(), null, false, 30f, 10f);
			pdf.writePara("受托人盖章:", null, false, null, 20f);
			pdf.writePara("日期:%" + DateUtil.format(new Date(), "yyyy年MM月dd日"));
			pdf.writePara("\n");
			pdf.writePara("委托人签字:%#img#" + pdfFileReq.getEntrustSignImg() + "%", null, false, 50f, null);
			pdf.writePara("委托人盖章:", null, false, null, 20f);
			pdf.writePara("日期:%" + DateUtil.format(new Date(), "yyyy年MM月dd日"));

			pdf.end();
			File nf = new File(nfName);
			...
		}
		catch (Exception ex) {
			log.error("create pdf error.vin={}", pdfFileReq.getVin(), ex);
		}
		log.info("getEntrustFile fileurl=" + testFile);
		return testFile;
	}

注意事项

1.字体文件需要指定到路径
2.打印排版需要按照实际业务调试

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值