在日常開發過程中,若是想要把java中的某個對象中的內容,按某種排列方式輸出到PDF中,有幾種方式,此處只使用了itextpdf的方式。
itext pdf 文檔
一、加入依賴
在gradle中只需要加入
compile group: 'com.itextpdf', name: 'itextpdf', version: '5.5.6'
二、創建一個Document,并加入內容
public void createPdf() {
Document document = new Document();
try {
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("HelloWorld.pdf"));
document.open();
document.add(new Paragraph("Some content here"));
settings(document);
style(document);
document.close();
writer.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (DocumentException e) {
e.printStackTrace();
}
}
新建一個Document對象,再定義PdfWriter,把document中的內容寫入HelloWorld.pdf文件。
在添加內容到document之前需要執行document.open()才可以。
document可以添加Paragraph、PdfPTable等元素。
三、踩過的坑
- 問題:使用PdfPTable來構造整體結構時,如何設置行間距?
解決方案:在給cell中添加內容的時候有兩種方式,一種是直接初始化的時候添加,另一種是調用addElement方法添加內容。
PdfPCell cell = new PdfPCell(new Paragraph(100,"Table 1"));
PdfPCell cell= new PdfPCell();
cell.addElement(new Paragraph(100,"Table 1"));
這兩種方法中第一種不支持設置Leading為100,第二種方法支持設置Leading為100。除了在初始化Paragraph時可以設置Leading,還可以調用setLeading()來設置,第一個參數是固定的行間距,第二個參數是行間距為行高的倍數。
Paragraph element = new Paragraph("Some content here");
element.setLeading(0,2);
- 問題:如何給PdfPTable設置每列的寬度?
解決方案:設置table的列寬時,需要把所有列的寬度放進數組列表中,缺一不可,如果數組的大小和table的列數不匹配則整體都不會顯示出來。
PdfPTable table = new PdfPTable(3);
table.setWidths(new int[]{2, 1, 1});
- 問題:如何設置邊框?
解決方案:邊框的值不一樣,當setBorder()函數的參數為0時,沒有邊框,1為上邊框TOP,2為下邊框BOTTOM,4為左邊框LEFT,8為右邊框RIGHT。具體的可以調用Rectangle中的固定值。
PdfPCell cell = new PdfPCell(new Phrase("StackOverflow"));
cell.setBorder(Rectangle.NO_BORDER);