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 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM