Java生成pdf以及页码显示和表格分页处理

最近要开发一个生成pdf版本合同的功能,在网上找了很多资料,没有得到想要的生成pdf页码的效果,最终参考一篇文章实现了想要的页码功能: https://www.iteye.com/blog/honda418-513746

以下为生成pdf全部功能的代码,末尾附效果图

import com.bizduo.zflow.util.FileUtil;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;
import javassist.runtime.Cflow;
import org.apache.poi.hssf.usermodel.HeaderFooter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import sun.font.FontFamily;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping(value = "/pdf")
public class CreatePdf {

    @Autowired
    private IDataService dataService;

    private static Font CFont; //中文字体
    private static Font EFont; //英文字体
    private static Font EFont2; //英文字体
    private static Font KFont; //楷体

    public PdfTemplate tpl; //模板用来固定显示数据
    public PdfTemplate tpl2; //模板用来固定显示数据

    //** 关注重点

    private static BaseFont bfChinese;

    static{
        try{
            //定义字体
            bfChinese = BaseFont.createFont("C:\\Users\\who\\Desktop\\simsun.ttc,1",BaseFont.IDENTITY_H,BaseFont.NOT_EMBEDDED);
            //中文字体
            CFont = new Font(bfChinese,12,Font.UNDEFINED);
            //英文字体
            KFont = new Font(bfChinese,11,Font.BOLD);
            EFont = new Font(Font.FontFamily.TIMES_ROMAN,12,Font.UNDEFINED);
//            bfChinese = BaseFont.createFont("C:\\Users\\who\\Desktop\\arialuni.ttf",BaseFont.IDENTITY_H,BaseFont.NOT_EMBEDDED);
//            EFont2 = new Font(bfChinese,12,Font.UNDEFINED);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

//    public static void main(String[] args) {
//        createpdf(1270);
//    }

    @RequestMapping(value = "/contract")
    public void createContractPdf(@RequestParam(value = "order_id", required = true) Integer order_id, HttpServletRequest request) {
        try{
            createpdf(order_id,request);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    public void createpdf(Integer order_id,HttpServletRequest request) {
        try{
            String pdfname="";
            List<Map<String, Object>> resultset = dataService.callShellProcedure("R2019005|"+order_id);
            Map<String,Object> orderMap=resultset.get(0);
            List<Map<String, Object>> orderDetail = dataService.callShellProcedure("R2019006|"+order_id);


            SimpleDateFormat dataFm=new SimpleDateFormat("yyyyMMdd");
            String dataStr=dataFm.format(new Date());
            pdfname+=orderMap.get("vendor_name").toString()+dataStr+"("+orderMap.get("code").toString()+")";

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String filepath=request.getSession().getServletContext().getRealPath("/WEB-INF")+ File.separator + "upload" + File.separator + sdf.format(new Date());
            File dir = new File(filepath);
            if(dir.exists()) {
                dir.mkdirs();
            }

            // 1.创建一个document
            Document document = new Document(PageSize.A4);
            //** 定义writer写入页码等 2.定义pdfWriter,指明文件输出流输出到一个文件
            PdfWriter writer = PdfWriter.getInstance(document,new FileOutputStream(filepath+File.separator+pdfname+".pdf"));

            //3.打开文档
            document.open();

            //** 创建模板存放页码内容以及模块大小
            tpl = writer.getDirectContent().createTemplate(100, 100);
            tpl2 = writer.getDirectContent().createTemplate(100, 100);

            //** 声明表格列数
            PdfPTable table = new PdfPTable(2);
            table.setWidthPercentage(100); // 宽度100%填充
            table.setSpacingBefore(10f); // 前间距
            table.setSpacingAfter(10f); // 后间距

            // 设置列宽
            float[] columnWidths = { 1.3f, 0.5f};
            table.setWidths(columnWidths);
            table.getDefaultCell().setBorder(0); //表格边框

            PdfPCell pdfPCell;
            Chunk chunk;
            Paragraph paragraph;

            //显示固定页码位置
            getTotalNum(writer);
            //第一行
            pdfPCell = new PdfPCell();
            Paragraph faxparagrah = new Paragraph();
            faxparagrah.add(new Paragraph("FAX\n\n", FontFactory.getFont(FontFactory.TIMES_ROMAN,36, Font.UNDEFINED)));
            faxparagrah.add(new Paragraph("Number of pages (including this page): ", FontFactory.getFont(FontFactory.TIMES_ROMAN,(float) 10.5, Font.UNDEFINED)));
            pdfPCell.setPhrase(faxparagrah);
            //表格边框设置为空
            table.addCell(pdfPCell).setBorder(0);

            pdfPCell = new PdfPCell();
            Paragraph cellParagraph= new Paragraph();
            chunk = new Chunk("*******有限公司\n", KFont);
            paragraph = new Paragraph(chunk);
            cellParagraph.add(paragraph);
            BaseFont baseFont;
//            baseFont = BaseFont.createFont("Times-Roman","UniGB-UCS2-H",BaseFont.NOT_EMBEDDED);
//            Font font = new Font(baseFont,(float) 10.5,Font.BOLD);
            Font font = new Font(Font.FontFamily.TIMES_ROMAN,(float) 10.5,Font.BOLD);
            paragraph = new Paragraph("\n" +
                    "Automotive Components\n" +
                    "Co., Ltd.\n" ,font);
            cellParagraph.add(paragraph);
            paragraph = new Paragraph("\n" +
                    "Anting Industrial Zone\n" +
                    "Jiading District\n" +
                    "201814 Shanghai, China\n" ,FontFactory.getFont(FontFactory.TIMES_ROMAN,(float) 10.5, Font.UNDEFINED));
            cellParagraph.add(paragraph);
            cellParagraph.setAlignment(1);
            pdfPCell.setPhrase(cellParagraph);
            table.addCell(pdfPCell).setBorder(0);

            document.add(table);

            //显示第几页
            onEndPage(writer,document);
            //新的表格列
            PdfPTable table2 = new PdfPTable(4);
            table2.setWidthPercentage(100); // 宽度100%填充
            table2.setSpacingBefore(10f); // 前间距
            table2.setSpacingAfter(10f); // 后间距
            float[] columnWidths1 = { 0.25f, 0.6f, 0.25f, 0.6f};
            table2.setWidths(columnWidths1);
            //第一行
            pdfPCell = createPdfPCell("To:",true,font);
            table2.addCell(pdfPCell);
            pdfPCell = createPdfPCell(orderMap.get("linkman").toString(),true,CFont);  
            table2.addCell(pdfPCell).setBorder(0);
            pdfPCell = createPdfPCell("From:",true,font);
            table2.addCell(pdfPCell).setBorder(0);
            pdfPCell = createPdfPCell(orderMap.get("comp_name").toString(),true,CFont);  //*******有限公司
            table2.addCell(pdfPCell);
            //第二行
            pdfPCell = createPdfPCell("Company:",true,EFont);
            table2.addCell(pdfPCell);
            pdfPCell = createPdfPCell(orderMap.get("vendor_name").toString(),false,CFont);  
            table2.addCell(pdfPCell);
            pdfPCell = createPdfPCell("Name:",true,EFont);
            table2.addCell(pdfPCell);
            pdfPCell = createPdfPCell(orderMap.get("duserName").toString(),false,CFont);
            table2.addCell(pdfPCell);
            //第三行
            pdfPCell = createPdfPCell("",true,CFont);
            table2.addCell(pdfPCell);
            pdfPCell = createPdfPCell("",false,CFont);
            table2.addCell(pdfPCell);
            pdfPCell = createPdfPCell("Department:",true,EFont);
            table2.addCell(pdfPCell);
            pdfPCell = createPdfPCell("采购部",false,CFont);
            table2.addCell(pdfPCell);
            //第四行
            pdfPCell = createPdfPCell("Department:",true,EFont);
            table2.addCell(pdfPCell);
            pdfPCell = createPdfPCell(orderMap.get("vendor_department").toString(),false,CFont);  
            table2.addCell(pdfPCell);
            pdfPCell = createPdfPCell("Tel.- No.:",true,EFont);
            table2.addCell(pdfPCell);
            pdfPCell = createPdfPCell(orderMap.get("telephone").toString(),false,CFont);   
            table2.addCell(pdfPCell);
            //第五行
            pdfPCell = createPdfPCell("Tel:",true,EFont);
            table2.addCell(pdfPCell);
            pdfPCell = createPdfPCell(orderMap.get("linkman_phone").toString(),false,CFont);  
            table2.addCell(pdfPCell);
            pdfPCell = createPdfPCell("Fax-No.:",true,EFont);
            table2.addCell(pdfPCell);
            pdfPCell = createPdfPCell("0086-21-69979017",false,CFont); 
            table2.addCell(pdfPCell);
            //第五行
            pdfPCell = createPdfPCell("Fax-No.:",true,EFont);
            table2.addCell(pdfPCell);
            pdfPCell = createPdfPCell(orderMap.get("fax").toString(),false,CFont);  
            table2.addCell(pdfPCell);
            pdfPCell = createPdfPCell("E-mail:",true,EFont);
            table2.addCell(pdfPCell);
            pdfPCell = createPdfPCell(orderMap.get("mail").toString(),false,CFont);  
            table2.addCell(pdfPCell);
            //第五行
            pdfPCell = createPdfPCell("Copy to:",true,EFont);
            table2.addCell(pdfPCell);
            pdfPCell = createPdfPCell("",false,CFont);
            table2.addCell(pdfPCell);
            pdfPCell = createPdfPCell("Date:",true,EFont);
            table2.addCell(pdfPCell);
            pdfPCell = createPdfPCell(orderMap.get("date").toString(),false,CFont);  
            table2.addCell(pdfPCell);
            document.add(table2);

            //显示第几页
            onEndPage(writer,document);

            paragraph = new Paragraph(
                    "    您好!\n" +
                    "我司为*******有限公司,现需采购产品一批,请在交货期(1周)前将货物送至*******有限公司。\n" +
                    "付款条件:预付100%。\n" +
                    "具体订货如下:",CFont);
            document.add(paragraph);
            int num=0;
            //循环数据
            for(int i=0;i<50;i++){
                Map<String,Object> orderlist=orderDetail.get(0);
                num+=1;
                //1.宁波电测箱故障维修费                 数量:1次           单价:60498.45元
                paragraph = new Paragraph(
                        num+"."+orderlist.get("name").toString()+"                 数量:"+orderlist.get("requiredNum").toString()+orderlist.get("unit").toString()+"           单价:"+orderlist.get("taxedAmount").toString()+"元",CFont);
                document.add(paragraph);
            }

            //显示第几页
            onEndPage(writer,document);
            paragraph = new Paragraph("总计:(含税" +
                    orderMap.get("tax").toString()+"%):"+orderMap.get("taxedAmountSum").toString()+"\n\n",CFont);   
            document.add(paragraph);

            paragraph = new Paragraph();
            chunk = new Chunk("税号:",CFont);
            paragraph.add(chunk);
            chunk = new Chunk(orderMap.get("identify_number").toString()+"                          ");  
            paragraph.add(chunk);
            chunk = new Chunk("电话:",CFont);
            paragraph.add(chunk);
            chunk = new Chunk(orderMap.get("tel").toString()+"\n");  
            paragraph.add(chunk);
            chunk = new Chunk("账号:",CFont);
            paragraph.add(chunk);
            chunk = new Chunk(orderMap.get("bank_number").toString()+"                                 "); 
            paragraph.add(chunk);
            chunk = new Chunk("邮编:",CFont);
            paragraph.add(chunk);
            chunk = new Chunk(orderMap.get("postcode").toString()+"\n");
            paragraph.add(chunk);
            chunk = new Chunk("公司地址:"+orderMap.get("address").toString()+"\n\n",CFont);
            paragraph.add(chunk);

//            paragraph.add(new Paragraph("913100006074029383"));
            document.add(paragraph);

            paragraph = new Paragraph("收货人、发货地址:\n" +
                    "  *******有限公司\n" +
                    "  "+orderMap.get("receivingAddress").toString()+"\n" +
                    "  联系人:"+orderMap.get("realname").toString()+" 收   电话:"+orderMap.get("receving_phone").toString()+"      订单号:"+orderMap.get("code").toString()+"\n" +
                    "\n" +
                    "供应商回签:邮件答复确认!\n", CFont);
            document.add(paragraph);

            //测试表格分割效果
            PdfPTable table3 = new PdfPTable(1);
            table3.setWidthPercentage(100); // 宽度100%填充
            table3.setSpacingBefore(10f); // 前间距
            table3.setSpacingAfter(10f); // 后间距
            float[] columnWidths2 = { 0.25f};
            table3.setWidths(columnWidths2);
            //第一行
            pdfPCell = new PdfPCell();
            pdfPCell.setPhrase(new Paragraph("11111\n111\n2222\n2222\n3333", CFont));
            table3.addCell(pdfPCell);
            onEndPage(writer,document);
            //第一行
            pdfPCell = new PdfPCell();
            pdfPCell.setPhrase(new Paragraph("11111\n111\n2222\n2222\n3333", CFont));
            table3.addCell(pdfPCell);
            //第一行
            pdfPCell = new PdfPCell();
            pdfPCell.setPhrase(new Paragraph("11111\n111\n2222\n2222\n3333", CFont));
            table3.addCell(pdfPCell);
            //第一行
            pdfPCell = new PdfPCell();
            pdfPCell.setPhrase(new Paragraph("11111\n111\n2222\n2222\n3333", CFont));
            table3.addCell(pdfPCell);
            document.add(table3);


            //显示第几页
            onEndPage(writer,document);
            onCloseDocument(writer,document);
            onCloseDocument2(writer,document);
            document.close();

        }catch (Exception e){
            e.printStackTrace();
        }
    }

    private void getTotalNum(PdfWriter writer ){
        PdfContentByte cb = writer.getDirectContent();
        cb.saveState();
        //** 创建以及固定显示总页数的位置
        cb.addTemplate(tpl2, 205, 720);//定位“y页” 在具体的页面调试时候需要更改这xy的坐标

//            cb.saveState();
        cb.stroke();
        cb.restoreState();
        cb.closePath();
    }

    //** 显示当前页码
    private void onEndPage(PdfWriter writer , Document document){
        PdfContentByte cb = writer.getDirectContent();
        cb.saveState();
        String text = "第" + writer.getPageNumber() + "页,共";
        cb.beginText();

        cb.setFontAndSize(bfChinese, 8);
        cb.setTextMatrix(250, 10);//定位“第x页,共” 在具体的页面调试时候需要更改这xy的坐标
        cb.showText(text);
        cb.endText();
        //** 创建以及固定显示总页数的位置
        cb.addTemplate(tpl, 283, 10);//定位“y页” 在具体的页面调试时候需要更改这xy的坐标

//            cb.saveState();
        cb.stroke();
        cb.restoreState();
        cb.closePath();
    }

    private static PdfPCell createPdfPCell(String text ,Boolean border, Font font) {
        PdfPCell pdfPCell = new PdfPCell();
        //合并单元格
//        pdfPCell.setColspan(colSpan);
//        pdfPCell.setRowspan(rowSpan);
        pdfPCell.setPhrase(new Paragraph(text, font));
        if(border){
            pdfPCell.setBorder(0);
        }else{
            //** 边框的是否显示
            pdfPCell.disableBorderSide(13);  ////            pdfPCell.disableBorderSide(4);  ////            pdfPCell.disableBorderSide(6);  ////            pdfPCell.disableBorderSide(8);  ////            pdfPCell.disableBorderSide(3);
        }
        return pdfPCell;
    }

    //** 显示总页数
    public void onCloseDocument(PdfWriter writer, Document document) {
//        //关闭document的时候获取总页数,并把总页数按模版写道之前预留的位置
        tpl.beginText();
        tpl.setFontAndSize(bfChinese, 8);
        tpl.showText(Integer.toString(writer.getPageNumber() )+"页");
        tpl.endText();
        tpl.closePath();//sanityCheck();
    }

    //** 显示总页数在第一页固定位置
    public void onCloseDocument2(PdfWriter writer, Document document) {
//        //关闭document的时候获取总页数,并把总页数按模版写道之前预留的位置
        tpl2.beginText();
        tpl2.setFontAndSize(bfChinese, 13);
        tpl2.showText(Integer.toString(writer.getPageNumber() ));
        tpl2.endText();
        tpl2.closePath();//sanityCheck();
    }
}

效果图如下:

 
原创https://www.cnblogs.com/longdie-lls/p/11773022.html 

猜你喜欢

转载自www.cnblogs.com/longdie-lls/p/11773022.html
今日推荐