导航:首页 > 文档加密 > java上传pdf

java上传pdf

发布时间:2024-01-06 05:33:24

‘壹’ 如何把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("&nbsp;", ""); //返回文本字符串

}

/**

* @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;

}

阅读全文

与java上传pdf相关的资料

热点内容
单纯形法包括动态规划算法 浏览:949
cpdf百度网盘 浏览:669
综合布线工程中配线架的算法 浏览:923
单片机硕士论文 浏览:327
股票预测算法现状 浏览:428
程序员三高 浏览:178
pythonfiddle 浏览:215
韩信分油总共有几种算法 浏览:941
程序员思维方案 浏览:970
编译环境要装c盘吗 浏览:648
单片机生成pwm 浏览:206
线上租车有什么app 浏览:908
php程序修改 浏览:684
下列能查找文件或文件夹的操作是 浏览:314
遥感科学与技术算法待遇 浏览:136
cad标注半径命令 浏览:367
打卡领购app邀请码怎么填 浏览:336
编程访问权限冲突 浏览:152
桌面运维如何转服务器运维 浏览:627
tomcat如何设置服务器 浏览:679