java使用itext生成pdf

import java.io.FileOutputStream;
import java.util.UUID;

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

public class PdfUtils {
	/**
	 * 引入itextpdf.jar
	 */
	public static void test(String name) {
		Document document = new Document(PageSize.A4,50, 50, 50, 50);
		try {
			String resoure = PdfUtils.class.getResource("/").getPath();//获取src下的根路径
			String fontPath = resoure +"font/NotoSansCJKsc-Regular.otf";//中文字体路径
			BaseFont bfChinese = BaseFont.createFont(fontPath, BaseFont.IDENTITY_H,BaseFont.NOT_EMBEDDED);
			Font FontChinese12 = new Font(bfChinese, 12, Font.NORMAL);
			Font FontChinese16 = new Font(bfChinese, 16, Font.NORMAL);
			PdfWriter.getInstance(document, new FileOutputStream("G:/wxcreatebuy/file/"+UUID.randomUUID().toString()+".pdf"));
			document.open();
			Paragraph p0 = new Paragraph(name,FontChinese16);
			document.add(p0);
			Paragraph p1 = new Paragraph("徐志摩曾说过:“一生中至少该有一次,为了某个人而忘记了自己,不求结果,不求同行。",FontChinese12);
			document.add(p1);
			Paragraph p2 = new Paragraph("还记得初相识时你那拘谨的样子,话不是很多只是坐在那里听我不停地说着各种不着边际的话。",FontChinese12);
			document.add(p2);
			Image image = Image.getInstance(resoure+"img/aa.png");
			image.setAbsolutePosition(50, 500);//设置坐标
			image.scaleAbsolute(100, 100);//设置大小
			document.add(image);
		} catch (Exception e) {
			e.printStackTrace();
		}
		document.close();
	}
}

你可能感兴趣的:(java,后端)