Java 借助poi操作PDF工具類


一直以來說寫一個關於Java操作PDF的工具類,也沒有時間去寫,今天抽空寫一個簡單的工具類,擁有PDF中 換行,字體大小,字體設置,字體顏色,首行縮進,居中,居左,居右,增加新一頁等功能,如果需要Table表格的可以用Cell這個方法就可以實現,這個工具類參數也比較多點,自己想優化的,可以寫一個實體類來封裝。

好了,廢話不多說了。

首先我們引入需要的第三方jar包

 

<!-- https://mvnrepository.com/artifact/com.lowagie/itext -->
 <dependency>
     <groupId>com.lowagie</groupId>
     <artifactId>itext</artifactId>
     <version>2.1.7</version>
 </dependency>

<!-- https://mvnrepository.com/artifact/com.itextpdf/itextpdf -->
 <dependency>
      <groupId>com.itextpdf</groupId>
      <artifactId>itextpdf</artifactId>
      <version>5.5.11</version>
 </dependency>

 

 

iText是著名的開放項目,是用於生成PDF文檔的一個java類庫。通過iText不僅可以生成PDF或rtf的文檔,而且可以將XML、Html文件轉化為PDF文件。

下面我們直接就用代碼來描述。 

 

package com.herbert.test;

import com.lowagie.text.*;
import com.lowagie.text.Font;
import com.lowagie.text.pdf.BaseFont;
import com.lowagie.text.pdf.PdfWriter;

import java.awt.*;
import java.io.FileOutputStream;
import java.io.IOException;

/**
* Created by Herbert on 2019/1/21.
*/
public class PDFUtil {

   /**
    * document對象
    */
   private static Document document =  null;

   /**
    *  創建一個書寫器,布局文本位置
    * @param leftSize 居左
    * @param rightSize 居右
    * @param onSize 居上
    * @param underSize 居下
    * @param path 存儲位置
    * @throws Exception 初始化PDF錯誤
    */
   public PDFUtil(Integer leftSize , Integer rightSize , Integer onSize , Integer underSize, String path) throws Exception {
       try{
           // 新建document對象 第一個參數是頁面大小。接下來的參數分別是左、右、上和下頁邊距。
           document = new Document(PageSize.A4, leftSize, rightSize, onSize, underSize);
           // 建立一個書寫器(Writer)與document對象關聯,通過書寫器(Writer)可以將文檔寫入到磁盤中。
           PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(path));
           // 打開文件
           document.open();
       }catch (Exception e){
           e.printStackTrace();
           System.out.println("PDF初始化錯誤");
       }
   }

   /**
    *  書寫每一個段落選擇的字體
    *
    * @param fontType
    *             0 //楷體字
    *             1 //仿宋體
    *             2 //黑體
    *             字體需要可在追加
    * @return
    * @throws IOException
    * @throws DocumentException
    */
   public BaseFont addFontType(Integer fontType)  {
       BaseFont baseFont = null;
       try{

           switch (fontType){
               case 0:
                   //楷體字
                   baseFont = BaseFont.createFont("c://windows//fonts//simkai.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
                   break;
               case 1:
                   //仿宋體
                   baseFont = BaseFont.createFont("c://windows//fonts//SIMFANG.TTF", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
                   break;
               case 2:
                   //黑體
                   baseFont = BaseFont.createFont("c://windows//fonts//SIMHEI.TTF", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
                   break;
           }
           return baseFont;
       }catch (Exception e){
           System.out.println("選擇字體異常");
           e.printStackTrace();

       }
       return baseFont;
   }

   /**
    *  添加段落 -  段落位置( 0 居左  1 居中 2 居右)
    * @param fontType 選擇字體
    *             0 //楷體字
    *             1 //仿宋體
    *             2 //黑體
    * @param fontSize 字體大小
    * @param color 字體顏色
    * @param alignment   0 居左  1 居中 2 居右
    * @param text 文本內容
    */
   public void addParagraph(Integer fontType , Integer fontSize,Color color ,Integer alignment ,String text){
       try{
           BaseFont chinese =addFontType(fontType);
           Font font = new Font(chinese, fontSize, Font.COURIER,color);
           Paragraph paragraph =new Paragraph(text,font);
           //居中顯示
           paragraph.setAlignment(alignment);
           document.add(paragraph);
       }catch (Exception e){
           e.printStackTrace();
           System.out.println("添加段落異常");
       }
   }

   /**
    *  添加段落 -  首行縮進
    * @param fontType 選擇字體
    *             0 //楷體字
    *             1 //仿宋體
    *             2 //黑體
    * @param fontSize 字體大小
    * @param color 字體顏色
    * @param index  首行縮進
    * @param text 文本內容
    */
   public void addTextIndent(Integer fontType , Integer fontSize,Color color ,Integer index ,String text){
       try{
           BaseFont chinese =addFontType(fontType);
           Font font = new Font(chinese, fontSize, Font.COURIER,color);
           Paragraph paragraph =new Paragraph(text,font);
           //設置首行縮進
           paragraph.setFirstLineIndent(index);
           document.add(paragraph);
       }catch (Exception e){
           e.printStackTrace();
           System.out.println("添加段落異常");
       }
   }

   /**
    *  添加新的一頁
    */
   public void addPage(){
       try{
         document.newPage();
       }catch (Exception e){
           e.printStackTrace();
           System.out.println("添加段落異常");
       }
   }

   /**
    *  換行
    *  傳入1是一行,以此遞增
    * @param lineNum 換的行數
    */
   public void newLine(Integer lineNum) {
       try{
           for(int i =0 ; i<lineNum ; i++){
               document.add(new Paragraph("\n"));
           }
       }catch (Exception e){
           e.printStackTrace();
           System.out.println("換行錯誤");
       }
   }

   /**
    *  關閉文檔
    */
   public void close (){

       // 關閉文檔
       document.close();
   }

   public static void main(String args[]) throws Exception {
       PDFUtil pdfUtil = new PDFUtil(80, 80, 120, 120,"E:\\herbert\\test.pdf");
       pdfUtil.addParagraph(1,24,new Color(179, 91, 68),0,"我是0個測試案例--居左");
       pdfUtil.newLine(10);
       pdfUtil.addParagraph(1,24,new Color(75, 108, 179),1,"我是1個測試案例--居中 空行");
       pdfUtil.addParagraph(1,24,new Color(140, 109, 179),2,"我是2個測試案例--居右");
       pdfUtil.addPage();
       pdfUtil.addParagraph(1,24,new Color(73, 179, 130),1,"我是3個測試案例--新增頁");
       pdfUtil.addParagraph(1,24,new Color(179, 91, 68),0,"我是0個測試案例--居左");
       pdfUtil.addTextIndent(1,24,new Color(41, 124, 179),28,"我是3個測試案例--首行縮進");
       pdfUtil.close();

   }

}

 

測試截圖

 

注意事項:

1:這個方法目前只能在window上進行操作,如果在其他服務器上,由於使用window自帶中文字體,需要對方法進行改進

2:目前只是對段落進行簡單的操作,如果寫發票那樣的PDF文件,建議通過模板來實現,這樣格式比較規整

 

 


免責聲明!

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



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