iText5實現Java生成PDF文件完整版


最近項目中使用到Java實現導出PDF文件,經過一番參考研究最終決定使用itextpdf來實現,當然也可以參考 PDF Java類庫:Spire.PDF for Java(https://www.e-iceblue.cn/spirepdfjava/create-pdf-in-java.html)。本文是使用第一種來實現的。
iText是著名的開放源碼的站點sourceforge一個項目,是用於生成PDF文檔的一個java類庫。通過iText不僅可以生成PDF或rtf的文檔,而且可以將XML、Html文件轉化為PDF文件。
首先如果是maven項目的話需要添加2個依賴,普通項目的話在官網(http://itextpdf.com/)下載對應的2個jar包加入即可。LZ是maven項目,添加依賴如下:

 <!-- https://mvnrepository.com/artifact/com.itextpdf/itextpdf -->
    <dependency>
      <groupId>com.itextpdf</groupId>
      <artifactId>itextpdf</artifactId>
      <version>5.5.13</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>

建立第一個PDF文檔:
一、主要步驟(5個):
1.新建document對象,可通過一下三種任意一種
Document document =new Document(); // 默認頁面大小是A4
Document document =new Document(PageSize.A4); // 指定頁面大小為A4
Document document =new Document(PageSize.A4,50,50,30,20); // 指定頁面大小為A4,且自定義頁邊距(marginLeft、marginRight、marginTop、marginBottom)
其中頁面大小PageSize也可自定義大小,例:new Document(new Rectangle(400, 500));
2.建立一個書寫器(Writer)與document對象關聯,通過書寫器(Writer)可以將文檔寫入到磁盤中。
創建 PdfWriter 對象 第一個參數是對文檔對象的引用,第二個參數是文件的實際名稱,在該名稱中還會給出其輸出路徑
PdfWriter writer =PdfWriter.getInstance(document,new FileOutputStream(filePath));
3.打開文檔
寫入數據之前要打開文檔
document.open();
4.向文檔中添加內容
document.add();
5.關閉文檔
document.close();
 二、字體
新建一個字體,iText的方法
BaseFont bfChinese;
bfChinese=BaseFont.createFont("STSongStd-Light","UniGB-UCS2-H",BaseFont.NOT_EMBEDDED);//jar包
bfChinese=BaseFont.createFont("C:/Windows/Fonts/msyh.ttf",BaseFont.IDENTITY_H,BaseFont.NOT_EMBEDDED); //系統字體,其實5.0版以后的iText加入字體還是很方便的。
STSongStd-Light 是字體,在jar 中以property為后綴
UniGB-UCS2-H 是編碼,在jar 中以cmap為后綴
H 代表文字版式是橫版,相應的 V 代表豎版
字體設置
參數一:新建好的字體;參數二:字體大小,參數三:字體樣式,多個樣式用“|”分隔
Font topfont = new Font(bfChinese,14,Font.BOLD);
Font textfont =new Font(bfChinese,10,,Font.BOLD|Font.UNDERLINE);
 三、添加文本的對象:塊、短句和段落
Chunk:塊(Chunk)是能被添加到文檔的文本的最小單位。
Phrase:短句(Phrase)是一系列以特定間距(兩行之間的距離)作為參數的塊。
Paragraph:段落是一系列塊和(或)短句。同短句一樣,段落有確定的間距。用戶還可以指定縮排;在邊和(或)右邊保留一定空白,段落可以左對齊、右對齊和居中對齊。添加到文檔中的每一個段落將自動另起一行。
 四、步驟2書寫器創建之后,步驟3文檔打開之前
以下項只可在文檔關閉狀態執行 ,包括水印、頁眉、頁腳
水印
Watermark內部類,需要繼承 PdfPageEventHelper類
writer.setPageEvent(new Watermark());
頁眉/頁腳
iText5中並沒有之前版本HeaderFooter對象設置頁眉和頁腳,可以利用PdfPageEvent來完成頁眉頁腳的設置工作。
PdfPageEvent提供了幾個pdf在創建時的事件,頁眉頁腳就是在每頁加載完寫入的。
每一頁加個頁碼還是很簡單的,但是總頁碼就麻煩了,iText是流模式的寫入內容,只有寫到最后,才能知道有多少頁,那么顯示總頁數就麻煩了,不過麻煩不代表不可能。
其實iText僅在調用釋放模板方法后才將PdfTemplate寫入到OutputStream中,否則對象將一直保存在內存中,直到關閉文檔。
所以我們可以在最后關閉文檔前,使用PdfTemplate寫入總頁碼。可以理解成先寫個占位符,然后統一替換。
 五、設置文檔屬性  (與文檔是否打開沒有關聯)
document.addTitle("Title@PDF-Java");// 標題
document.addAuthor("Author@umiz");// 作者
document.addSubject("Subject@iText pdf sample");// 主題
document.addKeywords("Keywords@iTextpdf");// 關鍵字
document.addCreator("Creator@umiz`s");// 創建者
 六、文檔內容
段落Paragraph
Paragraph pt=new Paragraph(name,headfont);//設置字體樣式
pt.setAlignment(1);//設置文字居中 0靠左   1,居中     2,靠右
pt.setIndentationLeft(12);// 左縮進  
pt.setIndentationRight(12);// 右縮進  
pt.setFirstLineIndent(24);// 首行縮進
paragraph.setLeading(20f); //行間距
paragraph.setSpacingBefore(5f); //設置段落上空白
paragraph.setSpacingAfter(10f); //設置段落下空白

表格table
PdfPTable table =new Table(3);//括號參數表示列
int width[] = {10,45,45};//設置每列寬度比例   
table.setWidths(width);   
table.setWidth(95);//占頁面寬度比例
table.setAlignment(Element.ALIGN_CENTER);//居中    
table.setAutoFillEmptyCells(true);//自動填滿       
table.setBorderWidth((float)0.1);//表格邊框線條寬度    
table.setPadding(1);//邊距:單元格的邊線與單元格內容的邊距  
table.setSpacing(0);//間距:單元格與單元格之間的距離
table.addCell(new Paragraph("name"),textfont));//添加單元格內容
table.endHeaders();//每頁都會顯示表頭

單元格內容樣式cell  
PdfPCell cell=new PdfPCell(new Paragraph("序號",keyfont));
cell.setHorizontalAlignment(Element.ALIGN_CENTER);//水平居中
cell.setVerticalAlignment(Element.ALIGN_MIDDLE); //垂直居中   
table.addCell(cell);

表格嵌套
  最外層表格
PdfPTable table =new PdfPTable(3);
table.setTotalWidth(300);
table.setLockedWidth(true);

PdfPCell cell;
cell =new PdfPCell(new Phrase("Table 5"));
cell.setColspan(3);
cell.setBorderWidth(0);//設置表格的邊框寬度為0
table.addCell(cell);

  嵌套表格
PdfPTable celltable =new PdfPTable(2);
cell =new PdfPCell(celltable);
cell.setRowspan(2);
cell.setBorderWidth(1);//設置表格的邊框寬度為1
cell.setPadding(10);//設置表格與上一個表格的填充為10
table.addCell(cell);

直線  
Paragraph p1 =new Paragraph();  
p1.add(new Chunk(new LineSeparator()));   
doc.add(p1);  

點線  
Paragraph p2 =new Paragraph();  
p2.add(new Chunk(new DottedLineSeparator()));

超鏈接
Anchor anchor =new Anchor("this is anchor");

定位
點擊后,跳到topline的位置
Anchor gotop =new Anchor("go top");
gotop.setReference("#us");

添加圖片
Image image =Image.getInstance(imgPath);
image.setAlignment(Image.ALIGN_CENTER);
image.scalePercent(40);//依照比例縮放
七、一個簡單的demo:

package com.soco.erp;
 
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;
import com.itextpdf.text.pdf.draw.DottedLineSeparator;
import com.itextpdf.text.pdf.draw.LineSeparator;
 
import java.io.File;
import java.io.FileOutputStream;
 
public class PdfReport {
 
    // main測試
    public static void main(String[] args) throws Exception {
        try {
            // 1.新建document對象
            Document document = new Document(PageSize.A4);// 建立一個Document對象
 
            // 2.建立一個書寫器(Writer)與document對象關聯
            File file = new File("D:\\PDFDemo.pdf");
            file.createNewFile();
            PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file));
            writer.setPageEvent(new Watermark("HELLO ITEXTPDF"));// 水印
            writer.setPageEvent(new MyHeaderFooter());// 頁眉/頁腳
 
            // 3.打開文檔
            document.open();
            document.addTitle("Title@PDF-Java");// 標題
            document.addAuthor("Author@umiz");// 作者
            document.addSubject("Subject@iText pdf sample");// 主題
            document.addKeywords("Keywords@iTextpdf");// 關鍵字
            document.addCreator("Creator@umiz`s");// 創建者
 
            // 4.向文檔中添加內容
            new PdfReport().generatePDF(document);
 
            // 5.關閉文檔
            document.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
 
    // 定義全局的字體靜態變量
    private static Font titlefont;
    private static Font headfont;
    private static Font keyfont;
    private static Font textfont;
    // 最大寬度
    private static int maxWidth = 520;
    // 靜態代碼塊
    static {
        try {
            // 不同字體(這里定義為同一種字體:包含不同字號、不同style)
            BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
            titlefont = new Font(bfChinese, 16, Font.BOLD);
            headfont = new Font(bfChinese, 14, Font.BOLD);
            keyfont = new Font(bfChinese, 10, Font.BOLD);
            textfont = new Font(bfChinese, 10, Font.NORMAL);
 
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
 
    // 生成PDF文件
    public void generatePDF(Document document) throws Exception {
 
        // 段落
        Paragraph paragraph = new Paragraph("美好的一天從早起開始!", titlefont);
        paragraph.setAlignment(1); //設置文字居中 0靠左   1,居中     2,靠右
        paragraph.setIndentationLeft(12); //設置左縮進
        paragraph.setIndentationRight(12); //設置右縮進
        paragraph.setFirstLineIndent(24); //設置首行縮進
        paragraph.setLeading(20f); //行間距
        paragraph.setSpacingBefore(5f); //設置段落上空白
        paragraph.setSpacingAfter(10f); //設置段落下空白
 
        // 直線
        Paragraph p1 = new Paragraph();
        p1.add(new Chunk(new LineSeparator()));
 
        // 點線
        Paragraph p2 = new Paragraph();
        p2.add(new Chunk(new DottedLineSeparator()));
 
        // 超鏈接
        Anchor anchor = new Anchor("baidu");
        anchor.setReference("www.baidu.com");
 
        // 定位
        Anchor gotoP = new Anchor("goto");
        gotoP.setReference("#top");
 
        // 添加圖片
        Image image = Image.getInstance("https://img-blog.csdn.net/20180801174617455?watermark/2/text/aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl8zNzg0ODcxMA==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70");
        image.setAlignment(Image.ALIGN_CENTER);
        image.scalePercent(40); //依照比例縮放
 
        // 表格
        PdfPTable table = createTable(new float[] { 40, 120, 120, 120, 80, 80 });
        table.addCell(createCell("美好的一天", headfont, Element.ALIGN_LEFT, 6, false));
        table.addCell(createCell("早上9:00", keyfont, Element.ALIGN_CENTER));
        table.addCell(createCell("中午11:00", keyfont, Element.ALIGN_CENTER));
        table.addCell(createCell("中午13:00", keyfont, Element.ALIGN_CENTER));
        table.addCell(createCell("下午15:00", keyfont, Element.ALIGN_CENTER));
        table.addCell(createCell("下午17:00", keyfont, Element.ALIGN_CENTER));
        table.addCell(createCell("晚上19:00", keyfont, Element.ALIGN_CENTER));
        Integer totalQuantity = 0;
        for (int i = 0; i < 5; i++) {
            table.addCell(createCell("起床", textfont));
            table.addCell(createCell("吃午飯", textfont));
            table.addCell(createCell("午休", textfont));
            table.addCell(createCell("下午茶", textfont));
            table.addCell(createCell("回家", textfont));
            table.addCell(createCell("吃晚飯", textfont));
            totalQuantity ++;
        }
        table.addCell(createCell("總計", keyfont));
        table.addCell(createCell("", textfont));
        table.addCell(createCell("", textfont));
        table.addCell(createCell("", textfont));
        table.addCell(createCell(String.valueOf(totalQuantity) + "件事", textfont));
        table.addCell(createCell("", textfont));
 
        document.add(paragraph);
        document.add(anchor);
        document.add(p2);
        document.add(gotoP);
        document.add(p1);
        document.add(table);
        document.add(image);
    }
 
 
/**------------------------創建表格單元格的方法start----------------------------*/
    /**
     * 創建單元格(指定字體)
     * @param value
     * @param font
     * @return
     */
    public PdfPCell createCell(String value, Font font) {
        PdfPCell cell = new PdfPCell();
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell.setPhrase(new Phrase(value, font));
        return cell;
    }
    /**
     * 創建單元格(指定字體、水平..)
     * @param value
     * @param font
     * @param align
     * @return
     */
    public PdfPCell createCell(String value, Font font, int align) {
        PdfPCell cell = new PdfPCell();
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell.setHorizontalAlignment(align);
        cell.setPhrase(new Phrase(value, font));
        return cell;
    }
    /**
     * 創建單元格(指定字體、水平居..、單元格跨x列合並)
     * @param value
     * @param font
     * @param align
     * @param colspan
     * @return
     */
    public PdfPCell createCell(String value, Font font, int align, int colspan) {
        PdfPCell cell = new PdfPCell();
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell.setHorizontalAlignment(align);
        cell.setColspan(colspan);
        cell.setPhrase(new Phrase(value, font));
        return cell;
    }
    /**
     * 創建單元格(指定字體、水平居..、單元格跨x列合並、設置單元格內邊距)
     * @param value
     * @param font
     * @param align
     * @param colspan
     * @param boderFlag
     * @return
     */
    public PdfPCell createCell(String value, Font font, int align, int colspan, boolean boderFlag) {
        PdfPCell cell = new PdfPCell();
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell.setHorizontalAlignment(align);
        cell.setColspan(colspan);
        cell.setPhrase(new Phrase(value, font));
        cell.setPadding(3.0f);
        if (!boderFlag) {
            cell.setBorder(0);
            cell.setPaddingTop(15.0f);
            cell.setPaddingBottom(8.0f);
        } else if (boderFlag) {
            cell.setBorder(0);
            cell.setPaddingTop(0.0f);
            cell.setPaddingBottom(15.0f);
        }
        return cell;
    }
    /**
     * 創建單元格(指定字體、水平..、邊框寬度:0表示無邊框、內邊距)
     * @param value
     * @param font
     * @param align
     * @param borderWidth
     * @param paddingSize
     * @param flag
     * @return
     */
    public PdfPCell createCell(String value, Font font, int align, float[] borderWidth, float[] paddingSize, boolean flag) {
        PdfPCell cell = new PdfPCell();
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell.setHorizontalAlignment(align);
        cell.setPhrase(new Phrase(value, font));
        cell.setBorderWidthLeft(borderWidth[0]);
        cell.setBorderWidthRight(borderWidth[1]);
        cell.setBorderWidthTop(borderWidth[2]);
        cell.setBorderWidthBottom(borderWidth[3]);
        cell.setPaddingTop(paddingSize[0]);
        cell.setPaddingBottom(paddingSize[1]);
        if (flag) {
            cell.setColspan(2);
        }
        return cell;
    }
/**------------------------創建表格單元格的方法end----------------------------*/
 
 
/**--------------------------創建表格的方法start------------------- ---------*/
    /**
     * 創建默認列寬,指定列數、水平(居中、右、左)的表格
     * @param colNumber
     * @param align
     * @return
     */
    public PdfPTable createTable(int colNumber, int align) {
        PdfPTable table = new PdfPTable(colNumber);
        try {
            table.setTotalWidth(maxWidth);
            table.setLockedWidth(true);
            table.setHorizontalAlignment(align);
            table.getDefaultCell().setBorder(1);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return table;
    }
    /**
     * 創建指定列寬、列數的表格
     * @param widths
     * @return
     */
    public PdfPTable createTable(float[] widths) {
        PdfPTable table = new PdfPTable(widths);
        try {
            table.setTotalWidth(maxWidth);
            table.setLockedWidth(true);
            table.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.getDefaultCell().setBorder(1);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return table;
    }
    /**
     * 創建空白的表格
     * @return
     */
    public PdfPTable createBlankTable() {
        PdfPTable table = new PdfPTable(1);
        table.getDefaultCell().setBorder(0);
        table.addCell(createCell("", keyfont));
        table.setSpacingAfter(20.0f);
        table.setSpacingBefore(20.0f);
        return table;
    }
/**--------------------------創建表格的方法end------------------- ---------*/
 
 
}

頁眉/頁腳的定義實現類:

package com.soco.erp;
 
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;
 
import java.io.IOException;
 
public class MyHeaderFooter extends PdfPageEventHelper {
    // 總頁數
    PdfTemplate totalPage;
    Font hfFont;
    {
        try {
            hfFont = new Font(BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED), 8, Font.NORMAL);
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
 
    // 打開文檔時,創建一個總頁數的模版
    public void onOpenDocument(PdfWriter writer, Document document) {
        PdfContentByte cb =writer.getDirectContent();
        totalPage = cb.createTemplate(30, 16);
    }
    // 一頁加載完成觸發,寫入頁眉和頁腳
    public void onEndPage(PdfWriter writer, Document document) {
        PdfPTable table = new PdfPTable(3);
        try {
            table.setTotalWidth(PageSize.A4.getWidth() - 100);
            table.setWidths(new int[] { 24, 24, 3});
            table.setLockedWidth(true);
            table.getDefaultCell().setFixedHeight(-10);
            table.getDefaultCell().setBorder(Rectangle.BOTTOM);
 
            table.addCell(new Paragraph("我是頁眉/頁腳", hfFont));// 可以直接使用addCell(str),不過不能指定字體,中文無法顯示
            table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_RIGHT);
            table.addCell(new Paragraph("第" + writer.getPageNumber() + "頁/", hfFont));
            // 總頁數
            PdfPCell cell = new PdfPCell(Image.getInstance(totalPage));
            cell.setBorder(Rectangle.BOTTOM);
            table.addCell(cell);
            // 將頁眉寫到document中,位置可以指定,指定到下面就是頁腳
            table.writeSelectedRows(0, -1, 50,PageSize.A4.getHeight() - 20, writer.getDirectContent());
        } catch (Exception de) {
            throw new ExceptionConverter(de);
        }
    }
 
    // 全部完成后,將總頁數的pdf模版寫到指定位置
    public void onCloseDocument(PdfWriter writer,Document document) {
        String text = "總" + (writer.getPageNumber()) + "頁";
        ColumnText.showTextAligned(totalPage, Element.ALIGN_LEFT, new Paragraph(text,hfFont), 2, 2, 0);
    }
 
}

加水印的實現類:

package com.soco.erp;
 
import com.itextpdf.text.Document;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.pdf.ColumnText;
import com.itextpdf.text.pdf.GrayColor;
import com.itextpdf.text.pdf.PdfPageEventHelper;
import com.itextpdf.text.pdf.PdfWriter;
 
public class Watermark extends PdfPageEventHelper {
    Font FONT = new Font(Font.FontFamily.HELVETICA, 30, Font.BOLD, new GrayColor(0.95f));
    private String waterCont;//水印內容
    public Watermark() {
 
    }
    public Watermark(String waterCont) {
        this.waterCont = waterCont;
    }
 
    @Override
    public void onEndPage(PdfWriter writer, Document document) {
        for(int i=0 ; i<5; i++) {
            for(int j=0; j<5; j++) {
                ColumnText.showTextAligned(writer.getDirectContentUnder(),
                        Element.ALIGN_CENTER,
                        new Phrase(this.waterCont == null ? "HELLO WORLD" : this.waterCont, FONT),
                        (50.5f+i*350),
                        (40.0f+j*150),
                        writer.getPageNumber() % 2 == 1 ? 45 : -45);
            }
        }
    }
}

八、生成pdf截圖:

 

 

PdfP


免責聲明!

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



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