原文来自:https://www.cnblogs.com/joann/p/5511905.html

我只是记录所有jar版本,由于版本冲突及不兼容很让人头疼的,一共需要5个jar,

其中itextpdf是itext的升级版本,并且itextpdf-5.5.jar以上版本算总页数不需要-1,之前版本必须-1;

jfinal.jar只能用2.0版本,用3.0的会报版本过高;希望能帮到有需要的人

itextpdf-5.5.13.jar 下载地址:http://central.maven.org/maven2/com/itextpdf/itextpdf/5.5.13/itextpdf-5.5.13.jar

freemarker-2.3.23.jar 下载地址:http://central.maven.org/maven2/org/freemarker/freemarker/2.3.23/freemarker-2.3.23.jar

jfinal-2.0.jar 下载地址:http://central.maven.org/maven2/com/jfinal/jfinal/2.0/jfinal-2.0.jar

xmlworker-5.5.11.jar 下载地址:http://central.maven.org/maven2/com/itextpdf/tool/xmlworker/5.5.11/xmlworker-5.5.11.jar

itext-asian-5.2.0.jar 下载地址:http://central.maven.org/maven2/com/itextpdf/itext-asian/5.2.0/itext-asian-5.2.0.jar

import java.io.ByteArrayInputStream;
import java.io.FileOutputStream;
import java.io.StringWriter;
import java.nio.charset.Charset;
import com.itextpdf.text.Document;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.tool.xml.XMLWorkerHelper;
import com.jfinal.log.Logger;
import com.jfinal.render.FreeMarkerRender;
import freemarker.template.Template; public class PdfKit {
private static final Logger log = Logger.getLogger(PdfKit.class);
/**
* 导出pdf
*
* @param templateView-freemarker模板相对路径
* @param os-输出流
* @param model-模板所需要的数据
* @throws Exception
*/
public static void export(String templateView,Object model,String temp) throws Exception {
log.info("生成的PDF地址:"+temp);
FileOutputStream tempOs = new FileOutputStream(temp);
Template template = FreeMarkerRender.getConfiguration().getTemplate(templateView);
StringWriter result = new StringWriter();
template.process(model, result);
String htmlData = result.toString();//模版变量
Document document = new Document(PageSize.A4);
PdfWriter writer = PdfWriter.getInstance(document, tempOs); //添加水印和页码
PDFBuilder builder = new PDFBuilder();
writer.setPageEvent(builder);
//打开文件
document.open();
//html文件解析
XMLWorkerHelper.getInstance().parseXHtml(writer, document,
new ByteArrayInputStream(htmlData.getBytes()), Charset.forName("UTF-8"));
//关闭
document.close();
} public static void main(String[] args) throws Exception {
//html模板路径只支持相对路径
String templateView="./web/itextpdf.html";
//生成pdf的路径支持绝对路径和相对路径
String temp="./web/pdf/itextpdf.pdf";
//中间模板对应数据model可为null
export(templateView,null,temp);
}
}

  

import java.io.IOException;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.Image;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.ColumnText;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfPageEventHelper;
import com.itextpdf.text.pdf.PdfTemplate;
import com.itextpdf.text.pdf.PdfWriter; /**
* 设置页面附加属性
*
*/
public class PDFBuilder extends PdfPageEventHelper { /**
* 页眉
*/
public String header = "itext测试页眉"; /**
* 文档字体大小,页脚页眉最好和文本大小一致
*/
public int presentFontSize = 12; /**
* 文档页面大小,最好前面传入,否则默认为A4纸张
*/
public Rectangle pageSize = PageSize.A4; // 模板
public PdfTemplate total; // 基础字体对象
public BaseFont bf = null; // 利用基础字体生成的字体对象,一般用于生成中文文字
public Font fontDetail = null; /**
*
* Creates a new instance of PdfReportM1HeaderFooter 无参构造方法.
*
*/
public PDFBuilder() { } /**
*
* Creates a new instance of PdfReportM1HeaderFooter 构造方法.
*
* @param yeMei
* 页眉字符串
* @param presentFontSize
* 数据体字体大小
* @param pageSize
* 页面文档大小,A4,A5,A6横转翻转等Rectangle对象
*/
public PDFBuilder(String yeMei, int presentFontSize, Rectangle pageSize) {
this.header = yeMei;
this.presentFontSize = presentFontSize;
this.pageSize = pageSize;
} public void setHeader(String header) {
this.header = header;
} public void setPresentFontSize(int presentFontSize) {
this.presentFontSize = presentFontSize;
} /**
*
* TODO 文档打开时创建模板
*
* @see com.itextpdf.text.pdf.PdfPageEventHelper#onOpenDocument(com.itextpdf.text.pdf.PdfWriter,
* com.itextpdf.text.Document)
*/
public void onOpenDocument(PdfWriter writer, Document document) {
total = writer.getDirectContent().createTemplate(50, 50);// 共 页 的矩形的长宽高
} /**
*
* TODO 关闭每页的时候,写入页眉,写入'第几页共'这几个字。
*
* @see com.itextpdf.text.pdf.PdfPageEventHelper#onEndPage(com.itextpdf.text.pdf.PdfWriter,
* com.itextpdf.text.Document)
*/
public void onEndPage(PdfWriter writer, Document document) {
this.addPage(writer, document);
//this.addWatermark(writer);
} //加分页
public void addPage(PdfWriter writer, Document document){
//设置分页页眉页脚字体
try {
if (bf == null) {
bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", false);
}
if (fontDetail == null) {
fontDetail = new Font(bf, presentFontSize, Font.NORMAL);// 数据体字体
}
} catch (DocumentException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} // 1.写入页眉
ColumnText.showTextAligned(writer.getDirectContent(),
Element.ALIGN_LEFT, new Phrase(header, fontDetail),
document.left(), document.top() + 20, 0);
// 2.写入前半部分的 第 X页/共
int pageS = writer.getPageNumber();
String foot1 = "第 " + pageS + " 页 /共";
Phrase footer = new Phrase(foot1, fontDetail); // 3.计算前半部分的foot1的长度,后面好定位最后一部分的'Y页'这俩字的x轴坐标,字体长度也要计算进去 = len
float len = bf.getWidthPoint(foot1, presentFontSize); // 4.拿到当前的PdfContentByte
PdfContentByte cb = writer.getDirectContent(); // 5.写入页脚1,x轴就是(右margin+左margin + right() -left()- len)/2.0F
// 再给偏移20F适合人类视觉感受,否则肉眼看上去就太偏左了
// ,y轴就是底边界-20,否则就贴边重叠到数据体里了就不是页脚了;注意Y轴是从下往上累加的,最上方的Top值是大于Bottom好几百开外的。
ColumnText
.showTextAligned(
cb,
Element.ALIGN_CENTER,
footer,
(document.rightMargin() + document.right()
+ document.leftMargin() - document.left() - len) / 2.0F + 20F,
document.bottom() - 20, 0); // 6.写入页脚2的模板(就是页脚的Y页这俩字)添加到文档中,计算模板的和Y轴,X=(右边界-左边界 - 前半部分的len值)/2.0F +
// len , y 轴和之前的保持一致,底边界-20
cb.addTemplate(total, (document.rightMargin() + document.right()
+ document.leftMargin() - document.left()) / 2.0F + 20F,
document.bottom() - 20); // 调节模版显示的位置 } //加水印
public void addWatermark(PdfWriter writer){
// 水印图片
Image image;
try {
image = Image.getInstance("./web/images/001.jpg");
PdfContentByte content = writer.getDirectContentUnder();
content.beginText();
// 开始写入水印
for(int k=0;k<5;k++){
for (int j = 0; j <4; j++) {
image.setAbsolutePosition(150*j,170*k);
content.addImage(image);
}
}
content.endText();
} catch (IOException | DocumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} /**
*
* TODO 关闭文档时,替换模板,完成整个页眉页脚组件
*
* @see com.itextpdf.text.pdf.PdfPageEventHelper#onCloseDocument(com.itextpdf.text.pdf.PdfWriter,
* com.itextpdf.text.Document)
*/
public void onCloseDocument(PdfWriter writer, Document document) {
// 7.最后一步了,就是关闭文档的时候,将模板替换成实际的 Y 值,至此,page x of y 制作完毕,完美兼容各种文档size。
total.beginText();
total.setFontAndSize(bf, presentFontSize);// 生成的模版的字体、颜色
String foot2 = " " + (writer.getPageNumber()) + " 页"; //页脚内容拼接 如 第1页/共2页
total.showText(foot2);// 模版显示的内容
total.endText();
total.closePath();
}
}

  

import com.itextpdf.text.Font;
import com.itextpdf.tool.xml.XMLWorkerFontProvider;
/**
* 设置pdf内容字体类型,注意字体与html页面字体一致
*/
public class AsianFontProvider extends XMLWorkerFontProvider {
@Override
public Font getFont(final String fontname, String encoding, float size, final int style){
String fntname = fontname;
if (fntname == null) {
fntname = "fonts/simsun.ttc";
}
if(size == 0){
size = 4;
}
return super.getFont(fntname,encoding,size,style);
}
}

  

itext 生成pdf文件添加页眉页脚的更多相关文章

  1. Java Itext 生成PDF文件

    利用Java Itext生成PDF文件并导出,实现效果如下: PDFUtil.java package com.jeeplus.modules.order.util; import java.io.O ...

  2. Itext生成pdf文件

    来源:https://my.oschina.net/lujianing/blog/894365 1.背景 在某些业务场景中,需要提供相关的电子凭证,比如网银/支付宝中转账的电子回单,签约的电子合同等. ...

  3. 【Java】使用iText生成PDF文件

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

  4. 关于java poi itext生成pdf文件的例子以及方法

    最近正在做导出pdf文件的功能,所以查了了一些相关资料,发现不是很完善,这里做一些小小的感想,欢迎各位“猿”童鞋批评指正. poi+itext,所需要的jar包有itext-2.1.7.jar,poi ...

  5. 使用iText生成pdf文件

    前言 折腾了一早上的iText,下面主要介绍一下如何使用iText通过java代码生成pdf文档,以及如何输出包含中文的pdf文档. 首先,要说明的是,我用的是iText-7(java),下载链接是: ...

  6. iText + Freemarker实现pdf的导出,支持中文、css以及图片,页眉页脚,页眉添加图片

    本文为了记录自己的实现过程,具体的实现步骤是参考博文 https://www.cnblogs.com/youzhibing/p/7692366.html 来实现的,只是在他的基础上添加了页眉页脚及页眉 ...

  7. c# iText 生成PDF 有文字,图片,表格,文字样式,对齐方式,页眉页脚,等等等,

    #region 下载说明书PDF protected void lbtnDownPDF_Click(object sender, EventArgs e) { int pid = ConvertHel ...

  8. ★itext-为pdf文件添加页眉页脚 | 3步完成 |

    由于上一篇自定义生成pdf的功能需求又增加了,需要加上页码.所以本博客诞生了~ 1. 通过继承PdfPageEventHelper类,实现需要实现的方法 import com.lowagie.text ...

  9. 【Itext】7步制作Itext5页眉页脚pdf实现第几页共几页

    itext5页眉页脚工具类,实现page x of y 完美兼容各种格式大小文档A4/B5/B3,兼容各种文档格式自动计算页脚XY轴坐标 鉴于没人做的这么细致,自己就写了一个itext5页眉页脚工具类 ...

随机推荐

  1. 第191天:js---Array常用属性和方法总结

    Array---常用属性和方法总结 1.Array对象构造函数 /*Array对象构造函数*/ /*组合记忆 shift unshift pop push 添加和删除 shift unshift 从数 ...

  2. bzoj4032-最短不公共子串

    题意 给出两个长度小于等于2000的小写字母串,四个问题: A的最短子串不是B的子串 A的最短子串不是B的子序列 A的最短子序列不是B的子串 A的最短子序列不是B的子序列 分析 虽然求的是不公共,但是 ...

  3. BZOJ 2186 沙拉公主的困惑(预处理逆元+欧拉函数)

    题意:求1-n!里与m!互质的数有多少?(m<=n<=1e6). 因为n!%m!=0,所以题目实际上求的是phi(m!)*n!/m!. 预处理出这些素数的逆元和阶乘的模即可. # incl ...

  4. 【bzoj3697】采药人的路径 树的点分治

    题目描述 给出一棵 $n$ 个点的树,每条边的边权为1或0.求有多少点对 $(i,j)$ ,使得:$i$ 到 $j$ 的简单路径上存在点 $k$ (异于 $i$ 和 $j$ ),使得 $i$ 到 $k ...

  5. wp开发(一)--应用发布篇

    本文非常简单,适合刚刚刚刚入门的菜鸟,且针对的是wp8版本.wp8应用的发布总体来说没什么难度,只是有几个值得注意的地方,希望本文可以减少菜鸟们不必要的担心. 首先假设项目已经完成,且要发布到应用商城 ...

  6. MD5加密概述

    一.Note: 写到这篇文章是工作中实际遇到了,以前都听过不过没有细看.这里简单概述下,原理的话需要看看更专业的介绍了. 二.MD5简介 Message Digest Algorithm MD5(中文 ...

  7. 用户缓冲式I/O

    2018-08-05 (星期日)缓冲式I/O    所有磁盘操作都是按照块来进行的,因此,若所送出的I/O请求,其对齐块便捷为实际块大小的整数倍,则可以优化I/O的性能.    读取操作需要进行的系统 ...

  8. bzoj2396: 神奇的矩阵(矩阵乘法+随机化)

    这题n三方显然会GG... 运用矩阵乘法的性质A*B*R=A*(B*R)=C*R,于是随机化出一个一列的R,就可以把复杂度降低成n方...大概率是不会错的 #include<iostream&g ...

  9. [雅礼集训 2017 Day1]市场

    link 试题分析 可以容易发现此题维护的是一个数据结构,支持区间加,区间除,区间查询最大值.其实就是在$\log$级复杂度内维护除法操作. 我们发现当除数很大或者此串序列大小差不多时,我们令$a_i ...

  10. 使用pt-ioprofile监控数据库io文件读写情况

    我们在做IO密集型的应用程序的时候,比如MySQL数据库,通常系统的表现取决于workload的类型. 比如我们要调优,我们就必须非常清楚的知道数据的访问规律,收集到足够的数据,用来做调优的依据. 有 ...