Java PDF中table的生成和使用

下列例子基于itextpdf-5.5.13.jar

為以下問(wèn)題提供了解決方法:

Unit1:
  1. 如何生成帶一個(gè)表格的PDF?
  2. 如何生成帶多個(gè)表格的PDF讶踪?
Unit2:
  1. 如何生成帶簡(jiǎn)單表格(多行多列)的PDF颂砸?
  2. 如何生成帶復(fù)雜表格(跨列/跨行)的PDF笼恰?
Unit3:
  1. 如何使用內(nèi)部字體文件洛心?
  2. 如何使用外部字體文件缴守?
Unit1-1:如何生成帶一個(gè)表格的PDF葬毫?
SimpleTable.png

import java.io.File;
import java.io.FileOutputStream;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;

public class SimpleTable {
    public static final String DEST = "results/tables/simple_table1.pdf";

    public static void main(String[] args) throws DocumentException, Exception {
        File file = new File(DEST);
        file.getParentFile().mkdirs();
        SimpleTable.createPDF(DEST);
    }

    public static void createPDF(String dest) throws Exception, DocumentException {
        Document document = new Document();
        PdfWriter.getInstance(document, new FileOutputStream(dest));
        document.open();
        
        //生成一個(gè)2行4列的表格,各列的寬度比為1:2:1:2
        PdfPTable table = new PdfPTable(4);
        table.setWidths(new int[] { 1, 2, 1, 2 });
        table.addCell("1line A");
        table.addCell("1line B");
        table.addCell("1line C");
        table.addCell("1line D");

        table.addCell("2line A");
        table.addCell("2line B");
        table.addCell("2line C");
        table.addCell("2line D");
        document.add(table);
        document.close();
        System.out.println(DEST + "生成成功");
    }

}
Unit1-2:如何生成帶多個(gè)表格的PDF屡穗?
SimpleTable2.png

1. 在創(chuàng)建第二個(gè)table之前贴捡,新加 document.add(new Phrase("\n"));
2. 開(kāi)始創(chuàng)建新的table:table=new PdfTable(colnum);

import java.io.File;
import java.io.FileOutputStream;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;

public class SimpleTable {
    public static final String DEST = "results/tables/simple_table2.pdf";

    public static void main(String[] args) throws DocumentException, Exception {
        File file = new File(DEST);
        file.getParentFile().mkdirs();
        SimpleTable.createPDF(DEST);
    }

    public static void createPDF(String dest) throws Exception, DocumentException {
        Document document = new Document();
        PdfWriter.getInstance(document, new FileOutputStream(dest));
        document.open();

        // 生成一個(gè)2行4列的表格村砂,4列的長(zhǎng)度比為1:2:1:2
        PdfPTable table = new PdfPTable(4);
        table.setWidths(new int[] { 1, 2, 1, 2 });
        table.addCell("1line A");
        table.addCell("1line B");
        table.addCell("1line C");
        table.addCell("1line D");

        table.addCell("2line A");
        table.addCell("2line B");
        table.addCell("2line C");
        table.addCell("2line D");
        document.add(table);

        // 用換行符進(jìn)行表格分割
        document.add(new Phrase("\n"));

        // 創(chuàng)建第二個(gè)表格
        table = new PdfPTable(4);
        // 下列代碼與建立第一個(gè)表格的代碼重復(fù)
        table.setWidths(new int[] { 1, 2, 1, 2 });
        table.addCell("1line A");
        table.addCell("1line B");
        table.addCell("1line C");
        table.addCell("1line D");

        table.addCell("2line A");
        table.addCell("2line B");
        table.addCell("2line C");
        table.addCell("2line D");
        document.add(table);

        document.close();
        System.out.println(DEST + "生成成功");

    }

}
Unit2-1:如何生成帶簡(jiǎn)單表格(多行多列)PDF烂斋?

該問(wèn)題與Unit1-1相似,不同的是考慮了存在列表數(shù)據(jù)比較多的情況,用了linkedHashMap進(jìn)行存值汛骂。

table1.png

import java.io.File;
import java.io.FileOutputStream;
import java.util.LinkedHashMap;
import java.util.Map;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;

public class LinkedHashMapTable {
    public static final String DEST = "results/tables/table.pdf";

    public static void main(String[] args) throws DocumentException, Exception {
        File file = new File(DEST);
        file.getParentFile().mkdirs();
        LinkedHashMapTable.createPDF(DEST);
    }

    public static void createPDF(String dest) throws Exception, DocumentException {
        Document document = new Document();
        PdfWriter.getInstance(document, new FileOutputStream(dest));
        document.open();

        PdfPTable table = new PdfPTable(4);
        table.setWidths(new int[] { 1, 2, 1, 2 });
        // 通過(guò)有序的LinkedHashMap進(jìn)行key-value存值
        Map<String, String> map = new LinkedHashMap<String, String>();
        map.put("1Line A", "1Line B");
        map.put("1Line C", "1Line D");
        map.put("2Line A", "2Line B");
        map.put("2Line C", "2Line D");
        // 通過(guò)Map.entrySet遍歷key和value
        for (Map.Entry<String, String> entry : map.entrySet()) {
            table.addCell(entry.getKey());
            table.addCell(entry.getValue());
        }

        document.add(table);
        document.close();

        System.out.println(DEST + "生成成功");

    }
}
Unit2-2:如何生成帶復(fù)雜表格(多行多列)PDF罕模?
row_col.png
import java.io.File;
import java.io.FileOutputStream;
import java.util.LinkedHashMap;
import java.util.Map;

import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Font;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;

public class RowColspan {
    public static final String DEST = "results/tables/rowspan_colspan11.pdf";
    public static final String FONT = "C:/Windows/Fonts/msyh.ttc,0";

    public static void main(String[] args) throws DocumentException, Exception {
        File file = new File(DEST);
        file.getParentFile().mkdirs();
        RowColspan.createPDF(DEST);
    }

    public static void createPDF(String dest) throws DocumentException, Exception {
        Document document = new Document();
        PdfWriter.getInstance(document, new FileOutputStream(dest));
        document.open();
        BaseFont unicode = BaseFont.createFont(FONT, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
        Font font = new Font(unicode, 12, Font.NORMAL, new BaseColor(50, 205, 50));
        PdfPTable table = new PdfPTable(4);
        table.setWidths(new int[] { 1, 2, 1, 2 });
        PdfPCell cell;
        cell = new PdfPCell(new Phrase("基本信息", font));
        // 跨四列,由四列變成一列
        cell.setColspan(4);
        table.addCell(cell);

        // 由四列變成兩列
        cell = new PdfPCell(new Phrase("A"));
        table.addCell(cell);
        cell = new PdfPCell(new Phrase("B"));
        cell.setColspan(3);
        table.addCell(cell);

        // 為了使代碼簡(jiǎn)潔帘瞭,接下來(lái)的存值進(jìn)行遍歷
        Map<String, String> map = new LinkedHashMap<String, String>();
        map.put("C", "D");
        map.put("E", "F");
        map.put("G", "H");
        map.put("I", "J");
        map.put("K", "L");
        for (Map.Entry<String, String> entry : map.entrySet()) {
            cell = new PdfPCell(new Phrase(entry.getKey()));
            table.addCell(cell);
            cell = new PdfPCell(new Phrase(entry.getValue()));
            cell.setColspan(3);
            table.addCell(cell);
        }

        // 正常四列
        table.addCell(new Phrase("第一列", font));
        table.addCell(new Phrase("第二列", font));
        table.addCell(new Phrase("第三列", font));
        table.addCell(new Phrase("第四列", font));

        document.add(table);
        document.close();
        System.out.println(DEST + "生成成功淑掌!");

    }
}
Unit3-1:如何使用內(nèi)部字體文件?

如要使用系統(tǒng)自帶的微軟雅黑字體蝶念,
首先抛腕,在類中增加靜態(tài)常量:
public static final String FONT = "C:/Windows/Fonts/msyh.ttc,0";
接著,在方法體里(例如createPDF(String dest){ })添加:

BaseFont unicode = BaseFont.createFont(FONT, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
        Font font = new Font(unicode, 12, Font.NORMAL, new BaseColor(50, 205, 50));

最后媒殉,將設(shè)置后的font格式應(yīng)用到輸入值("第一列")上
new Phrase("第一列", font)

Unit3-2:如何使用外部字體文件担敌?

若要使用從網(wǎng)絡(luò)上下載的字體(如:vista.ttf)
只需把public static final String FONT = "C:/Windows/Fonts/msyh.ttc,0";
改成public static final String FONT = "results/font/vista.ttf";
即可。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末廷蓉,一起剝皮案震驚了整個(gè)濱河市全封,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌桃犬,老刑警劉巖刹悴,帶你破解...
    沈念sama閱讀 218,546評(píng)論 6 507
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異疫萤,居然都是意外死亡颂跨,警方通過(guò)查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,224評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門(mén)扯饶,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)恒削,“玉大人,你說(shuō)我怎么就攤上這事尾序〉龇幔” “怎么了?”我有些...
    開(kāi)封第一講書(shū)人閱讀 164,911評(píng)論 0 354
  • 文/不壞的土叔 我叫張陵每币,是天一觀的道長(zhǎng)携丁。 經(jīng)常有香客問(wèn)我,道長(zhǎng)兰怠,這世上最難降的妖魔是什么梦鉴? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 58,737評(píng)論 1 294
  • 正文 為了忘掉前任,我火速辦了婚禮揭保,結(jié)果婚禮上肥橙,老公的妹妹穿的比我還像新娘。我一直安慰自己秸侣,他們只是感情好存筏,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,753評(píng)論 6 392
  • 文/花漫 我一把揭開(kāi)白布宠互。 她就那樣靜靜地躺著,像睡著了一般椭坚。 火紅的嫁衣襯著肌膚如雪予跌。 梳的紋絲不亂的頭發(fā)上,一...
    開(kāi)封第一講書(shū)人閱讀 51,598評(píng)論 1 305
  • 那天善茎,我揣著相機(jī)與錄音券册,去河邊找鬼。 笑死垂涯,一個(gè)胖子當(dāng)著我的面吹牛汁掠,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播集币,決...
    沈念sama閱讀 40,338評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼翠忠!你這毒婦竟也來(lái)了鞠苟?” 一聲冷哼從身側(cè)響起,我...
    開(kāi)封第一講書(shū)人閱讀 39,249評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤秽之,失蹤者是張志新(化名)和其女友劉穎当娱,沒(méi)想到半個(gè)月后,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體考榨,經(jīng)...
    沈念sama閱讀 45,696評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡跨细,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,888評(píng)論 3 336
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了河质。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片冀惭。...
    茶點(diǎn)故事閱讀 40,013評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖掀鹅,靈堂內(nèi)的尸體忽然破棺而出散休,到底是詐尸還是另有隱情,我是刑警寧澤乐尊,帶...
    沈念sama閱讀 35,731評(píng)論 5 346
  • 正文 年R本政府宣布戚丸,位于F島的核電站,受9級(jí)特大地震影響扔嵌,放射性物質(zhì)發(fā)生泄漏限府。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,348評(píng)論 3 330
  • 文/蒙蒙 一痢缎、第九天 我趴在偏房一處隱蔽的房頂上張望胁勺。 院中可真熱鬧,春花似錦牺弄、人聲如沸姻几。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 31,929評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)蛇捌。三九已至抚恒,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間络拌,已是汗流浹背俭驮。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 33,048評(píng)論 1 270
  • 我被黑心中介騙來(lái)泰國(guó)打工, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留春贸,地道東北人混萝。 一個(gè)月前我還...
    沈念sama閱讀 48,203評(píng)論 3 370
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像萍恕,于是被迫代替她去往敵國(guó)和親逸嘀。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,960評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容