溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

Java如何使用itext5實(shí)現(xiàn)PDF表格文檔導(dǎo)出

發(fā)布時(shí)間:2021-09-23 11:43:46 來(lái)源:億速云 閱讀:153 作者:小新 欄目:編程語(yǔ)言

這篇文章主要介紹了Java如何使用itext5實(shí)現(xiàn)PDF表格文檔導(dǎo)出,具有一定借鑒價(jià)值,感興趣的朋友可以參考下,希望大家閱讀完這篇文章之后大有收獲,下面讓小編帶著大家一起了解一下。

1.依賴導(dǎo)入

<!-- https://mvnrepository.com/artifact/com.itextpdf/itextpdf -->  <dependency>   <groupId>com.itextpdf</groupId>   <artifactId>itextpdf</artifactId>   <version>5.5.13.1</version>  </dependency>  <!-- https://mvnrepository.com/artifact/com.itextpdf/itext-asian -->  <dependency>   <groupId>com.itextpdf</groupId>   <artifactId>itext-asian</artifactId>   <version>5.2.0</version>  </dependency>

這里說(shuō)明下:上面的依賴就是主要實(shí)現(xiàn)PDF生成的,下面的依賴是中文字體相關(guān)依賴;

2.PDF表格導(dǎo)出實(shí)現(xiàn)

1.導(dǎo)出PDF

//   1.打開文檔并設(shè)置基本屬性   Document document = new Document();//   2.設(shè)置請(qǐng)求頭,encode文件名   response.setContentType("application/pdf;charset=UTF-8");   response.setHeader("Content-Disposition",    "attachment; filename=" + java.net.URLEncoder.encode("" +    recordDto.getTitle() + ".pdf", "UTF-8"));//   3.通過(guò)流將pdf實(shí)例寫出到瀏覽器   PdfWriter writer = PdfWriter.getInstance(document, response.getOutputStream());

至此導(dǎo)出PDF已經(jīng)實(shí)現(xiàn)了,只是這個(gè)PDF中什么內(nèi)容都沒(méi)有,明白這一點(diǎn),接下來(lái)做的就是給這個(gè)文檔“加料”咯(這里的response就是HttpServletResponse)。

2.頁(yè)面美化

//    這里的wirter就是上文的writer   writer.setViewerPreferences(PdfWriter.PageModeUseThumbs);   writer.setPageSize(PageSize.A4);

這里設(shè)置了文檔的顯示縮略圖以及文檔大小為A4;

3.中文字體設(shè)置

public static Font getPdfChineseFont() throws Exception {  BaseFont bfChinese = BaseFont.createFont("STSongStd-Light", "UniGB-UCS2-H",    BaseFont.NOT_EMBEDDED);  Font fontChinese = new Font(bfChinese, 12, Font.NORMAL);  fontChinese.setColor(BaseColor.BLACK);  fontChinese.setSize(11);  return fontChinese; }

這個(gè)方法設(shè)置了中文字體樣式,感興趣的同學(xué)可以試試其他的樣式,例如:字體顏色,大小,字體都可以修改;

4.輸出表格內(nèi)容到文檔

// 首先打開文檔document.open();// 向文檔中添加表格數(shù)據(jù)private static void printBasicInfo(ShopApplyRecordDto recordDto, Document document, Font font) throws DocumentException {// 表格中的數(shù)據(jù)  Object[][] basicDatas = {    {"標(biāo)題","xxx申請(qǐng)", "審批編號(hào)","1234"},    {"申請(qǐng)人","小明", "申請(qǐng)商鋪","xxx商場(chǎng)"},    {"申請(qǐng)日期","2020/1/16", "審批結(jié)果","同意")}};// 每個(gè)cell的寬度  float[] widthss = {50, 200, 50, 200};//   創(chuàng)建一個(gè)表格,每一行有四個(gè)cell  PdfPTable basicTable = new PdfPTable(widthss);// 外層循環(huán)表格的行  for (int i = 0; i < basicDatas.length; i++) {// 內(nèi)層循環(huán)每一行具體數(shù)據(jù)   for (int j = 0; j < basicDatas[i].length; j++) {//   新建一個(gè)cell    PdfPCell cell = new PdfPCell();// 這個(gè)方法是統(tǒng)一設(shè)置表格和cell的樣式,下面會(huì)寫     setTableStyle(basicTable, cell);// cell中需要填充數(shù)據(jù)的格式    Paragraph paragraph =     new Paragraph(StrUtil.toString(basicDatas[i][j]), font);// 設(shè)置cell的值    cell.setPhrase(paragraph);// 將cell添加到表格中    basicTable.addCell(cell);   }  }// 將表格添加到文檔中  document.add(basicTable); }// 結(jié)束時(shí)要關(guān)閉文檔document.close();

大功告成,現(xiàn)在導(dǎo)出的PDF中已經(jīng)有了類似這樣的表格了:

當(dāng)然你的樣式會(huì)很丑,接下來(lái)我們來(lái)設(shè)置下樣式。

5.表格和cell樣式設(shè)置

public static void setTableStyle(PdfPTable table, PdfPCell cell) {// 設(shè)置表格樣式  table.setLockedWidth(true);  table.setTotalWidth(500);  table.setHorizontalAlignment(Element.ALIGN_LEFT);// 設(shè)置單元格樣式  cell.setMinimumHeight(35);  cell.setHorizontalAlignment(Element.ALIGN_CENTER);  cell.setVerticalAlignment(Element.ALIGN_MIDDLE);  cell.setBackgroundColor(BaseColor.WHITE);  cell.setBorder(0);  cell.setBorderWidthTop(0.1f);  cell.setBorderWidthBottom(0.1f);  cell.setBorderWidthLeft(0.1f);  cell.setBorderWidthRight(0.1f);  cell.setBorderColorBottom(BaseColor.BLACK);  cell.setBorderColorLeft(BaseColor.BLACK);  cell.setBorderColorRight(BaseColor.BLACK);  cell.setBorderColorTop(BaseColor.BLACK);  cell.setPadding(3); }

api方法還是比較易懂的,這里就不多贅述了,不明白的自己設(shè)置試試就可以做出自己喜歡的樣式咯。

6.頁(yè)眉和頁(yè)碼的設(shè)置

這里說(shuō)明下,itext2和itext5的api有很大不同,2的版本有一個(gè)專門的HeaderFooter類來(lái)設(shè)置樣式,5的版本沒(méi)有這樣的類,取而代之的是PdfPageEventHelper這樣一個(gè)事件處理類,這里大家千萬(wàn)別弄混了,這兩個(gè)版本的api互相不兼容;這里首先寫一個(gè)PdfPageEventHelper的子類來(lái)實(shí)現(xiàn)頁(yè)眉頁(yè)碼的打?。?/p>

public class HeaderFooter extends PdfPageEventHelper {// 這里是業(yè)務(wù)相關(guān)的屬性可以無(wú)視 private ShopApplyRecordDto recordDto; private SysUserInfo userInfo;// 大部分情況下頁(yè)眉的值是動(dòng)態(tài)的,這里可以在初始化的時(shí)候進(jìn)行參數(shù)傳遞 public HeaderFooter(ShopApplyRecordDto recordDto, SysUserInfo userInfo) {  this.recordDto = recordDto;  this.userInfo = userInfo; } public HeaderFooter() { } public ShopApplyRecordDto getRecordDto() {  return recordDto; } public void setRecordDto(ShopApplyRecordDto recordDto) {  this.recordDto = recordDto; } public SysUserInfo getUserInfo() {  return userInfo; } public void setUserInfo(SysUserInfo userInfo) {  this.userInfo = userInfo; }// 這個(gè)方法就是實(shí)現(xiàn)頁(yè)眉和頁(yè)碼的關(guān)鍵:它的含義是每當(dāng)頁(yè)面結(jié)束會(huì)執(zhí)行該方法 @Override public void onEndPage(PdfWriter writer, Document document) {  Font font = null;  try {   font = getPdfChineseFont();  } catch (Exception e) {   e.printStackTrace();  }  SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd HH:mm");// 設(shè)置頁(yè)眉:這里圖省事就用空格來(lái)實(shí)現(xiàn)左中右三個(gè)位置的頁(yè)眉,其實(shí)可以寫三個(gè),通過(guò)Element.ALIGN_LEFT來(lái)控制頁(yè)眉的位置,document.left()/document.top()這兩個(gè)可以設(shè)置頁(yè)眉具體位置類似于html的上下調(diào)整,大家可以多試試  ColumnText.showTextAligned(writer.getDirectContent(),   Element.ALIGN_LEFT,  new Phrase("所屬項(xiàng)目:" + recordDto.getMallName() + "             打印時(shí)間:" + format.format(new Date()) + "         打印人:" + userInfo.getUserName(), font),  document.left(),  document.top() + 3, 0);// 獲得一個(gè)名為“art”的盒子   Rectangle rect = writer.getBoxSize("art");// 設(shè)置頁(yè)碼:這里的頁(yè)碼位置已經(jīng)設(shè)置好,大家可直接使用,至于1/20這種效果的頁(yè)碼實(shí)現(xiàn)則十分復(fù)雜,如有需求請(qǐng)自行百度/谷歌  ColumnText.showTextAligned(writer.getDirectContent(),  Element.ALIGN_CENTER,   new Phrase(String.format("%d", writer.getPageNumber())),  (rect.getLeft() + rect.getRight()) / 2,   rect.getBottom() - 18, 0); } public static Font getPdfChineseFont() throws Exception {  BaseFont bfChinese = BaseFont.createFont("STSongStd-Light", "UniGB-UCS2-H",    BaseFont.NOT_EMBEDDED);  Font fontChinese = new Font(bfChinese, 12, Font.NORMAL);  fontChinese.setColor(BaseColor.BLACK);  fontChinese.setSize(11);  return fontChinese; }} 接下來(lái)就很簡(jiǎn)單了,將我們的HeaderFooter設(shè)置給PdfWriter對(duì)象即可:// 新建HeaderFooter并傳遞需要的參數(shù)HeaderFooter headerFooter = new HeaderFooter(recordDto, userInfo);// 新建一個(gè)盒子Rectangle rect = new Rectangle(36, 54, 559, 788);// 設(shè)置名稱為“art”,上面get的就是這個(gè)盒子了writer.setBoxSize("art", rect);writer.setPageEvent(headerFooter);// 這個(gè)可以設(shè)置內(nèi)容的margindocument.setMargins(45f, 45f, 65f, 50f);

感謝你能夠認(rèn)真閱讀完這篇文章,希望小編分享的“Java如何使用itext5實(shí)現(xiàn)PDF表格文檔導(dǎo)出”這篇文章對(duì)大家有幫助,同時(shí)也希望大家多多支持億速云,關(guān)注億速云行業(yè)資訊頻道,更多相關(guān)知識(shí)等著你來(lái)學(xué)習(xí)!

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI