欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

生成pdf文档 插入签名图片

程序员文章站 2024-03-21 14:45:34
...

描述:生成pdf文档,包括标题 正文 签名图片,生成正式的签名文档

/**
 * 下载签名文档
 * @param detailId
 * @param request
 * @param response
 */
public void export(long detailId, HttpServletRequest request, HttpServletResponse response) throws Exception {
	// 文件名
	String fn = uploadFoldName.concat(System.currentTimeMillis()+"").concat(".pdf");
	//创建一个文档对象
	Document doc = new Document();
	float documentWidth = doc.getPageSize().getWidth() - doc.leftMargin() - doc.rightMargin();
	float documentHeight = doc.getPageSize().getHeight() - doc.topMargin() - doc.bottomMargin();
	// 定义输出位置并把文档对象装入输出对象中
	PdfWriter.getInstance(doc, new FileOutputStream(fn));
	// 打开文档对象
	doc.open();
	// 设置中文字体
	BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
	Font font = new Font(bfChinese, 13, Font.BOLD);
	//粗体,字体大小12
	Font blodFont= new Font(bfChinese, 12,Font.NORMAL);
	// title
	String title = "这是标题";
	Paragraph tt = new Paragraph(title, font);
	tt.setAlignment(Element.TITLE);
	// 段落
	Paragraph ttk = new Paragraph("     ", font);

	// 内容
	String content = "这是内容";
	Paragraph tt2 = new Paragraph(content, blodFont);
	tt2.setLeading(15f);
	tt2.setIndentationLeft(20);
	tt2.setAlignment(Element.BODY);
	tt2.setFirstLineIndent(15);
	doc.add(tt);
	doc.add(ttk);
	doc.add(tt2);
	// 加入图片Deepinpl.jpg
	Image image = Image.getInstance("图片url");
	image.scaleAbsolute(150, 80);//重新设置宽高
	image.setAlignment(Element.ALIGN_RIGHT);
	doc.add(image);

	Paragraph tt3 = new Paragraph("这是签名时间2019.1.1", blodFont);
	tt3.setAlignment(Element.ALIGN_BOTTOM);
	tt3.setIndentationLeft(documentWidth-110);
	doc.add(tt3);
	// 关闭文档对象,释放资源
	doc.close();

	File file = new File(fn);
	//设置response的编码方式
	response.setContentType("application/x-msdownload");
	// 文件尺寸
	response.setContentLength((int)file.length());

	String filename = new String(file.getName().getBytes("GB2312"), "ISO_8859_1");
	response.setHeader("Content-Disposition","attachment;filename=" + filename);
	response.setHeader("Pragma","no-cache");
	OutputStream myout = response.getOutputStream();
	if(file.exists()){
		FileInputStream fis = new FileInputStream(file);
		BufferedInputStream buff = new BufferedInputStream(fis);
		byte [] b = new byte[1024];
		long k = 0;
		while(k < file.length()){
			int j = buff.read(b,0,1024);
			k += j;
			myout.write(b,0,j);
			myout.flush();
		}
		buff.close();
	}
	myout.close();

	// 删除pdf
	File pdfFile = new File(fn);
	if(pdfFile.exists()){
		pdfFile.delete();
	}
}