java使用itextpdf生成PDF批量打印荣誉证书(指定位置输出文字)

       最近公司项目有个需求,批量打印荣誉证书,一开始尝试过传统的Web打印,控件打印,js调用浏览器打印方法,遇到各种问题,比如定位不准,分页问题,缩放问题等。然后就自己研究,整理了一套打印方案,项目已测试通过,现在把这一成果分享给大家。

下面,我会提供一个工具类,这个工具类里,会有两种打印方案:

一.  把要打印的内容,放到html代码中,然后解析html(虽然支持解析样式,由于支持的样式非常少,字体字号样式都不支持,所以这种方式并没有太大意义),解析后生成pdf文件,然后下载到客户端。

二.先生成多页的空白PDF,然后将文字通过添加水印(可设置透明度)的方式,输出指定位置。

注意事项:在这个过程中,会产生一些临时文件,注意临时文件存放目录,由于项目运行时必然有并发问题,临时文件名一定要取时间戳或UUID这种不会重复的名字,还有临时文件使用完成后要及时删除,删除前要关闭  IO流对象,pdf书写器对象(关闭要由外到里,一定要close掉,因为 JVM 的GC 无法回收这些资源,否则是不能删除这些被占用的临时文件的)

package com.chinauip.contract.service.contract;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.UUID;


import javax.servlet.http.HttpServletRequest;


import org.apache.commons.lang.StringUtils;


import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Document;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.FontProvider;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfCopy;
import com.itextpdf.text.pdf.PdfGState;
import com.itextpdf.text.pdf.PdfImportedPage;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.tool.xml.XMLWorkerHelper;


/**
 * 
 * @author YuGongWen 2018年6月27日 上午8:20:31 PackagePath :
 *         com.chinauip.contract.service.contract.pdfPrintUtil.java
 *
 */
public class pdfPrintUtil {


/**
* 生成打印pdf文件(多个企业)

* @param printParam
* @return
* @throws Exception
*/
public static String creatPdf(List<Map<String, Object>> printParam, String modeltype, String path) throws Exception {
List<String> files = new ArrayList<String>();
for (int i = 0; i < printParam.size(); i++) {
String filePath = new pdfPrintUtil().createSinglePdf(path, printParam.get(i), modeltype);
files.add(filePath);
}
String savepath = path + String.valueOf(new Date().getTime()) + ".pdf";
savepath = mergePdfFiles(files, savepath);
for (int i = 0; i < files.size(); i++) {
forceDelete(files.get(i));
}
System.out.println("合成pdf的路径:" + savepath);
return savepath;
}
 
/**
* 生成html模板代码(模板1)

* @param parMap
* @return
* @throws UnsupportedEncodingException
*/
public static String getHtml1(Map<String, Object> parMap) throws UnsupportedEncodingException {
String certificate_number = parMap.get("certificate_number") != null ? parMap.get("certificate_number").toString() : "";
String year = parMap.get("year") != null ? parMap.get("year").toString() : "";
String enterprise_name = parMap.get("enterprise_name") != null ? parMap.get("enterprise_name").toString() : "";
String month = parMap.get("month") != null ? parMap.get("month").toString() : "";
String day = parMap.get("day") != null ? parMap.get("day").toString() : "";
String first_time = parMap.get("first_time") != null ? parMap.get("first_time").toString() : "";
StringBuffer html = new StringBuffer();
html.append("<div id='model1' align='center'>");
html.append("<div style='margin-left:60px' align='center'>");
html.append("<table border='1' style='width: 100%;height: 100%;'>");


html.append("<tr style='height:100px;'>");
html.append("<td style='width:60%;'>");
html.append("</td>");
html.append("<td style='width:40%'>");
html.append("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" + year);
html.append("</td>");
html.append("</tr>");


html.append("<tr style='height:100px;'>");
html.append("<td style='font-family: 楷体';>");
html.append("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;");
html.append(
"&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;");
html.append(
"&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;");
html.append(
"&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;");
html.append(
"&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;");
html.append("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"
+ certificate_number + "<br />");
html.append("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;");
html.append("<font size='15'>");
html.append(enterprise_name);
html.append("</font> ");


html.append("</td>");
html.append("<td>");
html.append("</td>");
html.append("</tr>");


html.append("<tr style='height:100px;'>");
html.append("<td>");
html.append("</td>");
html.append("<td>");
html.append("</td>");
html.append("</tr>");


html.append("<tr style='height:100px;'>");
html.append("<td>");
html.append("</td>");
html.append("<td>");
html.append("</td>");
html.append("</tr>");


html.append("<tr style='height:100px;'>");
html.append("<td>");
html.append("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;");
html.append("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;");
html.append("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;");
html.append(year + "&nbsp;&nbsp;&nbsp;" + month + "&nbsp;&nbsp;&nbsp;" + day);
html.append("</td>");
html.append("<td></td>");
html.append("</tr>");


html.append("<tr style='height:100px;'>");
html.append("<td>");
html.append("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;");
html.append("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;");
// html.append("${list.first_time}");
html.append(first_time);
html.append("</td>");
html.append("<td></td>");
html.append("</tr>");


html.append("</table>");
html.append("</div>");
html.append("</div>");
return html.toString();
}


/**
* 生成html模板代码(模板2)

* @param parMap
* @return
* @throws UnsupportedEncodingException
*/
public static String getHtml2(Map<String, Object> parMap) throws UnsupportedEncodingException {
String year = parMap.get("year") != null ? parMap.get("year").toString() : "";
String enterprise_name = parMap.get("enterprise_name") != null ? parMap.get("enterprise_name").toString() : "";
String month = parMap.get("month") != null ? parMap.get("month").toString() : "";
String day = parMap.get("day") != null ? parMap.get("day").toString() : "";
String first_time = parMap.get("first_time") != null ? parMap.get("first_time").toString() : "";
StringBuffer html = new StringBuffer();
html.append("<div id='model2' align='center'>");
html.append("<div align='center'>");
html.append("<table border='0' style='width: 80%;height: 80%'>");
html.append("<tr>");
html.append("<td>");
html.append("</td>");
html.append("<td>");
html.append("</td>");
html.append("</tr>");


html.append("<tr>");
html.append("<td width='70%'>");
html.append("</td>");
html.append("<td>");
html.append("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" + year);
html.append("</td>");
html.append("</tr>");


html.append("<tr>");
html.append("<td>");
html.append("</td>");
html.append("<td>");
html.append("</td>");
html.append("</tr>");


html.append("<tr>");
html.append("<td>");
html.append("</td>");
html.append("<td>");
html.append("</td>");
html.append("</tr>");


html.append("<tr>");
html.append("<td>");
html.append("</td>");
html.append("<td></td>");
html.append("</tr>");


html.append("<tr>");
html.append("<td>");
html.append("</td>");
html.append("<td></td>");
html.append("</tr>");


html.append("</table>");
html.append("</div>");
html.append("</div>");
return html.toString();
}


/**
* 生成html模板代码(模板3)

* @param parMap
* @return
* @throws UnsupportedEncodingException
*/
public static String getHtml3(Map<String, Object> parMap) throws UnsupportedEncodingException {
String year = parMap.get("year") != null ? parMap.get("year").toString() : "";
String enterprise_name = parMap.get("enterprise_name") != null ? parMap.get("enterprise_name").toString() : "";
String month = parMap.get("month") != null ? parMap.get("month").toString() : "";
String day = parMap.get("day") != null ? parMap.get("day").toString() : "";
String first_time = parMap.get("first_time") != null ? parMap.get("first_time").toString() : "";
StringBuffer html = new StringBuffer();
html.append("<div id='model3' align='center'>");
html.append("<table border='0' style='width: 80%;height: 80%'>");
html.append("<tr>");
html.append("<td>");
html.append("</td>");
html.append("<td>");
html.append("</td>");
html.append("</tr>");


html.append("<tr>");
html.append("<td>");
html.append("</td>");
html.append("<td>");
html.append("</td>");
html.append("</tr>");


html.append("<tr>");
html.append("<td width='70%'>");
html.append("</td>");
html.append("<td>");
html.append("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" + year);
html.append("</td>");
html.append("</tr>");


html.append("<tr>");
html.append("<td>");
html.append("</td>");
html.append("<td>");
html.append("</td>");
html.append("</tr>");


html.append("<tr>");
html.append("<td>");
html.append("</td>");
html.append("<td></td>");
html.append("</tr>");


html.append("<tr>");
html.append("<td>");
html.append("</td>");
html.append("<td></td>");
html.append("</tr>");


html.append("</table>");
html.append("</div>");
return html.toString();
}


/**
* 生成html模板代码(模板4)

* @param parMap
* @return
* @throws UnsupportedEncodingException
*/
public static String getHtml4(Map<String, Object> parMap) throws UnsupportedEncodingException {
String year = parMap.get("year") != null ? parMap.get("year").toString() : "";
String enterprise_name = parMap.get("enterprise_name") != null ? parMap.get("enterprise_name").toString() : "";
String month = parMap.get("month") != null ? parMap.get("month").toString() : "";
String day = parMap.get("day") != null ? parMap.get("day").toString() : "";
String first_time = parMap.get("first_time") != null ? parMap.get("first_time").toString() : "";
StringBuffer html = new StringBuffer();
html.append("<div id='model4' align='center'>");
html.append("<table border='0' style='width: 80%;height: 80%'>");
html.append("<tr>");
html.append("<td>");
html.append("</td>");
html.append("<td>");
html.append("</td>");
html.append("</tr>");


html.append("<tr>");
html.append("<td>");
html.append("</td>");
html.append("<td>");
html.append("</td>");
html.append("</tr>");


html.append("<tr>");
html.append("<td>");
html.append("</td>");
html.append("<td>");
html.append("</td>");
html.append("</tr>");


html.append("<tr>");
html.append("<td width='70%'>");
html.append("</td>");
html.append("<td>");
html.append("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" + year);
html.append("</td>");
html.append("</tr>");


html.append("<tr>");
html.append("<td>");
html.append("</td>");
html.append("<td></td>");
html.append("</tr>");


html.append("<tr>");
html.append("<td>");
html.append("</td>");
html.append("<td></td>");
html.append("</tr>");


html.append("</table>");
html.append("</div>");
return html.toString();
}


/**
* 生成html模板代码(模板5)

* @param parMap
* @return
* @throws UnsupportedEncodingException
*/
public static String getHtml5(Map<String, Object> parMap) throws UnsupportedEncodingException {
String year = parMap.get("year") != null ? parMap.get("year").toString() : "";
String enterprise_name = parMap.get("enterprise_name") != null ? parMap.get("enterprise_name").toString() : "";
String month = parMap.get("month") != null ? parMap.get("month").toString() : "";
String day = parMap.get("day") != null ? parMap.get("day").toString() : "";
String first_time = parMap.get("first_time") != null ? parMap.get("first_time").toString() : "";
StringBuffer html = new StringBuffer();
html.append("<div id='model5' align='center'>");
html.append("<table border='0' style='width: 80%;height: 80%'>");
html.append("<tr>");
html.append("<td>");
html.append("</td>");
html.append("<td>");
html.append("</td>");
html.append("</tr>");


html.append("<tr>");
html.append("<td>");
html.append("</td>");
html.append("<td>");
html.append("</td>");
html.append("</tr>");


html.append("<tr>");
html.append("<td>");
html.append("</td>");
html.append("<td>");
html.append("</td>");
html.append("</tr>");


html.append("<tr>");
html.append("<td>");
html.append("</td>");
html.append("<td></td>");
html.append("</tr>");


html.append("<tr>");
html.append("<td width='70%'>");
html.append("</td>");
html.append("<td>");
html.append("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" + year);
html.append("</td>");
html.append("</tr>");


html.append("<tr>");
html.append("<td>");
html.append("</td>");
html.append("<td></td>");
html.append("</tr>");


html.append("</table>");
html.append("</div>");
return html.toString();
}


/**

* 提供中文

*/
public static final class ChinaFontProvide implements FontProvider {
@Override
public Font getFont(String arg0, String arg1, boolean arg2, float arg3, int arg4, BaseColor arg5) {
BaseFont bfChinese = null;
try {
bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
} catch (Exception e) {
e.printStackTrace();
}
Font FontChinese = new Font(bfChinese, 12, Font.NORMAL);
return FontChinese;
}


@Override
public boolean isRegistered(String arg0) {
return false;
}
}


/**
* 合并pdf文件

* @param files
* @param savepath
* @throws Exception
*/
public static String mergePdfFiles(List<String> files, String savepath) throws Exception {
Document document = null;
FileOutputStream outfile = null;
PdfReader reader = null;
try {
document = new Document(new PdfReader(files.get(0)).getPageSize(1));
outfile = new FileOutputStream(savepath);
PdfCopy copy = new PdfCopy(document, outfile);
document.open();
for (int i = 0; i < files.size(); i++) {
reader = new PdfReader(files.get(i));
int n = reader.getNumberOfPages();
for (int j = 1; j <= n; j++) {
document.newPage();
PdfImportedPage page = copy.getImportedPage(reader, j);
copy.addPage(page);
}
reader.close();
}
} catch (Exception e) {
e.printStackTrace();
throw new Exception("merge-----生成pdf异常", e);
} finally {
document.close();
try {
outfile.close();
} catch (IOException e) {
e.printStackTrace();
}
reader.close();
}


return savepath;
}
 


/**
* 获取当前字符串的字符编码

* @param str
* @return
*/
public static String getEncoding(String str) {
String encode = "GB2312";
try {
if (str.equals(new String(str.getBytes(encode), encode))) {
String s = encode;
return s;
}
} catch (Exception exception) {
}
encode = "ISO-8859-1";
try {
if (str.equals(new String(str.getBytes(encode), encode))) {
String s1 = encode;
return s1;
}
} catch (Exception exception1) {
}
encode = "UTF-8";
try {
if (str.equals(new String(str.getBytes(encode), encode))) {
String s2 = encode;
return s2;
}
} catch (Exception exception2) {
}
encode = "GBK";
try {
if (str.equals(new String(str.getBytes(encode), encode))) {
String s3 = encode;
return s3;
}
} catch (Exception exception3) {
}
return "";
}


/**
* 删除文件

* @param pathname
* @return
* @throws IOException
*/
public static boolean deleteFile(String pathname) {
boolean result = false;
File file = new File(pathname);
if (file.exists()) {
result = file.delete();
if(result) {
System.out.println("文件已经被删除成功!!");
}else {
System.out.println("文件已经被删除失败!!");
}
}
return result;
}


/**
* 强制删除文件

* @param file
* @return
*/
public static boolean forceDelete(String filePath) {
File file = new File(filePath);
boolean result = file.delete();
int tryCount = 0;
while (!result && tryCount++ < 2) {
System.gc(); // 回收资源
result = file.delete();
// System.out.println("删除"+ tryCount +"次!");
}
return result;
}


/**
* 文件转byte[]

* @param file
* @return
*/
public static byte[] File2byte(File file) {
byte[] buffer = null;
try {
FileInputStream fis = new FileInputStream(file);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] b = new byte[1024];
int n;
while ((n = fis.read(b)) != -1) {
bos.write(b, 0, n);
}
fis.close();
bos.close();
buffer = bos.toByteArray();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return buffer;
}


 

/**
* 生成多页pdf
* @throws Exception 
*/
public static String createPrintPdfFile(String path,List<Map<String, String>> paramMapList,String modeltype) throws Exception {
// 生成空白pdf
Document document = new Document(PageSize.A4.rotate(), 0, 0, 0, 0);
String filepath = path + UUID.randomUUID() +".pdf";
FileOutputStream fileoutput = new FileOutputStream(filepath);
PdfWriter.getInstance(document, fileoutput);  
document.open();  
for(int i=0;i<paramMapList.size();i++) {
document.newPage();
// 不能为空,否则无法添加page
document.add(new Paragraph("  "));
}
document.close();
fileoutput.close();
// 在pdf中添加文字
String outputPath = path + UUID.randomUUID()+".pdf";
if ("1".equals(modeltype)) {
addWatermark(path,filepath, outputPath, paramMapList);
} else {
addWatermark2_5(path,filepath, outputPath, paramMapList,modeltype);
}
deleteFile(filepath);
return outputPath; 
}



/**
* 在pdf上添加文字
* @param path
* @param inputPath
* @param outputPath
* @param paramMapList
* @throws Exception
*/
private static void addWatermark(String path,String inputPath,String outputPath, List<Map<String, String>> paramMapList) throws Exception {
PdfReader pdfReader = new PdfReader(inputPath);
FileOutputStream fileoutputStream = new FileOutputStream(outputPath);
PdfStamper pdfStamper = new PdfStamper(pdfReader,fileoutputStream);
PdfContentByte content_company_name = null;
PdfContentByte content_certificate_number = null;
PdfContentByte content_month = null;
PdfContentByte content_day = null;
PdfContentByte content_continue_year = null;
PdfContentByte content_year = null;
PdfContentByte content_certificate_number_wenzi = null;
PdfContentByte content_yeardu = null;
PdfContentByte content_first_time = null;
BaseFont basefont_kaiti = null;
BaseFont basefont_songti = null;
PdfGState pdfGstate = new PdfGState();
basefont_kaiti = BaseFont.createFont(path+"font/kaiti.TTF", BaseFont.IDENTITY_H,BaseFont.NOT_EMBEDDED);
basefont_songti = BaseFont.createFont(path+"font/songti.TTF", BaseFont.IDENTITY_H,BaseFont.NOT_EMBEDDED);

// BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
try {
if (basefont_songti == null || basefont_kaiti == null) {
throw new Exception("生成打印pdf时,字体加载异常!!");
}
// 设置透明度为1.0   不透明
pdfGstate.setFillOpacity(1.0f);
int toPage = pdfStamper.getReader().getNumberOfPages();
for (int i = 1; i <= toPage; i++) {
Map<String, String> paremMap = paramMapList.get(i-1);

// 遍历,检查参数是否有空 或 null,有则抛出异常
Iterator<Map.Entry<String, String>> entries = paremMap.entrySet().iterator();
int count = 0;
while (entries.hasNext()) {
  count ++;
  Map.Entry<String, String> entry = entries.next(); 
//   System.out.println("Key  = " + entry.getKey() + ", Value = " + entry.getValue()); 
  if(StringUtils.isBlank(entry.getValue())) {
  throw new Exception("生成打印pdf时,解析传入参数时,发生异常,原因:参数"+entry.getKey()+"为空值或者null,请检查!!");
  }
}
if(count<8) {
throw new Exception("生成打印pdf时,解析传入参数时,发生异常,原因:缺少参数,请检查!!");
}
//解析传入的参数
String enterprise_name = paremMap.get("enterprise_name");
String certificate_number = paremMap.get("certificate_number");
String year = paremMap.get("year");
String month = paremMap.get("month");
String day = paremMap.get("day");
String first_time = paremMap.get("first_time");
String year_nd = paremMap.get("year_nd");
String continue_year = paremMap.get("continue_year");
// 设置整体调整参数
int yyy = 10 + 10 + 8;
int xxx = -30 + 11 + 6;
 
/*
  参数说明:以纸张的左下角为坐标原点,纸张左边框为 正Y轴,纸张底部为正X轴,
  把输出文字看作一个方块(具有 左-右-上-下边框)
  xxx参数代表文字的左边框到Y轴的像素
  yyy参数代表文字的下边框到X轴的像素
  */
 
// 企业名称
content_company_name = pdfStamper.getOverContent(i); 
content_company_name.saveState();
content_company_name.setGState(pdfGstate);
content_company_name.beginText();
content_company_name.setColorFill(BaseColor.BLACK);
content_company_name.setFontAndSize(basefont_kaiti, 23);
// content_company_name.setFontAndSize(FontKaitiJiaCu, 20); 
// size()        横坐标位置
// 20             x-270
// 23             x-280
content_company_name.showTextAligned(Element.ALIGN_CENTER, enterprise_name, 295 + xxx, 375 + yyy, 0);
content_company_name.endText();

// 证书编号前的文字
content_certificate_number_wenzi = pdfStamper.getOverContent(i);
content_certificate_number_wenzi.saveState();
content_certificate_number_wenzi.setGState(pdfGstate);
content_certificate_number_wenzi.beginText();
content_certificate_number_wenzi.setColorFill(BaseColor.BLACK); 
content_certificate_number_wenzi.setFontAndSize(basefont_kaiti, 14);
content_certificate_number_wenzi.showTextAligned(Element.ALIGN_CENTER, "证书编号:", 300 + xxx, 420 + yyy, 0);
content_certificate_number_wenzi.endText();

// 证书编号
content_certificate_number = pdfStamper.getOverContent(i); 
content_certificate_number.saveState();
content_certificate_number.setGState(pdfGstate);
content_certificate_number.beginText();
content_certificate_number.setColorFill(BaseColor.BLACK);
content_certificate_number.setFontAndSize(basefont_kaiti, 14);
content_certificate_number.showTextAligned(Element.ALIGN_CENTER, certificate_number, 380 + xxx, 418 + yyy, 0);
content_certificate_number.endText();

// 整体上移年月日
int date_y = 4;
// 日期-年
content_year = pdfStamper.getOverContent(i);
content_year.saveState();
content_year.setGState(pdfGstate);
content_year.beginText();
content_year.setColorFill(BaseColor.BLACK);
content_year.setFontAndSize(basefont_kaiti, 14); 
content_year.showTextAligned(Element.ALIGN_CENTER, year, 215 + xxx, 112 + yyy + date_y, 0);
content_year.endText();

// 日期-月
content_month = pdfStamper.getOverContent(i);
content_month.saveState();
content_month.setGState(pdfGstate);
content_month.beginText();
content_month.setColorFill(BaseColor.BLACK);
content_month.setFontAndSize(basefont_kaiti, 14); 
content_month.showTextAligned(Element.ALIGN_CENTER, month, 280 + xxx, 112 + yyy  + date_y, 0);
content_month.endText();

// 日期-天
content_day = pdfStamper.getOverContent(i);
content_day.saveState();
content_day.setGState(pdfGstate);
content_day.beginText();
content_day.setColorFill(BaseColor.BLACK);
content_day.setFontAndSize(basefont_kaiti, 14); 
content_day.showTextAligned(Element.ALIGN_CENTER, day, 335 + xxx, 112 + yyy  + date_y, 0);
content_day.endText();

// 首次公示年度
content_first_time = pdfStamper.getOverContent(i);
content_first_time.saveState();
content_first_time.setGState(pdfGstate);
content_first_time.beginText();
content_first_time.setColorFill(BaseColor.BLACK);
content_first_time.setFontAndSize(basefont_kaiti, 16); 
content_first_time.showTextAligned(Element.ALIGN_CENTER, first_time, 220+6 + xxx, 72-8 + yyy , 0);
content_first_time.endText();

// 公示年度
content_yeardu = pdfStamper.getOverContent(i);
content_yeardu.saveState();
content_yeardu.setGState(pdfGstate);
content_yeardu.beginText(); 
content_yeardu.setColorFill(BaseColor.BLACK);
content_yeardu.setFontAndSize(basefont_kaiti, 16);
content_yeardu.showTextAligned(Element.ALIGN_CENTER, year_nd, 510 + xxx, 418-8 + yyy, 0);
content_yeardu.endText();

// 连续年数
content_continue_year = pdfStamper.getOverContent(i);
content_continue_year.saveState();
content_continue_year.setGState(pdfGstate); 
content_continue_year.beginText(); 
content_continue_year.setColorFill(BaseColor.BLACK);
content_continue_year.setFontAndSize(basefont_kaiti, 18); 
content_continue_year.showTextAligned(Element.ALIGN_CENTER, "连续"+ continue_year +"年", 650 + xxx, 418-8 + yyy, 0);
content_continue_year.endText();
}
} catch (Exception ex) {
ex.printStackTrace();
throw new Exception("生成打印pdf时,添加文字异常,请检查!!",ex);
} finally {
content_company_name = null;
content_certificate_number = null;
content_day = null;
content_year = null;
content_first_time = null;
content_certificate_number_wenzi = null;
content_continue_year = null;
content_yeardu = null;
basefont_kaiti = null;
pdfStamper.close();
pdfReader.close();
fileoutputStream.close();
}
}


/**
* 在pdf上添加文字
* @param path
* @param inputPath
* @param outputPath
* @param paramMapList
* @throws Exception
*/
private static void addWatermark2_5(String path,String inputPath,String outputPath, List<Map<String, String>> paramMapList,String modeltype) throws Exception {
PdfReader pdfReader = new PdfReader(inputPath);
FileOutputStream fileoutputStream = new FileOutputStream(outputPath);
PdfStamper pdfStamper = new PdfStamper(pdfReader,fileoutputStream);
PdfContentByte content_yeardu = null;
PdfContentByte content_continue_year = null;
BaseFont basefont_kaiti = null;
BaseFont basefont_songti = null;
PdfGState pdfGstate = new PdfGState();
basefont_kaiti = BaseFont.createFont(path+"font/kaiti.TTF", BaseFont.IDENTITY_H,BaseFont.NOT_EMBEDDED);
basefont_songti = BaseFont.createFont(path+"font/songti.TTF", BaseFont.IDENTITY_H,BaseFont.NOT_EMBEDDED);
try {
if (basefont_songti == null || basefont_kaiti == null) {
throw new Exception("生成打印pdf时,字体加载异常!!");
}
// 设置透明度为1.0   不透明
pdfGstate.setFillOpacity(1.0f);
int toPage = pdfStamper.getReader().getNumberOfPages();
for (int i = 1; i <= toPage; i++) {
Map<String, String> paremMap = paramMapList.get(i-1);
if(StringUtils.isBlank(paremMap.get("year_nd"))) {
throw new Exception("生成打印pdf时,解析传入参数时,发生异常,原因:参数year_nd为空值或者null,请检查!!");
}
if(StringUtils.isBlank(paremMap.get("continue_year"))) {
throw new Exception("生成打印pdf时,解析传入参数时,发生异常,原因:参数continue_year为空值或者null,请检查!!");
}
//解析传入的参数
String year_nd = paremMap.get("year_nd");
String continue_year = paremMap.get("continue_year");

content_yeardu = pdfStamper.getOverContent(i);
content_yeardu.saveState();
content_yeardu.setGState(pdfGstate);
content_yeardu.beginText(); 
content_yeardu.setColorFill(BaseColor.BLACK);
content_yeardu.setFontAndSize(basefont_kaiti, 16);
  
//
// int yyy = 10 + 10 + 8;
// int xxx = -30 + 11 + 6;
//  
//  
 
int year_nd_x = 484 + 11 + 12 - 12;
int continue_year_x = 624 + 11 + 12 - 12;
int year_nd_y_And_continue_year_y = 0 + 10 + 17 + 17;// 整体上下移动 
if("2".equals(modeltype)) {
content_yeardu.showTextAligned(Element.ALIGN_CENTER, year_nd, year_nd_x, 355 + year_nd_y_And_continue_year_y, 0);
}else if("3".equals(modeltype)) {
content_yeardu.showTextAligned(Element.ALIGN_CENTER, year_nd, year_nd_x, 290 + year_nd_y_And_continue_year_y, 0);
}else if("4".equals(modeltype)) {
content_yeardu.showTextAligned(Element.ALIGN_CENTER, year_nd, year_nd_x, 225 + year_nd_y_And_continue_year_y, 0);
}else if("5".equals(modeltype)) {
content_yeardu.showTextAligned(Element.ALIGN_CENTER, year_nd, year_nd_x, 160 + year_nd_y_And_continue_year_y, 0);
}
content_yeardu.endText(); 

content_continue_year = pdfStamper.getOverContent(i);    
content_continue_year.saveState();
content_continue_year.setGState(pdfGstate);
content_continue_year.beginText(); 
content_continue_year.setColorFill(BaseColor.BLACK); 
content_continue_year.setFontAndSize(basefont_kaiti, 18);  
if("2".equals(modeltype)) {
content_continue_year.showTextAligned(Element.ALIGN_CENTER, "连续"+ continue_year +"年", continue_year_x, 355 + year_nd_y_And_continue_year_y, 0);
}else if("3".equals(modeltype)) {
content_continue_year.showTextAligned(Element.ALIGN_CENTER, "连续"+ continue_year +"年", continue_year_x, 290 + year_nd_y_And_continue_year_y, 0);
}else if("4".equals(modeltype)) {
content_continue_year.showTextAligned(Element.ALIGN_CENTER, "连续"+ continue_year +"年", continue_year_x, 225 + year_nd_y_And_continue_year_y, 0);
}else if("5".equals(modeltype)) {
content_continue_year.showTextAligned(Element.ALIGN_CENTER, "连续"+ continue_year +"年", continue_year_x, 160 + year_nd_y_And_continue_year_y, 0);
}
content_continue_year.endText();



}
} catch (Exception ex) {
ex.printStackTrace();
throw new Exception("生成打印pdf时,添加文字异常,请检查!!",ex);
} finally {
content_yeardu = null;
content_continue_year = null;
basefont_kaiti = null;
pdfStamper.close();
pdfReader.close();
fileoutputStream.close();
}
}

/**
* 生成单个pdf文件

* @param path
* @param parMap
* @param moType
* @return
* @throws Exception
*/
public String createSinglePdf(String path, Map<String, Object> parMap, String modeltype) throws Exception {
String pathStr = "";
FileOutputStream outfile = null;
Document document = null;
PdfWriter mPdfWriter = null;
try {
// path = "C://aa/";
BaseFont bfChinese = BaseFont.createFont("STSongStd-Light", "UniGB-UCS2-H", false);
Font font = new Font(bfChinese, 12, Font.NORMAL); // 设置字体大小
// new Document(pageSize, marginLeft, marginRight, marginTop, marginBottom)
document = new Document(PageSize.A4.rotate(), 60, 60, 60, 50);
String filename = String.valueOf(new Date().getTime());
pathStr = path + filename + ".pdf";
outfile = new FileOutputStream(pathStr);
mPdfWriter = PdfWriter.getInstance(document, outfile);
document.open();
 
// document.add(new Paragraph("创建pdf文件.支持中文......", font));
document.add(new Paragraph("", font));
String htmlStr = "";
if ("1".equals(modeltype)) {
htmlStr = getHtml1(parMap);
// htmlStr = getHtml22222();
} else if ("2".equals(modeltype)) {
htmlStr = getHtml2(parMap);
} else if ("3".equals(modeltype)) {
htmlStr = getHtml3(parMap);
} else if ("4".equals(modeltype)) {
htmlStr = getHtml4(parMap);
} else if ("5".equals(modeltype)) {
htmlStr = getHtml5(parMap);
}
ByteArrayInputStream bin = new ByteArrayInputStream(htmlStr.getBytes("UTF-8"));
XMLWorkerHelper.getInstance().parseXHtml(mPdfWriter, document, bin, Charset.forName("UTF-8"), new ChinaFontProvide());
} catch (Exception e) {
e.printStackTrace();
throw new Exception("Single--生成pdf异常", e);
} finally {
document.close();
mPdfWriter.close();
try {
outfile.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return pathStr;
}



//读取请求传递过来的JSON格式数据,返回JSON字符串
public static  String readJSONData(HttpServletRequest request) {
        StringBuffer json=new StringBuffer();
        String lineString=null;
        try {
            BufferedReader reader=request.getReader();
            while ((lineString=reader.readLine())!=null) {
                json.append(lineString);                
            }
        } catch (Exception e) {
            System.out.println(e.toString());
        }
        return json.toString();
    }



}


猜你喜欢

转载自blog.csdn.net/qq_29062045/article/details/80893314
今日推荐