天天看點

Itext 5 Pdf 表格 流 浏覽器

自己的第二篇部落格,itext5生成pdf,變成流直接傳回給浏覽器,直接上代碼,具體看代碼注釋

發現一個問題,有些部落格也附上代碼 但是根本不告訴你裡面的引用是出自什麼包,這個讓人很頭疼,自己就遇見過很多類似問題。

第一步:引包如下

<!--PDF前兩個是itext5生成pdf必須-->
<dependency>
    <groupId>com.itextpdf</groupId>
    <artifactId>itextpdf</artifactId>
    <version>5.5.13</version>
</dependency>
<dependency>
    <groupId>com.itextpdf</groupId>
    <artifactId>itext-asian</artifactId>
    <version>5.2.0</version>
</dependency>

<!--後兩個是google生成二維碼-->
<dependency>
    <groupId>com.google.zxing</groupId>
    <artifactId>core</artifactId>
    <version>3.3.3</version>
</dependency>
<dependency>
    <groupId>com.google.zxing</groupId>
    <artifactId>javase</artifactId>
    <version>3.3.3</version>
</dependency>
           

具體引包如下:

import com.beta.small.controller.dto.InspectionItemResultDto;
import com.beta.small.controller.dto.InspectionResultPrintDto;
import com.beta.small.daolib.constant.InspectionStatus;
import com.beta.small.daolib.dao.VehicleBaseDao;
import com.beta.small.daolib.dao.VehicleDeviceDao;
import com.beta.small.daolib.model.VehicleBase;
import com.beta.small.daolib.model.VehicleDevice;
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;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.SimpleDateFormat;
           

代碼如下:

public class CreatePdfNew {

//printDtoList自己的參數資料,根據業務自己擷取
//response 将pdf直接變成流傳回給浏覽器
    public void createPdf(java.util.List<InspectionResultPrintDto> printDtoList, HttpServletResponse response){
        try {
            //頁面大小
            Rectangle rect = new Rectangle(PageSize.A4);
            //頁面背景色
            rect.setBackgroundColor(BaseColor.WHITE);
            // 1.建立document對象
            Document document = new Document(rect);
            //頁邊空白
            document.setMargins(16, 16, 56, 16);
            // 2.書寫器(Writer)與document對象關聯,通過書寫器(Writer)将文檔寫入到磁盤中或者浏覽器,本例傳回給浏覽器。
            PdfWriter.getInstance(document, response.getOutputStream());
            // 3.打開文檔
            document.open();
            //中文字型,解決中文不能顯示問題,沒有此段中文不顯示
            BaseFont bfChinese = BaseFont.createFont("STSong-Light","UniGB-UCS2-H",BaseFont.NOT_EMBEDDED);
            //将自有業務資料循環指派給pdf
            for (InspectionResultPrintDto list :printDtoList){
                //每次建立一個pdf頁
                document.newPage();
                //建立一個表格,資料代表列數,行數不用填寫,會随着PdfCell自增
                PdfPTable tablePage = new PdfPTable(5);
                //設定居中
                tablePage.setHorizontalAlignment(Element.ALIGN_CENTER);
                //設定每列的具體寬度
                tablePage.setWidthPercentage(new float[]{100f, 135f, 100f, 35f, 250f},rect);
                //設定表格總高度,setLockedWidth(true)必須,否則不好用
                tablePage.setLockedWidth(true);
                tablePage.setTotalWidth(510);//設定表格的總寬度
                //設定字型格式,Bold将自己加粗
                Font fontTitle = new Font(bfChinese,23,Font.BOLD);
                //建立一個單元格
                PdfPCell content01 = new PdfPCell();
                //二維碼對象,将二維碼攜帶資訊帶入生成方法中,具體生成方法在後面,
                ByteArrayOutputStream outputStream = encode(list.getInspectionNo());
                //建立一個圖檔對象,插入圖檔
                Image cImg = Image.getInstance(outputStream.toByteArray());
                //設定圖檔大小
                cImg.scaleAbsolute(80, 80);// 直接設定顯示尺寸
                cImg.setBorder(Image.BOX);
                //将圖檔資訊放入chunk,這裡面chunk為最小單元,phrase為第二小單元 之後是段落,此處不做具體介紹,可自行百度
                content01.setPhrase(new Phrase(new Chunk(cImg, 0, 0, true)));
                //單元格的邊框顯示,具體隐藏代碼見下面
                content01.disableBorderSide(8);
                //将單元格放入表格中
                tablePage.addCell(content01);
                //這裡面要注意,單元格是一個一個的順序插入資料的,舉個例子一行一列我們暫命名11,一行二列命名12,他是資料插                   入11後再插入12,在//插入13,等第一行滿了之後自動從第二行21開始插入

                PdfPCell title = new PdfPCell();
                title.setPhrase(new Phrase(new Chunk("      廣州市車輛終端入網許可證",fontTitle)));
                //下面3行為單元格設定水準居中,和垂直居中設定,其中setUseAscender必須,否則不好用
                title.setUseAscender(true);
                title.setHorizontalAlignment(Element.ALIGN_LEFT);//水準居中
                title.setVerticalAlignment(Element.ALIGN_MIDDLE); //垂直居中
                title.setFixedHeight(80);
                //合并單元格方法,我們定義5列,其中11的位置放入圖檔,2-5列合并,是以剩下4列,直接設定setColspan(4),後面四個單元格就會合并
                title.setColspan(4);
                title.disableBorderSide(4);
                tablePage.addCell(title);

                //設定字型格式
                Font font = new Font(bfChinese,15,Font.BOLD);
                Font fontValue = new Font(bfChinese,15);
                PdfPCell content11 = new PdfPCell();
                content11.setPhrase(new Phrase(new Chunk("車牌号",font)));
                content11.setUseAscender(true);
                content11.setHorizontalAlignment(Element.ALIGN_LEFT);//水準居中
                content11.setVerticalAlignment(Element.ALIGN_MIDDLE); //垂直居中
                content11.setFixedHeight(45);
                tablePage.addCell(content11);
                PdfPCell content12 = new PdfPCell();
                content12.setPhrase(new Phrase(new Chunk(list.getPlateCode(),fontValue)));
                content12.setUseAscender(true);
                content12.setHorizontalAlignment(Element.ALIGN_LEFT);//水準居中
                content12.setVerticalAlignment(Element.ALIGN_MIDDLE); //垂直居中
                tablePage.addCell(content12);
                PdfPCell content13 = new PdfPCell();
                content13.setPhrase(new Phrase(new Chunk("所屬公司",font)));
                content13.setUseAscender(true);
                content13.setHorizontalAlignment(Element.ALIGN_LEFT);//水準居中
                content13.setVerticalAlignment(Element.ALIGN_MIDDLE); //垂直居中
                tablePage.addCell(content13);
                PdfPCell content14 = new PdfPCell();
                content14.setPhrase(new Phrase(new Chunk(list.getTransportationName(),fontValue)));
                content14.setUseAscender(true);
                content14.setHorizontalAlignment(Element.ALIGN_LEFT);//水準居中
                content14.setVerticalAlignment(Element.ALIGN_MIDDLE); //垂直居中
                content14.setColspan(2);
                tablePage.addCell(content14);

                //下面2行查詢自己業務資訊放入PDF,根據自有業務修改
                VehicleBase vehicleBase = vehicleBaseDao.findOneActive(list.getVehicleId());
                VehicleDevice vehicleDevice = vehicleDeviceDao.findOneActive(vehicleBase.getDeviceId());

                PdfPCell content21 = new PdfPCell();
                content21.setPhrase(new Phrase(new Chunk("品牌型号",font)));
                content21.setUseAscender(true);
                content21.setHorizontalAlignment(Element.ALIGN_LEFT);//水準居中
                content21.setVerticalAlignment(Element.ALIGN_MIDDLE); //垂直居中
                content21.setFixedHeight(45);
                tablePage.addCell(content21);
                PdfPCell content22 = new PdfPCell();
                String brand = "";
                if(vehicleBase.getBrand()!=null&&!"".equals(vehicleBase.getBrand())){
                    brand = vehicleBase.getBrand();
                }
                content22.setPhrase(new Phrase(new Chunk(brand,fontValue)));
                content22.setUseAscender(true);
                content22.setHorizontalAlignment(Element.ALIGN_LEFT);//水準居中
                content22.setVerticalAlignment(Element.ALIGN_MIDDLE); //垂直居中
                tablePage.addCell(content22);
                PdfPCell content23 = new PdfPCell();
                content23.setPhrase(new Phrase(new Chunk("銷售公司",font)));
                content23.setUseAscender(true);
                content23.setHorizontalAlignment(Element.ALIGN_LEFT);//水準居中
                content23.setVerticalAlignment(Element.ALIGN_MIDDLE); //垂直居中
                tablePage.addCell(content23);
                PdfPCell content24 = new PdfPCell();
                String salesCompany = "";
                if(vehicleBase.getSalesCompany()!=null&&!"".equals(vehicleBase.getSalesCompany())){
                    salesCompany = vehicleBase.getSalesCompany();
                }
                content24.setPhrase(new Phrase(new Chunk(salesCompany,fontValue)));
                content24.setUseAscender(true);
                content24.setHorizontalAlignment(Element.ALIGN_LEFT);//水準居中
                content24.setVerticalAlignment(Element.ALIGN_MIDDLE); //垂直居中
                content24.setColspan(2);
                tablePage.addCell(content24);

                PdfPCell content31 = new PdfPCell();
                content31.setPhrase(new Phrase(new Chunk("終端裝置号",font)));
                content31.setUseAscender(true);
                content31.setHorizontalAlignment(Element.ALIGN_LEFT);//水準居中
                content31.setVerticalAlignment(Element.ALIGN_MIDDLE); //垂直居中
                content31.setFixedHeight(45);
                tablePage.addCell(content31);
                PdfPCell content32 = new PdfPCell();
                content32.setPhrase(new Phrase(new Chunk(list.getCommunicationNo(),fontValue)));
                content32.setUseAscender(true);
                content32.setHorizontalAlignment(Element.ALIGN_LEFT);//水準居中
                content32.setVerticalAlignment(Element.ALIGN_MIDDLE); //垂直居中
                tablePage.addCell(content32);
                PdfPCell content33 = new PdfPCell();
                content33.setPhrase(new Phrase(new Chunk("終端型号",font)));
                content33.setUseAscender(true);
                content33.setHorizontalAlignment(Element.ALIGN_LEFT);//水準居中
                content33.setVerticalAlignment(Element.ALIGN_MIDDLE); //垂直居中
                tablePage.addCell(content33);
                PdfPCell content34 = new PdfPCell();
                String model = "";
                if(vehicleDevice.getModel()!=null&&!"".equals(vehicleDevice.getModel())){
                    model = vehicleDevice.getModel();
                }
                content34.setPhrase(new Phrase(new Chunk(model,fontValue)));
                content34.setUseAscender(true);
                content34.setHorizontalAlignment(Element.ALIGN_LEFT);//水準居中
                content34.setVerticalAlignment(Element.ALIGN_MIDDLE); //垂直居中
                content34.setColspan(2);
                tablePage.addCell(content34);

                PdfPCell content41 = new PdfPCell();
                content41.setPhrase(new Phrase(new Chunk("驗收項及驗收結果",font)));
                content41.setUseAscender(true);
                content41.setHorizontalAlignment(Element.ALIGN_LEFT);//水準居中
                content41.setVerticalAlignment(Element.ALIGN_MIDDLE); //垂直居中
                content41.setFixedHeight(45);
                tablePage.addCell(content41);

                PdfPCell content42 = new PdfPCell();
                content42.setRowspan(4);

                PdfPTable tableItem = new PdfPTable(2);
                //此處用到了表格嵌套,就是在合并的單元格内嵌套進入新表格
                java.util.List<InspectionItemResultDto> itemResultDto = list.getItemResultDto();
                for (InspectionItemResultDto item :itemResultDto){
                    Font black = new Font(bfChinese,12);
                    Font red = new Font(bfChinese,12);
                    red.setColor(BaseColor.RED);
                    PdfPCell cell11 = new PdfPCell();
                    cell11.disableBorderSide(15);//去邊框
                    Phrase para1 = new Phrase(item.getName(),black);
                    cell11.setPhrase(para1);
                    tableItem.addCell(cell11);

                    PdfPCell cell21 = new PdfPCell();
                    cell21.disableBorderSide(15);//去邊框
                    Phrase para2 = new Phrase(item.getInspectionStatus(),red);
                    cell21.setPhrase(para2);
                    tableItem.addCell(cell21);
                }
                content42.addElement(tableItem);
                content42.setColspan(4);
                tablePage.addCell(content42);

                PdfPCell content51 = new PdfPCell();
                content51.setPhrase(new Phrase(new Chunk("驗收結果:"+list.getInspectionStatus(),font)));
                content51.setColspan(5);
                content51.disableBorderSide(2);
                tablePage.addCell(content51);

                PdfPCell content61 = new PdfPCell();
                content61.setPhrase(new Phrase(new Chunk("驗收意見:"+list.getInspectionOpinion(),font)));
                content61.setColspan(5);
                content61.disableBorderSide(3);
                tablePage.addCell(content61);

                PdfPCell content71 = new PdfPCell();
                content71.setPhrase(new Phrase(new Chunk("     ",font)));
                content71.setColspan(5);
                content71.disableBorderSide(3);
                tablePage.addCell(content71);

                PdfPCell content81 = new PdfPCell();
                content81.setPhrase(new Phrase(new Chunk("     ",font)));
                content81.setColspan(5);
                content81.disableBorderSide(3);
                tablePage.addCell(content81);

                Font foot = new Font(bfChinese,12);
                PdfPCell content91 = new PdfPCell();
                SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd");
                content91.setPhrase(new Phrase(new Chunk("驗收時間:"
                        +sd.format(list.getInspectionTime())+"          驗收人:"+list.getInspectorName()+"          驗收機關:",foot)));
                content91.disableBorderSide(11);
                content91.setColspan(4);
                tablePage.addCell(content91);

                PdfPCell content94 = new PdfPCell();
                content94.setPhrase(new Phrase(new Chunk(list.getInstallationName(),foot)));
                content94.disableBorderSide(7);
                tablePage.addCell(content94);

                Font bottom = new Font(bfChinese,2);
                PdfPCell content101 = new PdfPCell();
                content101.setPhrase(new Phrase(new Chunk("     ",bottom)));
                content101.setColspan(5);
                content101.disableBorderSide(1);
                tablePage.addCell(content101);
                //将表格放入到document中,
                document.add(tablePage);
            }
            // 5.關閉文檔
            document.close();
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }catch (IOException e) {
            e.printStackTrace();
        }
    }
}
           

//生成二維碼方法

public ByteArrayOutputStream encode(String inspectionNo) {

int width = 98;
    int height = 98;
    String format = "jpg";
    Hashtable hints = new Hashtable();
    hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
    BitMatrix bitMatrix = null;
    try {
        bitMatrix = new MultiFormatWriter().encode(inspectionNo, BarcodeFormat.QR_CODE, width, height, hints);
    } catch (WriterException e) {
        e.printStackTrace();
    }
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    try {
        MatrixToImageWriter.writeToStream(bitMatrix, format, outputStream);
    } catch (IOException e) {
        e.printStackTrace();
    }
    return outputStream;
}
           

附帶邊框設計方法,此處摘自https://blog.csdn.net/cfup_less/article/details/82686426

感謝部落客的邊框總結

//建立單元格對象

PdfPCell cell = new PdfPCell(new Phrase("test"));

//隐藏上邊框

cell.disableBorderSide(1);

//隐藏下邊框

cell.disableBorderSide(2);

//隐藏上、下邊框

cell.disableBorderSide(3);

//隐藏左邊框

cell.disableBorderSide(4);

//隐藏左、上邊框

cell.disableBorderSide(5);

//隐藏左、下邊框

cell.disableBorderSide(6);

//隐藏左、上、下邊框

cell.disableBorderSide(7);

//隐藏右邊框

cell.disableBorderSide(8);

//隐藏右、上邊框

cell.disableBorderSide(9);

//隐藏右、下邊框

cell.disableBorderSide(10);

//隐藏右、上、下邊框

cell.disableBorderSide(11);

//隐藏左、右邊框

cell.disableBorderSide(12);

//隐藏上、左、右邊框

cell.disableBorderSide(13);

//隐藏下、左、右邊框

cell.disableBorderSide(14);

//隐藏全部

cell.disableBorderSide(15);

---------------------

作者:cfup_less

來源:CSDN

原文:https://blog.csdn.net/cfup_less/article/details/82686426

版權聲明:本文為部落客原創文章,轉載請附上博文連結!

Pdf建立結果如下: