『壹』 如何把springmvc model 生成pdf文件
本文先敘述,如何操作PDF模板生成PDF文件,再說明在SpringMVC中如何根據PDF模板生成PDF文件。
使用PDF模板生成PDF文件需要以下幾個步驟:
下面按步驟說明:
1. 使用Microsoft Office Word畫好模板
此步驟就不詳述了,就是一個普通的Word文件(template.docx)。給個示例截圖:
2. 使用Adobe Acrobat X Pro將Word文件轉換為帶表單欄位的PDF模板文件
1) 打開Adobe Acrobat X Pro
2) 選擇「創建PDF表單」
3) 選擇源:(PDF、Word、Excel或其它文件類型),下一步
4) 定位Word文件路徑,下一步
5) Adobe Acrobat X Pro會自動猜測表單欄位位置,如圖
6) 一般生成的表單欄位都不符合我們的要求,選中刪除即可。
7) 點擊右鍵選擇文本框,拖動到適當的位置,設置好域名稱,字型大小,字體等。
8) 保存模板文件。(template.pdf)
3. 使用itext操作PDF模板,填充數據,生成PDF文件
1) 需要jar包:itext.jar、itextAsian.jar
2) 核心代碼:
package personal.hutao.test;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;
import org.junit.Test;
import com.lowagie.text.DocumentException;
import com.lowagie.text.pdf.AcroFields;
import com.lowagie.text.pdf.PdfReader;
import com.lowagie.text.pdf.PdfStamper;
public class TestPdf {
@Test
public void test() throws IOException, DocumentException {
String fileName = "D:/template.pdf"; // pdf模板
PdfReader reader = new PdfReader(fileName);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
PdfStamper ps = new PdfStamper(reader, bos);
AcroFields fields = ps.getAcroFields();
fillData(fields, data());
ps.setFormFlattening(true);
ps.close();
OutputStream fos = new FileOutputStream("D:/contract.pdf");
fos.write(bos.toByteArray());
}
public void fillData(AcroFields fields, Map<String, String> data) throws IOException, DocumentException {
for (String key : data.keySet()) {
String value = data.get(key);
fields.setField(key, value);
}
}
public Map<String, String> data() {
Map<String, String> data = new HashMap<String, String>();
data.put("borrower", "胡桃同學");
return data;
}
}
3) 打開contract.pdf,如圖
至此,就實現了根據PDF模板生成PDF文件。
SpringMVC的視圖中已提供了對PDF模板文件的支持:org.springframework.web.servlet.view.document.AbstractPdfStamperView。那麼只需要配置好此視圖就可以了。具體分為以下步驟:
1) 實現抽象類 AbstractPdfStamperView
package personal.hutao.view;
import java.io.IOException;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.view.document.AbstractPdfStamperView;
import com.lowagie.text.DocumentException;
import com.lowagie.text.pdf.AcroFields;
import com.lowagie.text.pdf.PdfStamper;
public class PdfStamperView extends AbstractPdfStamperView {
public static final String DATA = "data";
public static final String FILENAME = "mergePdfFileName";
@SuppressWarnings("unchecked")
@Override
protected void mergePdfDocument(Map<String, Object> model,
PdfStamper stamper, HttpServletRequest request,
HttpServletResponse response) throws Exception {
response.setHeader("Content-Disposition", "attachment;filename=" + new String(model.get(FILENAME).toString().getBytes(), "ISO8859-1"));
AcroFields fields = stamper.getAcroFields();
fillData(fields, (Map<String, String>) model.get(DATA));
stamper.setFormFlattening(true);
}
private void fillData(AcroFields fields, Map<String, String> data)
throws IOException, DocumentException {
for (String key : data.keySet()) {
String value = data.get(key);
fields.setField(key, value);
}
}
}
2) 在SpringMVC的配置文件中配置視圖
<!-- 按照BeanName解析視圖 -->
<bean class="org.springframework.web.servlet.view.BeanNameViewResolver">
<property name="order" value="1" />
</bean>
<!-- 定義Pdf模版視圖 -->
<bean id="contract" class="personal.hutao.view.PdfStamperView">
<property name="url" value="/WEB-INF/template/template.pdf" />
</bean>
3) Controller中的業務邏輯處理
package personal.hutao.controller;
import static personal.hutao.view.PdfStamperView.DATA;
import static personal.hutao.view.PdfStamperView.FILENAME;
import java.util.HashMap;
import java.util.Map;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import com.coamctech.sample.commons.controller.BaseController;
@RequestMapping("/contract")
@Controller
public class TestController {
@RequestMapping("/export/pdf")
public String (Model model) {
model.addAttribute(DATA, data());
model.addAttribute(FILENAME, "XXX貸款合同");
return "contract";
}
private Map<String, String> data() {
Map<String, String> data = new HashMap<String, String>();
data.put("borrower", "胡桃同學");
return data;
}
}
『貳』 java讀取doc,pdf問題。
PDFBox是一個開源的對pdf文件進行操作的庫。 PDFBox-0.7.3.jar加入classpath。同時FontBox1.0.jar加入classpath,否則報錯
importjava.io.FileInputStream;
importjava.io.FileNotFoundException;
importjava.io.IOException;
importorg.pdfbox.pdfparser.PDFParser;
importorg.pdfbox.pdmodel.PDDocument;
importorg.pdfbox.util.PDFTextStripper;
publicclassPdfReader{
/**
*.
*.
*2008-2-25
*@parampdfFilePathfilepath
*@returnalltextinthepdffile
*/
(StringpdfFilePath)
{
Stringresult=null;
FileInputStreamis=null;
PDDocumentdocument=null;
try{
is=newFileInputStream(pdfFilePath);
PDFParserparser=newPDFParser(is);
parser.parse();
document=parser.getPDDocument();
PDFTextStripperstripper=newPDFTextStripper();
result=stripper.getText(document);
}catch(FileNotFoundExceptione){
//TODOAuto-generatedcatchblock
e.printStackTrace();
}catch(IOExceptione){
//TODOAuto-generatedcatchblock
e.printStackTrace();
}finally{
if(is!=null){
try{
is.close();
}catch(IOExceptione){
//TODOAuto-generatedcatchblock
e.printStackTrace();
}
}
if(document!=null){
try{
document.close();
}catch(IOExceptione){
//TODOAuto-generatedcatchblock
e.printStackTrace();
}
}
}
returnresult;
}
publicstaticvoidmain(String[]args)
{
Stringstr=PdfReader.getTextFromPDF("C:\Read.pdf");
System.out.println(str);
}
}
代碼2:
importjava.io.File;
importjava.io.FileOutputStream;
importjava.io.OutputStreamWriter;
importjava.io.Writer;
importjava.net.MalformedURLException;
importjava.net.URL;
importorg.pdfbox.pdmodel.PDDocument;
importorg.pdfbox.util.PDFTextStripper;
publicclassPDFReader{
publicvoidreadFdf(Stringfile)throwsException{
booleansort=false;
StringpdfFile=file;
StringtextFile=null;
Stringencoding="UTF-8";
intstartPage=1;
intendPage=Integer.MAX_VALUE;
Writeroutput=null;
PDDocumentdocument=null;
try{
try{
//首先當作一個URL來裝載文件,如果得到異常再從本地文件系統//去裝載文件
URLurl=newURL(pdfFile);
//注意參數已不是以前版本中的URL.而是File。
document=PDDocument.load(pdfFile);
//獲取PDF的文件名
StringfileName=url.getFile();
//以原來PDF的名稱來命名新產生的txt文件
if(fileName.length()>4){
FileoutputFile=newFile(fileName.substring(0,fileName
.length()-4)
+".txt");
textFile=outputFile.getName();
}
}catch(MalformedURLExceptione){
//如果作為URL裝載得到異常則從文件系統裝載
//注意參數已不是以前版本中的URL.而是File。
document=PDDocument.load(pdfFile);
if(pdfFile.length()>4){
textFile=pdfFile.substring(0,pdfFile.length()-4)
+".txt";
}
}
output=newOutputStreamWriter(newFileOutputStream(textFile),
encoding);
PDFTextStripperstripper=null;
stripper=newPDFTextStripper();
//設置是否排序
stripper.setSortByPosition(sort);
//設置起始頁
stripper.setStartPage(startPage);
//設置結束頁
stripper.setEndPage(endPage);
//調用PDFTextStripper的writeText提取並輸出文本
stripper.writeText(document,output);
}finally{
if(output!=null){
//關閉輸出流
output.close();
}
if(document!=null){
//關閉PDFDocument
document.close();
}
}
}
/**
*@paramargs
*/
publicstaticvoidmain(String[]args){
//TODOAuto-generatedmethodstub
PDFReaderpdfReader=newPDFReader();
try{
//取得E盤下的SpringGuide.pdf的內容
pdfReader.readFdf("C:\Read.pdf");
}catch(Exceptione){
e.printStackTrace();
}
}
}
2、抽取支持中文的pdf文件-xpdf
xpdf是一個開源項目,我們可以調用他的本地方法來實現抽取中文pdf文件。
http://www.java-cn.com/technology/tech_downs/1880_004.zip
補丁包:
http://www.java-cn.com/technology/tech_downs/1880_005.zip
按照readme放好中文的patch,就可以開始寫調用本地方法的java程序了。
下面是一個如何調用的例子:
importjava.io.*;
/**
*<p>Title:pdfextraction</p>
*<p>Description:email:[email protected]</p>
*<p>Copyright:MatrixCopyright(c)2003</p>
*<p>Company:Matrix.org.cn</p>
*@authorchris
*@version1.0,
*/
publicclassPdfWin{
publicPdfWin(){
}
publicstaticvoidmain(Stringargs[])throwsException
{
StringPATH_TO_XPDF="C:ProgramFilesxpdfpdftotext.exe";
Stringfilename="c:a.pdf";
String[]cmd=newString[]{PATH_TO_XPDF,"-enc","UTF-8","-q",filename,"-"};
Processp=Runtime.getRuntime().exec(cmd);
BufferedInputStreambis=newBufferedInputStream(p.getInputStream());
InputStreamReaderreader=newInputStreamReader(bis,"UTF-8");
StringWriterout=newStringWriter();
char[]buf=newchar[10000];
intlen;
while((len=reader.read(buf))>=0){
//out.write(buf,0,len);
System.out.println("thelengthis"+len);
}
reader.close();
Stringts=newString(buf);
System.out.println("thestris"+ts);
}
}
『叄』 有關Java導出pdf的功能
轉pdf時,有2種解決方法
1 itext ,這個我就不說了 ,代碼很多,我想你也實踐過。
2 通過openoffice轉換為pdf 。這個比較繁瑣,要安裝一系列的組件,網路上也有類似的文章,前段時間我開發仿網路文庫的功能,就是將普通的辦公文檔在網頁顯示,辦公文檔-openoffice(pdf)-swftools(swf)-flexpaper,就是這樣的流程,如果需要,我將所用到的組件發你,代碼就不能給你了(嘿嘿)。操作excel 或word 還是比較容易的,將生成好的excel或word轉換為pdf非常容易,基本上是原樣輸出
『肆』 java中怎麼利用poi和itext生成pdf文檔
生成PDF文檔代碼如下:
packagepoi.itext;
importjava.io.FileOutputStream;
importjava.io.IOException;
importjava.awt.Color;
importcom.lowagie.text.*;
importcom.lowagie.text.pdf.*;
importcom.lowagie.text.pdf.BaseFont;
/**
*創建Pdf文檔
*@authorAdministrator
*
*/
publicclassHelloPdf
{
publicstaticvoidmain(String[]args)throwsException
{
BaseFontbfChinese=BaseFont.createFont("STSong-Light","UniGB-UCS2-H",BaseFont.NOT_EMBEDDED);
FontFontChinese=newFont(bfChinese,12,Font.NORMAL);
//第一步,創建document對象
RectanglerectPageSize=newRectangle(PageSize.A4);
//下面代碼設置頁面橫置
//rectPageSize=rectPageSize.rotate();
//創建document對象並指定邊距
Documentdoc=newDocument(rectPageSize,50,50,50,50);
Documentdocument=newDocument();
try
{
//第二步,將Document實例和文件輸出流用PdfWriter類綁定在一起
//從而完成向Document寫,即寫入PDF文檔
PdfWriter.getInstance(document,newFileOutputStream("src/poi/itext/HelloWorld.pdf"));
//第3步,打開文檔
document.open();
//第3步,向文檔添加文字.文檔由段組成
document.add(newParagraph("HelloWorld"));
Paragraphpar=newParagraph("世界你好",FontChinese);
document.add(par);
PdfPTabletable=newPdfPTable(3);
for(inti=0;i<12;i++)
{
if(i==0)
{
PdfPCellcell=newPdfPCell();
cell.setColspan(3);
cell.setBackgroundColor(newColor(180,180,180));
cell.addElement(newParagraph("表格頭",FontChinese));
table.addCell(cell);
}
else
{
PdfPCellcell=newPdfPCell();
cell.addElement(newParagraph("表格內容",FontChinese));
table.addCell(cell);
}
}
document.add(table);
}
catch(DocumentExceptionde)
{
System.err.println(de.getMessage());
}
catch(IOExceptionioe)
{
System.err.println(ioe.getMessage());
}
//關閉document
document.close();
System.out.println("生成HelloPdf成功!");
}
}
希望對你有幫助。
『伍』 java中怎麼利用struts2上傳多個pdf文件
通過3種方式模擬多個文件上傳
第一種方式
package com.ljq.action;
import java.io.File;
import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
@SuppressWarnings("serial")
public class UploadAction extends ActionSupport{
private File[] image; //上傳的文件
private String[] imageFileName; //文件名稱
private String[] imageContentType; //文件類型
public String execute() throws Exception {
ServletActionContext.getRequest().setCharacterEncoding("UTF-8");
String realpath = ServletActionContext.getServletContext().getRealPath("/images");
System.out.println(realpath);
if (image != null) {
File savedir=new File(realpath);
if(!savedir.getParentFile().exists())
savedir.getParentFile().mkdirs();
for(int i=0;i<image.length;i++){
File savefile = new File(savedir, imageFileName[i]);
FileUtils.File(image[i], savefile);
}
ActionContext.getContext().put("message", "文件上傳成功");
}
return "success";
}
public File[] getImage() {
return image;
}
public void setImage(File[] image) {
this.image = image;
}
public String[] getImageContentType() {
return imageContentType;
}
public void setImageContentType(String[] imageContentType) {
this.imageContentType = imageContentType;
}
public String[] getImageFileName() {
return imageFileName;
}
public void setImageFileName(String[] imageFileName) {
this.imageFileName = imageFileName;
}
}
第二種方式
package com.ljq.action;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
/**
* 使用數組上傳多個文件
*
* @author ljq
*
*/
@SuppressWarnings("serial")
public class UploadAction2 extends ActionSupport{
private File[] image; //上傳的文件
private String[] imageFileName; //文件名稱
private String[] imageContentType; //文件類型
private String savePath;
@Override
public String execute() throws Exception {
ServletActionContext.getRequest().setCharacterEncoding("UTF-8");
//取得需要上傳的文件數組
File[] files = getImage();
if (files !=null && files.length > 0) {
for (int i = 0; i < files.length; i++) {
//建立上傳文件的輸出流, getImageFileName()[i]
System.out.println(getSavePath() + "\\" + getImageFileName()[i]);
FileOutputStream fos = new FileOutputStream(getSavePath() + "\\" + getImageFileName()[i]);
//建立上傳文件的輸入流
FileInputStream fis = new FileInputStream(files[i]);
byte[] buffer = new byte[1024];
int len = 0;
while ((len=fis.read(buffer))>0) {
fos.write(buffer, 0, len);
}
fos.close();
fis.close();
}
}
return SUCCESS;
}
public File[] getImage() {
return image;
}
public void setImage(File[] image) {
this.image = image;
}
public String[] getImageFileName() {
return imageFileName;
}
public void setImageFileName(String[] imageFileName) {
this.imageFileName = imageFileName;
}
public String[] getImageContentType() {
return imageContentType;
}
public void setImageContentType(String[] imageContentType) {
this.imageContentType = imageContentType;
}
/**
* 返回上傳文件保存的位置
*
* @return
* @throws Exception
*/
public String getSavePath() throws Exception {
return ServletActionContext.getServletContext().getRealPath(savePath);
}
public void setSavePath(String savePath) {
this.savePath = savePath;
}
}
第三種方式
package com.ljq.action;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.List;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
/**
* 使用List上傳多個文件
*
* @author ljq
*
*/
@SuppressWarnings("serial")
public class UploadAction3 extends ActionSupport {
private List<File> image; // 上傳的文件
private List<String> imageFileName; // 文件名稱
private List<String> imageContentType; // 文件類型
private String savePath;
@Override
public String execute() throws Exception {
ServletActionContext.getRequest().setCharacterEncoding("UTF-8");
// 取得需要上傳的文件數組
List<File> files = getImage();
if (files != null && files.size() > 0) {
for (int i = 0; i < files.size(); i++) {
FileOutputStream fos = new FileOutputStream(getSavePath() + "\\" + getImageFileName().get(i));
FileInputStream fis = new FileInputStream(files.get(i));
byte[] buffer = new byte[1024];
int len = 0;
while ((len = fis.read(buffer)) > 0) {
fos.write(buffer, 0, len);
}
fis.close();
fos.close();
}
}
return SUCCESS;
}
public List<File> getImage() {
return image;
}
public void setImage(List<File> image) {
this.image = image;
}
public List<String> getImageFileName() {
return imageFileName;
}
public void setImageFileName(List<String> imageFileName) {
this.imageFileName = imageFileName;
}
public List<String> getImageContentType() {
return imageContentType;
}
public void setImageContentType(List<String> imageContentType) {
this.imageContentType = imageContentType;
}
/**
* 返回上傳文件保存的位置
*
* @return
* @throws Exception
*/
public String getSavePath() throws Exception {
return ServletActionContext.getServletContext().getRealPath(savePath);
}
public void setSavePath(String savePath) {
this.savePath = savePath;
}
}
struts.xml配置文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<!-- 該屬性指定需要Struts2處理的請求後綴,該屬性的默認值是action,即所有匹配*.action的請求都由Struts2處理。
如果用戶需要指定多個請求後綴,則多個後綴之間以英文逗號(,)隔開。 -->
<constant name="struts.action.extension" value="do" />
<!-- 設置瀏覽器是否緩存靜態內容,默認值為true(生產環境下使用),開發階段最好關閉 -->
<constant name="struts.serve.static.browserCache" value="false" />
<!-- 當struts的配置文件修改後,系統是否自動重新載入該文件,默認值為false(生產環境下使用),開發階段最好打開 -->
<constant name="struts.configuration.xml.reload" value="true" />
<!-- 開發模式下使用,這樣可以列印出更詳細的錯誤信息 -->
<constant name="struts.devMode" value="true" />
<!-- 默認的視圖主題 -->
<constant name="struts.ui.theme" value="simple" />
<!--<constant name="struts.objectFactory" value="spring" />-->
<!--解決亂碼 -->
<constant name="struts.i18n.encoding" value="UTF-8" />
<constant name="struts.multipart.maxSize" value="10701096"/>
<package name="upload" namespace="/upload" extends="struts-default">
<action name="*_upload" class="com.ljq.action.UploadAction" method="{1}">
<result name="success">/WEB-INF/page/message.jsp</result>
</action>
</package>
<package name="upload1" namespace="/upload1" extends="struts-default">
<action name="upload1" class="com.ljq.action.UploadAction2" method="execute">
<!-- 要創建/image文件夾,否則會報找不到文件 -->
<param name="savePath">/image</param>
<result name="success">/WEB-INF/page/message.jsp</result>
</action>
</package>
<package name="upload2" namespace="/upload2" extends="struts-default">
<action name="upload2" class="com.ljq.action.UploadAction3" method="execute">
<!-- 要創建/image文件夾,否則會報找不到文件 -->
<param name="savePath">/image</param>
<result name="success">/WEB-INF/page/message.jsp</result>
</action>
</package>
</struts>
上傳表單頁面upload.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>文件上傳</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
</head>
<body>
<!-- ${pageContext.request.contextPath}/upload/execute_upload.do -->
<!-- ${pageContext.request.contextPath}/upload1/upload1.do -->
<!-- ${pageContext.request.contextPath}/upload2/upload2.do -->
<!-- -->
<form action="${pageContext.request.contextPath}/upload2/upload2.do" enctype="multipart/form-data" method="post">
文件1:<input type="file" name="image"><br/>
文件2:<input type="file" name="image"><br/>
文件3:<input type="file" name="image"><br/>
<input type="submit" value="上傳" />
</form>
</body>
</html>
顯示頁面message.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="/struts-tags" prefix="s"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>My JSP 'message.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
</head>
<body>
上傳成功
<br/>
<s:debug></s:debug>
</body>
</html>
『陸』 我在java中用jacob把word文檔轉化成pdf文件出來了問題
1、到官網下載Jacob,2、將壓縮包解壓後,Jacob.jar添加到Libraries中(先復制到項目目錄中,右鍵單擊jar包選擇BuildPath—>AddtoBuildPath);3、將Jacob.dll放至當前項目所用到的「jre\bin」下面(比如Eclipse正在用的Jre路徑是C:\Java\jdk1.7
『柒』 java中 怎麼實現word、pdf、jpg等一些文件格式的上傳下載 並且還要支持預覽功能 最好有代碼 留qq也可以
jsp的話需要用smartup等上傳插件 另外servlet3.0自帶上傳功能
『捌』 如何運用Java組件itext生成pdf
Controller層(param為數據)
byte[]bytes=PdfUtils.createPdf(param);
ByteArrayInputStreaminStream=newByteArrayInputStream(bytes);
//設置輸出的格式
response.setContentType("bin");
response.setHeader("content-disposition","attachment;filename="+URLEncoder.encode(itemName+"(評審意見).pdf","UTF-8"));
//循環取出流中的數據
byte[]b=newbyte[2048];
intlen;
while((len=inStream.read(b))>0)
response.getOutputStream().write(b,0,len);
inStream.close();
Service層(param為數據)
public static byte[] createPdf(Map<String,Object> param) {
byte[] result= null;
ByteArrayOutputStream baos = null;
//支流程評審信息匯總
List<CmplncBranchRvwInfoDTO> branchRvwInfos = (List<CmplncBranchRvwInfoDTO>) param.get("branchRvwInfos");
//主流程評審信息匯總
List<CmplncMainRvwInfoDTO> mainRvwInfos = (List<CmplncMainRvwInfoDTO>) param.get("mainRvwInfos");
//主評審信息
CmplncRvwFormDTO rvwFormDTO = (CmplncRvwFormDTO) param.get("rvwFormDTO");
//附件列表
List<FileInfoDTO> fileList = (List<FileInfoDTO>) param.get("fileList");
//專業公司
String legalEntityDeptDesc = (String) param.get("legalEntityDeptDesc");
String legalEntitySonDeptDesc = (String) param.get("legalEntitySonDeptDesc");
//設置頁邊距
Document doc = new Document(PageSize.A4, 20, 20, 60, 20);
try {
baos = new ByteArrayOutputStream();//構建位元組輸出流
PdfWriter writer = PdfWriter.getInstance(doc,baos);
//頁眉頁腳字體
BaseFont bf = null;
BaseFont bFont = null;
try {
bFont = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.EMBEDDED);
bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H",BaseFont.NOT_EMBEDDED);
} catch (Exception e) {
e.printStackTrace();
}
Font footerFont = new Font(bFont, 10, Font.NORMAL);
Font title = new Font(bf,15,Font.BOLD);
Font content = new Font(bf,9,Font.NORMAL);
Font chinese = new Font(bf, 10, Font.BOLD);
/**
* HeaderFooter的第2個參數為非false時代表列印頁碼
* 頁眉頁腳中也可以加入圖片,並非只能是文字
*/
HeaderFooter header=new HeaderFooter(new Phrase("法律合規評審系統",title),false);
//設置是否有邊框等
header.setBorder(Rectangle.NO_BORDER);
header.setAlignment(1);
doc.setHeader(header);
HeaderFooter footer=new HeaderFooter(new Phrase("-",footerFont),new Phrase("-",footerFont));
/**
* 0左 1中 2右
*/
footer.setAlignment(1);
footer.setBorder(Rectangle.NO_BORDER);
doc.setFooter(footer);
doc.open();
//doc.add(new Paragraph("評審意見:",chinese));
//7列
PdfPTable table = new PdfPTable(7);
PdfPCell cell;
table.addCell(new Paragraph("評審項目編號",chinese));
table.addCell(new Paragraph(rvwFormDTO.getRvwItemCode(),content));
cell = new PdfPCell(new Paragraph("評審項目類型",chinese));
cell.setColspan(2);
table.addCell(cell);
String rvwItemParentType = (String) param.get("rvwItemParentType");
String rvwItemType = (String) param.get("rvwItemType");
String rvwItemTwoType = (String) param.get("rvwItemTwoType");
cell = new PdfPCell(new Paragraph(rvwItemParentType+"/"+rvwItemType+"/"+rvwItemTwoType,content));
cell.setColspan(3);
table.addCell(cell);
table.addCell(new Paragraph("申請人姓名",chinese));
table.addCell(new Paragraph(rvwFormDTO.getApplicantName(),content));
cell = new PdfPCell(new Paragraph("申請人所在部門",chinese));
cell.setColspan(2);
table.addCell(cell);
cell = new PdfPCell(new Paragraph(rvwFormDTO.getAplcntDeptName(),content));
cell.setColspan(3);
table.addCell(cell);
table.addCell(new Paragraph("錄入人姓名",chinese));
table.addCell(new Paragraph(rvwFormDTO.getRecordName(),content));
cell = new PdfPCell(new Paragraph("項目涉及金額",chinese));
cell.setColspan(2);
table.addCell(cell);
table.addCell(new Paragraph(String.valueOf(rvwFormDTO.getInvolveAmount()==null?0:rvwFormDTO.getInvolveAmount()),content));
table.addCell(new Paragraph("幣種",chinese));
String involveAmountType = (String) param.get("involveAmountType");
table.addCell(new Paragraph(involveAmountType,content));
table.addCell(new Paragraph("專業公司",chinese));
cell = new PdfPCell(new Paragraph(legalEntityDeptDesc+"->"+legalEntitySonDeptDesc,content));
cell.setColspan(6);
table.addCell(cell);
table.addCell(new Paragraph("項目名稱",chinese));
cell = new PdfPCell(new Paragraph(rvwFormDTO.getItemName(),content));
cell.setColspan(6);
table.addCell(cell);
table.addCell(new Paragraph("項目概述",chinese));
cell = new PdfPCell(new Paragraph(rvwFormDTO.getItemOverview(),content));
cell.setColspan(6);
table.addCell(cell);
table.addCell(new Paragraph("評審需求",chinese));
cell = new PdfPCell(new Paragraph(rvwFormDTO.getRvwDemand(),content));
cell.setColspan(6);
table.addCell(cell);
table.addCell(new Paragraph("申請人自我評估",chinese));
cell = new PdfPCell(new Paragraph(rvwFormDTO.getApplicantSelfAssmnt(),content));
cell.setColspan(6);
table.addCell(cell);
/* table.addCell(new Paragraph("同步抄送",chinese));
cell = new PdfPCell(new Paragraph(rvwFormDTO.getSyncsenderNames(),content));
cell.setColspan(6);
table.addCell(cell);*/
int infoNum = 0;
if(fileList.size() > 0){
//附件信息
cell = new PdfPCell(new Paragraph("附件信息",chinese));
cell.setUseAscender(true);
cell.setHorizontalAlignment(Element.ALIGN_CENTER); //水平居中
cell.setVerticalAlignment(Element.ALIGN_MIDDLE); //垂直居中
cell.setRowspan(fileList.size()+1);
table.addCell(cell);
//序號
cell = new PdfPCell(new Paragraph("序號",chinese));
cell.setUseAscender(true);
cell.setHorizontalAlignment(Element.ALIGN_CENTER); //水平居中
cell.setVerticalAlignment(Element.ALIGN_MIDDLE); //垂直居中
table.addCell(cell);
//附件名稱
cell = new PdfPCell(new Paragraph("附件名稱",chinese));
cell.setUseAscender(true);
cell.setHorizontalAlignment(Element.ALIGN_CENTER); //水平居中
cell.setVerticalAlignment(Element.ALIGN_MIDDLE); //垂直居中
table.addCell(cell);
//上傳時間
cell = new PdfPCell(new Paragraph("上傳時間",chinese));
cell.setUseAscender(true);
cell.setHorizontalAlignment(Element.ALIGN_CENTER); //水平居中
cell.setVerticalAlignment(Element.ALIGN_MIDDLE); //垂直居中
table.addCell(cell);
//上傳人
cell = new PdfPCell(new Paragraph("上傳人",chinese));
cell.setUseAscender(true);
cell.setHorizontalAlignment(Element.ALIGN_CENTER); //水平居中
cell.setVerticalAlignment(Element.ALIGN_MIDDLE); //垂直居中
table.addCell(cell);
//附件類型
cell = new PdfPCell(new Paragraph("附件類型",chinese));
cell.setUseAscender(true);
cell.setHorizontalAlignment(Element.ALIGN_CENTER); //水平居中
cell.setVerticalAlignment(Element.ALIGN_MIDDLE); //垂直居中
table.addCell(cell);
//法律合規評審
cell = new PdfPCell(new Paragraph("法律合規評審",chinese));
cell.setUseAscender(true);
cell.setHorizontalAlignment(Element.ALIGN_CENTER); //水平居中
cell.setVerticalAlignment(Element.ALIGN_MIDDLE); //垂直居中
table.addCell(cell);
for (FileInfoDTO file : fileList) {
infoNum++;
//序號
cell = new PdfPCell(new Paragraph(infoNum+"",content));
cell.setUseAscender(true);
cell.setHorizontalAlignment(Element.ALIGN_CENTER); //水平居中
cell.setVerticalAlignment(Element.ALIGN_MIDDLE); //垂直居中
table.addCell(cell);
//附件名稱
cell = new PdfPCell(new Paragraph(file.getFileName(),content));
cell.setUseAscender(true);
cell.setHorizontalAlignment(Element.ALIGN_CENTER); //水平居中
cell.setVerticalAlignment(Element.ALIGN_MIDDLE); //垂直居中
table.addCell(cell);
//上傳時間
cell = new PdfPCell(new Paragraph(file.getUploadTimeFormat(),content));
cell.setUseAscender(true);
cell.setHorizontalAlignment(Element.ALIGN_CENTER); //水平居中
cell.setVerticalAlignment(Element.ALIGN_MIDDLE); //垂直居中
table.addCell(cell);
//上傳人
cell = new PdfPCell(new Paragraph(file.getUploadName(),content));
cell.setUseAscender(true);
cell.setHorizontalAlignment(Element.ALIGN_CENTER); //水平居中
cell.setVerticalAlignment(Element.ALIGN_MIDDLE); //垂直居中
table.addCell(cell);
//附件類型
String fileType;
if("1".equals(file.getFileType())){
fileType = "合同文件";
}else if("99".equals(file.getFileType())){
fileType = "支持文檔";
}else{
fileType = "";
}
cell = new PdfPCell(new Paragraph(fileType,content));
cell.setUseAscender(true);
cell.setHorizontalAlignment(Element.ALIGN_CENTER); //水平居中
cell.setVerticalAlignment(Element.ALIGN_MIDDLE); //垂直居中
table.addCell(cell);
//法律合規評審
String typeRvwStatus;
if("1".equals(file.getTypeRvwStatus())){
typeRvwStatus = "經審查附件無重大法律合規問題";
}else if("2".equals(file.getTypeRvwStatus())){
typeRvwStatus = "退回修改";
}else{
typeRvwStatus = "";
}
cell = new PdfPCell(new Paragraph(typeRvwStatus,content));
cell.setUseAscender(true);
cell.setHorizontalAlignment(Element.ALIGN_CENTER); //水平居中
cell.setVerticalAlignment(Element.ALIGN_MIDDLE); //垂直居中
table.addCell(cell);
}
}else{
//附件信息
cell = new PdfPCell(new Paragraph("附件信息",chinese));
table.addCell(cell);
cell = new PdfPCell(new Paragraph("沒有附件",content));
cell.setColspan(6);
table.addCell(cell);
}
cell = new PdfPCell(new Paragraph("評審意見",chinese));
cell.setRowspan(mainRvwInfos.size()+branchRvwInfos.size());
//居中
cell.setUseAscender(true);
cell.setHorizontalAlignment(Element.ALIGN_CENTER); //水平居中
cell.setVerticalAlignment(Element.ALIGN_MIDDLE); //垂直居中
table.addCell(cell);
if(mainRvwInfos.size()>0){
cell = new PdfPCell(new Paragraph("主評審意見",chinese));
cell.setRowspan(mainRvwInfos.size());
//居中
cell.setUseAscender(true);
cell.setHorizontalAlignment(Element.ALIGN_CENTER); //水平居中
cell.setVerticalAlignment(Element.ALIGN_MIDDLE); //垂直居中
table.addCell(cell);
infoNum = 0;
for (CmplncMainRvwInfoDTO dto : mainRvwInfos) {
infoNum++;
//序號
cell = new PdfPCell(new Paragraph(infoNum+"",content));
cell.setUseAscender(true);
cell.setHorizontalAlignment(Element.ALIGN_CENTER); //水平居中
cell.setVerticalAlignment(Element.ALIGN_MIDDLE); //垂直居中
table.addCell(cell);
//評審意見
PdfPTable branchRvwInfosTable = new PdfPTable(1);
cell = new PdfPCell(new Paragraph(delHTMLTag(dto.getRvwOpinion()),content));
cell.disableBorderSide(2);
branchRvwInfosTable.addCell(cell);
//評審人和評審時間
cell = new PdfPCell(new Paragraph(dto.getRvwUmName()+"/"+getStringDate(dto.getRvwTime()),content));
cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
cell.disableBorderSide(1);
cell.setPaddingTop(5);
branchRvwInfosTable.addCell(cell);
PdfPCell branchRvwInfosCell = new PdfPCell(branchRvwInfosTable);
branchRvwInfosCell.setColspan(4);
table.addCell(branchRvwInfosCell);
}
doc.add(table);
}
if(branchRvwInfos.size()>0){
cell = new PdfPCell(new Paragraph("支評審意見",chinese));
cell.setRowspan(branchRvwInfos.size());
//居中
cell.setUseAscender(true);
cell.setHorizontalAlignment(Element.ALIGN_CENTER); //水平居中
cell.setVerticalAlignment(Element.ALIGN_MIDDLE); //垂直居中
table.addCell(cell);
infoNum = 0;
for (CmplncBranchRvwInfoDTO dto : branchRvwInfos) {
infoNum++;
//序號
cell = new PdfPCell(new Paragraph(infoNum+"",content));
cell.setUseAscender(true);
cell.setHorizontalAlignment(Element.ALIGN_CENTER); //水平居中
cell.setVerticalAlignment(Element.ALIGN_MIDDLE); //垂直居中
table.addCell(cell);
//評審意見
PdfPTable branchRvwInfosTable = new PdfPTable(1);
cell = new PdfPCell(new Paragraph(delHTMLTag(dto.getRvwOpinion()),content));
cell.disableBorderSide(2);
branchRvwInfosTable.addCell(cell);
//評審人和評審時間
cell = new PdfPCell(new Paragraph(dto.getRvwUmName()+"/"+getStringDate(dto.getRvwTime()),content));
cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
cell.disableBorderSide(1);//隱藏上邊框
cell.setPaddingTop(5);
branchRvwInfosTable.addCell(cell);
PdfPCell branchRvwInfosCell = new PdfPCell(branchRvwInfosTable);
branchRvwInfosCell.setColspan(4);
table.addCell(branchRvwInfosCell);
}
doc.add(table);
}
if(doc != null){
doc.close();
}
result =baos.toByteArray();
} catch (DocumentException e) {
e.printStackTrace();
}finally{
if(baos != null){
try {
baos.close();
} catch (IOException e) {
log.error("PDF異常", e);
}
}
}
return result;
}
工具
/**
* 去掉HTML標簽
* @param htmlStr
* @return
*/
public static String delHTMLTag(String htmlStr){
if (htmlStr!=null){
String regEx_script="<script[^>]*?>[\s\S]*?<\/script>"; //定義script的正則表達式
String regEx_style="<style[^>]*?>[\s\S]*?<\/style>"; //定義style的正則表達式
String regEx_html="<[^>]+>"; //定義HTML標簽的正則表達式
Pattern p_script=Pattern.compile(regEx_script,Pattern.CASE_INSENSITIVE);
Matcher m_script=p_script.matcher(htmlStr);
htmlStr=m_script.replaceAll(""); //過濾script標簽
Pattern p_style=Pattern.compile(regEx_style,Pattern.CASE_INSENSITIVE);
Matcher m_style=p_style.matcher(htmlStr);
htmlStr=m_style.replaceAll(""); //過濾style標簽
Pattern p_html=Pattern.compile(regEx_html,Pattern.CASE_INSENSITIVE);
Matcher m_html=p_html.matcher(htmlStr);
htmlStr=m_html.replaceAll(""); //過濾html標簽
Pattern p_enter = Pattern.compile("\s*| | | ");
Matcher m_enter = p_enter.matcher(htmlStr);
htmlStr = m_enter.replaceAll("");
}
return htmlStr.trim().replaceAll(" ", ""); //返迴文本字元串
}
/**
* @return返回字元串格式 yyyy-MM-dd HH:mm:ss
*/
public static String getStringDate(Date date) {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dateString = formatter.format(date);
return dateString;
}