關於java poi itext生成pdf文件的例子以及方法


最近正在做導出pdf文件的功能,所以查了了一些相關資料,發現不是很完善,這里做一些小小的感想,歡迎各位“猿”童鞋批評指正。

poi+itext,所需要的jar包有itext-2.1.7.jar,poi-3.14.jar,iTextAsian.jar:用於處理中文亂碼問題,這是我所用的jar包,大家也可以自行配置。https://www.cnblogs.com/h--d/p/6150320.html,這個網址步驟寫的挺好的,https://www.cnblogs.com/shuilangyizu/p/5760928.html 這個是畫pdf比較詳細

首先設置一下字體,看看pdf里有哪些需要的字體,這里先設置一個基礎的

   BaseFont bfChinese = null;
try {
bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
} catch (DocumentException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();

}

Font FontChinese = new Font(bfChinese,13,Font.NORMAL);

Font FontChinese2 = new Font(bfChinese,13,Font.NORMAL|Font.UNDERLINE);這里設置需要的的字體類型,在初始的字體里面修改,保證一下統一以便字體結構清晰。

// 第一步,創建document對象
Rectangle rectPageSize = new Rectangle(PageSize.A4);//這里可以查查,有很多其他的
//下面代碼設置頁面橫置

rectPageSize = rectPageSize.rotate();

//創建document對象並指定邊距

Document document1 = new Document(rectPageSize);

// 將Document實例和文件輸出流用PdfWriter類綁定在一起,從而完成向Document寫,即寫入PDF文檔

PdfWriter.getInstance(document1,new FileOutputStream("src/a.pdf"));//創建到哪個路徑文件中
//打開文檔
document1.open();

//向文檔添加文字. 文檔由段組成,這里只是做個別的說明

float[] widths = {40,80,150,50,50,100,60,50,70,70};數據存的是列寬,按照配比來的,不用在乎數據大小

PdfPTable table = new PdfPTable(widths);這個可以在頁面畫一個table,很方便並且比較好的方法

table.setWidthPercentage(100);設置占比
table.setSpacingBefore(10);設置上邊距離上個Paragraph的距離

table.setSpacingAfter(10);設置下邊距離下個Paragraph的距離

下面這個可以設置表格中同單元格存在不同的字體

Paragraph largeText = new Paragraph();
Chunk chunk1 = new Chunk("text0",FontChinese11);
Chunk chunk2 = new Chunk(text1,FontChinese1);
largeText.add(chunk1);
largeText.add(chunk2);

cell1.addElement(largeText);

document1.add(list+Paragraph+table等等之類的);

//關閉document
document1.close();


免責聲明!

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



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