SpringBoot导出pdf文件

1、引入依赖包


			com.itextpdf
			itextpdf
			5.5.12
		

2、编写创建pdf的方法 (解释都在代码中进行注解)

//pdf创建表格
    public static PdfPTable createTable(PdfWriter writer) throws DocumentException, IOException{
        PdfPTable table = new PdfPTable(2);//生成一个两列的表格
        PdfPCell cell;
        //有中文文字的话需要设置字体
        Font font = new Font(BaseFont.createFont("C:/Windows/Fonts/SIMYOU.TTF",BaseFont.IDENTITY_H,BaseFont.NOT_EMBEDDED));
        int size = 30;
        cell = new PdfPCell(new Phrase("你好,再见",font));
        cell.setFixedHeight(size);//设置高度
        table.addCell(cell);
        cell = new PdfPCell(new Phrase("two"));
        cell.setFixedHeight(size);
        table.addCell(cell);
        cell = new PdfPCell(new Phrase("three"));
        cell.setFixedHeight(size);
        table.addCell(cell);
        cell = new PdfPCell(new Phrase("four"));
        cell.setFixedHeight(size);
        table.addCell(cell);
        //合并单元格
        cell = new PdfPCell(new Phrase("five"));
        cell.setColspan(1);//设置所占列数
        cell.setRowspan(2);//设置所占行数
        cell.setFixedHeight(size*2);//设置高度为标准高度的两倍
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);//设置水平居中
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);//设置垂直居中
        table.addCell(cell);
        cell = new PdfPCell(new Phrase("six"));
        cell.setFixedHeight(size);
        table.addCell(cell);
        cell = new PdfPCell(new Phrase("seven"));
        cell.setFixedHeight(size);
        table.addCell(cell);

        Phrase phrase1 = new Phrase();
        Chunk chunk1 = new Chunk("         YES");
        Chunk chunk2 = new Chunk("          NO");
        phrase1.add(chunk1);
        phrase1.add(chunk2);
        cell = new PdfPCell(phrase1);
        cell.setColspan(2);
        table.addCell(cell);

        return table;
    }

    //创建pdf文件
    public void createPDF(String filename) throws IOException {
        Document document = new Document(PageSize.A4);
        try {
            PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(filename));
            document.addTitle("example of PDF");
            document.open();
            //document.add(new Paragraph("Hello World!"));
            PdfPTable table = this.createTable(writer);
            document.add(table);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (DocumentException e) {
            e.printStackTrace();
        } finally {
            document.close();
        }
    }

3、在主类中调用createPDF创建pdf文件

public static void main(String[] args){
        //测试生成pdf
        try{
            TestPDF testPDF = new TestPDF();
            testPDF.createPDF("D://hellowworld.pdf");
        }catch (Exception e){
            e.printStackTrace();
        }
    }

4、测试pdf生成效果 

SpringBoot导出pdf文件_第1张图片

 

 

你可能感兴趣的:(itext,java)