如何运用Java组件itext生成pdf

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何运用Java组件itext生成pdf相关的知识,希望对你有一定的参考价值。

Controller层(param为数据)

byte[] bytes = PdfUtils.createPdf(param);
ByteArrayInputStream inStream = new ByteArrayInputStream(bytes);
// 设置输出的格式
response.setContentType("bin");
response.setHeader("content-disposition", "attachment;filename="+ URLEncoder.encode(itemName+"(评审意见).pdf", "UTF-8"));
// 循环取出流中的数据
byte[] b = new byte[2048];
int len;
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*|\\t|\\r|\\n");

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;  

 

参考技术A

引入需要的类,如下图:

这些都是生成pdf文嘉需要的,设置样式:

参考技术B

给你几句简单的实例,以下代码均在springmvc框架的action层写。

import com.itextpdf.text.*;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;

response.setContentType("application/pdf");
Document document = new Document(PageSize.A4);
PdfWriter.getInstance(document, response.getOutputStream());
document.addTitle("文档名称");  
document.open();
//字体
BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H",BaseFont.NOT_EMBEDDED);
Paragraph titleParagraph = new Paragraph("xx报告",new Font(bfChinese, 20, Font.BOLD));
titleParagraph.setAlignment(1);
document.add(titleParagraph);
document.close();

参考技术C 使用iText,iText是一个能够快速产生PDF文件的java类库。iText的java类对于那些要产生包含文本,表格,图形的只读文档是很有用的。它的类库尤其与java Servlet有很好的给合。使用iText与PDF能够使你正确的控制Servlet的输出。本回答被提问者采纳 参考技术D 1. 建立com.lowagie.text.Document对象的实例。
  Document document = new Document();
2.建立一个书写器(Writer)与document对象关联,通过书写器(Writer)可以将文档写入到磁盘中。
  PDFWriter.getInstance(document, new FileOutputStream("Helloworld.PDF"));
3.打开文档。
  document.open();
4.
向文档中添加内容。
  document.add(new Paragraph("Hello World"));
5.
关闭文档。
  document.close();

java生成PDF,并下载到本地

1、首先要写一个PDF工具类,以及相关工具 
2、PDF所需jar包 
iText是一种生成PDF报表的Java组件 
freemarker是基于模板来生成文本输出

    <dependency>
        <groupId>com.itextpdf</groupId>
        <artifactId>itext-asian</artifactId>
        <version>5.2.0</version>
    </dependency>

    <dependency>
        <groupId>com.lowagie</groupId>
        <artifactId>itext</artifactId>
        <version>2.1.7</version>
    </dependency>

    <dependency>
        <groupId>org.freemarker</groupId>
        <artifactId>freemarker</artifactId>
        <version>2.3.23</version>
    </dependency>

 

3、需要使用Adobe Acrobat pro软件把要生成的模板转换为PDF格式 
打开Adobe Acrobat pro,打开模板,选择 |—— 准备表单 ,它会自动检测并命名表单域,然后保存为pdf格式即可

PDF工具类

public class PDFTemplet {
    private String templatePdfPath;
    private String targetPdfpath;
    private ServiceOrder order ;

    public PDFTemplet() {
    }

public void PDFTemplet(File file,String basePath)thows Exception{
/*模板路径*/
      PdfReader reader = new PdfReader(templatePdfPath);
ByteArrayOutputStream bos=new ByteArrayOutputStream();
/* 读取*/
PdfStamper pdfStamper= new PdfStamper(reader,bos);
/*使用中文字体*/
BaseFont baseFont=BaseFont.createFont(basePath+"WEB-INF/static/SIMHEI.TTF",BaseFont.IDENTITY_H,BaseFont.EMBEDDED);
ArrayList<BaseFont> fontList=new ArrayList<>();
fontList.add(baseFont);
AcroFields  s=pdfStamper.getAcroFields();
s.setSubstitutionFonts(fontList);

/*需要注意的是  setField的name和命名的表单域名字要一致*/
s.setField("enterpriseName",order.getEnerpriseName());
 s.setField("incubatorName",order.getIncubatorName());
        s.setField("recommend","");//孵化器推荐
        s.setField("contacts",order.getContacts());
        s.setField("phone",order.getPhone());
        s.setField("email",order.getEmail());
        s.setField("category ","");//服务类别
        s.setField("demand",order.getDemand());
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss ");
        String createTime = formatter.format(order.getCreateTime());
        String updateTime = formatter.format(order.getUpdateTime());
        s.setField("createTime",createTime);
        s.setField("updateTime", updateTime);
ps.setFormFlattenning(true);
ps.close();
FileOutputStream fileSteam =new FileOutPutStream(file);
fos.write(bos.toByteArray);
fos.close();}


}

 

调用方法

 @RequestMapping(value ="downloadPdf", method = RequestMethod.GET)
    public String downloadPDF(@PathVariable("id") Integer id,HttpServletRequest request) throws Exception {
        ServiceOrder serviceOrder = serviceOrderService.getById(id);
        PDFTemplet pdfTT = new PDFTemplet();
        pdfTT.setOrder(serviceOrder);
        String basePath = request.getSession().getServletContext().getRealPath("/");
        String template = request.getSession().getServletContext().getRealPath("/") + "WEB-INF/static/excel/confirmation.pdf";

        pdfTT.setTemplatePdfPath(template);
        pdfTT.setTargetPdfpath("D:/企业服务确认单.pdf");
        pdfTT.setOrder(serviceOrder);

        File file = new File("D:/企业服务确认单.pdf");
        file.createNewFile();
        pdfTT.templetTicket(file,basePath);
        return "/master/serviceOrder/orderList";
    }




以上是关于如何运用Java组件itext生成pdf的主要内容,如果未能解决你的问题,请参考以下文章

如何运用Java组件itext生成pdf

如何运用Java组件itext生成pdf

如何运用Java组件itext生成pdf

如何运用Java组件itext生成pdf

如何运用Java组件itext生成pdf

java 已经获取pdf代码,如何把他pdf文件保存到本机 要求用输出流做