SpirngBoot实现PDF文件生成

6 篇文章 0 订阅
本文详细介绍了如何利用iTextPDF Java库来创建PDF文件,包括引入依赖、编写工具类PDFUtils,以及如何自定义保存路径。示例代码展示了如何生成表格并设置内容,如标题、内容和边框样式,适用于数据报告或文档自动化生成。
摘要由CSDN通过智能技术生成

一、用itextpdf实现

1.引入依赖

<!--生成pdf-->
<dependency>
	<groupId>com.itextpdf</groupId>
    <artifactId>itextpdf</artifactId>
    <version>5.5.10</version>
</dependency>
<dependency>
    <groupId>com.itextpdf</groupId>
    <artifactId>itext-asian</artifactId>
    <version>5.2.0</version>
</dependency>

2.编写工具类PDFUtils.java将数据制作成PDF

2.1 先指定想要将文件存放的位置

private final static String REPORT_PATH = "E:\\pdf\\;

2.2 申明方法,此处方法的参数是需要生成PDF文件的数据,返回文件的路径

public String createPDF(T data){
    String filename = REPORT_PATH+"\\"+data.getFileName()+".pdf";
    return filePath;
}

2.3 实例化文件对象,此处可配置想要导出的文件的大小

Document document = new Document(new RectangleReadOnly(595F,420F));//横向A5

595F和420F刚好对应的是A5的长和宽,可以根据自己的实际需求进行设置

常量的大小可以进入com.itextpdf.text.PageSize的源码进行查看

2.4 实例化一个PdfWriter,打开文件准备生成内容

PdfWriter.getInstance(document,new FileOutputStream(filename));
document.addTitle("example of PDF");
document.open();

2.5 生成的内容会自上而下自动排列,也可自己设置。本案例中是添加表格,且每一页最多显示8行数据,故如此设计。

int page = 0;//页数
if(data.getList().size()%8==0){
	page = data.getList().size()/8;
}else {
    page = data.getList().size()/8+1;
}

2.6 开始制作内容(用表格进行设计)

PdfPTable table = new PdfPTable(24);//生成一个24列的表格
table.setWidthPercentage (100);//设置表格宽度,100表示占整行的100%,可根据实际情况调整
PdfPCell cell;//单元格
int size = 20;//声明一个大小,后续设置行高或其他的时候可以使用,方便统一管理
BaseFont baseFont = BaseFont.createFont("C:/Windows/Fonts/SIMYOU.TTF", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);//字体,默认系统字体
//BaseFont baseFont = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
Font font15 = new Font(baseFont,15, Font.BOLD);//新建一个15号大小、加粗字体
Font font12 = new Font(baseFont,12);//新建一个12号大小、不加粗字体
Font font10 = new Font(baseFont,10);
Font font10b = new Font(baseFont, 10,Font.BOLD);
Font font8 = new Font(baseFont,8);
Font font8b = new Font(baseFont,8,Font.BOLD);
Font font6 = new Font(baseFont,6);

//一般的排版分为三部分:顶部标题,中间内容,底部结尾信息
//标题部分:
cell = new PdfPCell(new Phrase("标题",font15));
cell.setColspan(24);//之前新建的表格一共24列,设置标题占据全部24列
cell.setFixedHeight(size*1.5f);//设置标题的高度
cell.setHorizontalAlignment(Element.ALIGN_CENTER);//水平居中
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);//垂直居中
cell.disableBorderSide(15);//隐藏边框
table.addCell(cell);//将单元格加入表格中
//内容部分:按照实际情况进行编写即可
//底部信息:一般会是公司名称,电话,邮箱,网址等

2.7 若中间需要空行

cell = new PdfPCell(new Phrase("",font10));
cell.setColspan(24);
cell.setFixedHeight(size);
cell.setLeading(0,1);
cell.disableBorderSide(15);//隐藏边框
table.addCell(cell);

2.8 关于表格需要隐藏边框

//新建单元格对象
PdfPCell cell = new PdfPCell(new Phrase(“test”));
//隐藏上边框
// cell.disableBorderSide(1);
//隐藏下边框
// cell.disableBorderSide(2);
//隐藏上、下边框
//cell.disableBorderSide(3);
//隐藏左边框
//cell.disableBorderSide(4);
//隐藏左、上边框
//cell.disableBorderSide(5);
//隐藏左、下边框
//cell.disableBorderSide(6);
//隐藏左、上、下边框
//cell.disableBorderSide(7);
//隐藏右边框
//cell.disableBorderSide(8);
//隐藏右、上边框
// cell.disableBorderSide(9);
//隐藏右、下边框
//cell.disableBorderSide(10);
//隐藏右、上、下边框
//cell.disableBorderSide(11);
//隐藏左、右边框
//cell.disableBorderSide(12);//左右没了
//隐藏上、左、右边框
//cell.disableBorderSide(13);//只剩下
//隐藏下、左、右边框
//cell.disableBorderSide(14);//只剩上
//隐藏全部
//cell.disableBorderSide(15);//全没了

1代表上边框 2代表下边框 4代表左边框 8代表右边框。需要隐藏那些边框就把对应的值加起来,得到的和就是要设置的值。比如要隐藏左右边框,就是 4+8=12
cell.disableBorderSide(12);//左右没了

2.9 完整代码

package com.xxx.utils;

import com.xxx.vo.T;
import com.xxx.vo.V;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;

/**
 * @Author: 如果这段代码能正常工作,请记住作者是:alvis
 * 如果不能正常工作,那我也不知道是谁写的
 * @Date: Created in 17:24 2022/2/24
 * @Description:
 */

public class PDFUtils {

    private final static String REPORT_PATH = "E:\\pdfs";

    /**
     * 根据传入的出库数据生成出库单PDF文件
     * 返回文件存放的路径
     * @param data
     */
    public String createStokoutOrderPDF(T data){
        String filename = REPORT_PATH+"\\"+data.getOrderId()+".pdf";
        Document document = new Document(new RectangleReadOnly(595F,420F));//横向A5

        try {
            PdfWriter.getInstance(document,new FileOutputStream(filename));
            document.addTitle("example of PDF");
            document.open();
            int page = 0;//出库单的页数
            if(data.getList().size()%8==0){
                page = data.getList().size()/8;
            }else {
                page = data.getList().size()/8+1;
            }
            //开始制作内容
            PdfPTable table = new PdfPTable(24);//生成一个24列的表格
            for (int curPage = 1; curPage <= page; curPage++) {
                table.setWidthPercentage (100);//设置表格宽度
                PdfPCell cell;
                int size = 20;
                BaseFont baseFont = BaseFont.createFont("C:/Windows/Fonts/SIMYOU.TTF", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
                Font font15 = new Font(baseFont,15, Font.BOLD);
                Font font12 = new Font(baseFont,12);
                Font font10 = new Font(baseFont,10);
                Font font10b = new Font(baseFont, 10,Font.BOLD);
                Font font8 = new Font(baseFont,8);
                Font font8b = new Font(baseFont,8,Font.BOLD);
                Font font6 = new Font(baseFont,6);
                //抬头
                cell = new PdfPCell(new Phrase("仓储系统出库单",font15));
                cell.setColspan(24);
                cell.setFixedHeight(size*1.5f);
                cell.setHorizontalAlignment(Element.ALIGN_CENTER);//水平居中
                cell.setVerticalAlignment(Element.ALIGN_MIDDLE);//垂直居中
                cell.disableBorderSide(15);//隐藏边框
                table.addCell(cell);
                //出库单号
                cell = new PdfPCell(new Phrase("出库单号:"+data.getOrderId(),font10b));
                cell.setColspan(24);
                cell.setFixedHeight(size*1.5f);
                cell.setHorizontalAlignment(Element.ALIGN_RIGHT);//水平靠右
                cell.setVerticalAlignment(Element.ALIGN_MIDDLE);//垂直居中
                cell.disableBorderSide(15);//隐藏边框
                table.addCell(cell);
                //申请和审核信息
                cell = new PdfPCell(new Phrase("申请人",font10b));
                cell.setColspan(2);
                cell.setFixedHeight(size);
                cell.setHorizontalAlignment(Element.ALIGN_CENTER);//居中
                cell.setVerticalAlignment(Element.ALIGN_MIDDLE);//垂直居中
                table.addCell(cell);
                cell = new PdfPCell(new Phrase(data.getApplyEmpName(),font10));
                cell.setColspan(3);
                cell.setFixedHeight(size);
                cell.setHorizontalAlignment(Element.ALIGN_CENTER);//居中
                cell.setVerticalAlignment(Element.ALIGN_MIDDLE);//垂直居中
                table.addCell(cell);
                cell = new PdfPCell(new Phrase("申请时间",font10b));
                cell.setColspan(3);
                cell.setFixedHeight(size);
                cell.setHorizontalAlignment(Element.ALIGN_CENTER);//居中
                cell.setVerticalAlignment(Element.ALIGN_MIDDLE);//垂直居中
                table.addCell(cell);
                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                cell = new PdfPCell(new Phrase(df.format(data.getCreateDate()),font10));
                cell.setColspan(4);
                cell.setFixedHeight(size);
                cell.setHorizontalAlignment(Element.ALIGN_CENTER);//居中
                cell.setVerticalAlignment(Element.ALIGN_MIDDLE);//垂直居中
                table.addCell(cell);
                cell = new PdfPCell(new Phrase("审核人",font10b));
                cell.setColspan(2);
                cell.setFixedHeight(size);
                cell.setHorizontalAlignment(Element.ALIGN_CENTER);//居中
                cell.setVerticalAlignment(Element.ALIGN_MIDDLE);//垂直居中
                table.addCell(cell);
                cell = new PdfPCell(new Phrase(data.getAuditEmpName(),font10));
                cell.setColspan(3);
                cell.setFixedHeight(size);
                cell.setHorizontalAlignment(Element.ALIGN_CENTER);//居中
                cell.setVerticalAlignment(Element.ALIGN_MIDDLE);//垂直居中
                table.addCell(cell);
                cell = new PdfPCell(new Phrase("审核时间",font10b));
                cell.setColspan(3);
                cell.setFixedHeight(size);
                cell.setHorizontalAlignment(Element.ALIGN_CENTER);//居中
                cell.setVerticalAlignment(Element.ALIGN_MIDDLE);//垂直居中
                table.addCell(cell);
                cell = new PdfPCell(new Phrase(df.format(data.getAuditDate()),font10));
                cell.setColspan(4);
                cell.setFixedHeight(size);
                cell.setHorizontalAlignment(Element.ALIGN_CENTER);//居中
                cell.setVerticalAlignment(Element.ALIGN_MIDDLE);//垂直居中
                table.addCell(cell);
                //空一行
                cell = new PdfPCell(new Phrase("",font6));
                cell.setColspan(24);
                cell.setFixedHeight(size*0.5f);
                cell.setHorizontalAlignment(Element.ALIGN_CENTER);//居中
                cell.setVerticalAlignment(Element.ALIGN_MIDDLE);//垂直居中
                cell.disableBorderSide(15);//隐藏边框
                table.addCell(cell);
                //库存品出库信息
                //******************属性名
                cell = new PdfPCell(new Phrase("序号",font10b));
                cell.setColspan(2);
                cell.setFixedHeight(size);
                cell.setHorizontalAlignment(Element.ALIGN_CENTER);//水平居中
                cell.setVerticalAlignment(Element.ALIGN_MIDDLE);//垂直居中
                table.addCell(cell);
                cell = new PdfPCell(new Phrase("出库品名称",font10b));
                cell.setColspan(4);
                cell.setFixedHeight(size);
                cell.setHorizontalAlignment(Element.ALIGN_CENTER);//水平居中
                cell.setVerticalAlignment(Element.ALIGN_MIDDLE);//垂直居中
                table.addCell(cell);
                cell = new PdfPCell(new Phrase("型号",font10b));
                cell.setColspan(4);
                cell.setFixedHeight(size);
                cell.setHorizontalAlignment(Element.ALIGN_CENTER);//水平居中
                cell.setVerticalAlignment(Element.ALIGN_MIDDLE);//垂直居中
                table.addCell(cell);
                cell = new PdfPCell(new Phrase("单位",font10b));
                cell.setColspan(3);
                cell.setFixedHeight(size);
                cell.setHorizontalAlignment(Element.ALIGN_CENTER);//水平居中
                cell.setVerticalAlignment(Element.ALIGN_MIDDLE);//垂直居中
                table.addCell(cell);
                cell = new PdfPCell(new Phrase("出库数量",font10b));
                cell.setColspan(4);
                cell.setFixedHeight(size);
                cell.setHorizontalAlignment(Element.ALIGN_CENTER);//水平居中
                cell.setVerticalAlignment(Element.ALIGN_MIDDLE);//垂直居中
                table.addCell(cell);
                cell = new PdfPCell(new Phrase("仓库位置",font10b));
                cell.setColspan(4);
                cell.setFixedHeight(size);
                cell.setHorizontalAlignment(Element.ALIGN_CENTER);//水平居中
                cell.setVerticalAlignment(Element.ALIGN_MIDDLE);//垂直居中
                table.addCell(cell);
                cell = new PdfPCell(new Phrase("备注",font10b));
                cell.setColspan(3);
                cell.setFixedHeight(size);
                cell.setHorizontalAlignment(Element.ALIGN_CENTER);//水平居中
                cell.setVerticalAlignment(Element.ALIGN_MIDDLE);//垂直居中
                table.addCell(cell);
                //******************属性值
                int num=0;
                if (curPage<page){
                    num=8;
                }else{
                    num=data.getList().size()-8*(page-1);
                }
                for (int i = 1; i <= num; i++) {
                    V res = data.getList().get(i-1);
                    //序号2
                    int no = 8*(curPage-1)+i;
                    cell = new PdfPCell(new Phrase(String.valueOf(no),font10));
                    cell.setColspan(2);
                    cell.setFixedHeight(size);
                    cell.setHorizontalAlignment(Element.ALIGN_CENTER);//水平居中
                    cell.setVerticalAlignment(Element.ALIGN_MIDDLE);//垂直居中
                    table.addCell(cell);
                    //出库品名称4
                    cell = new PdfPCell(new Phrase(res.getGoodsName(),font10));
                    cell.setColspan(4);
                    cell.setFixedHeight(size);
                    cell.setHorizontalAlignment(Element.ALIGN_CENTER);//水平居中
                    cell.setVerticalAlignment(Element.ALIGN_MIDDLE);//垂直居中
                    table.addCell(cell);
                    //型号4
                    cell = new PdfPCell(new Phrase(res.getGoodsModel(),font10));
                    cell.setColspan(4);
                    cell.setFixedHeight(size);
                    cell.setHorizontalAlignment(Element.ALIGN_CENTER);//水平居中
                    cell.setVerticalAlignment(Element.ALIGN_MIDDLE);//垂直居中
                    table.addCell(cell);
                    //单位3
                    cell = new PdfPCell(new Phrase(res.getUnit(),font10));
                    cell.setColspan(3);
                    cell.setFixedHeight(size);
                    cell.setHorizontalAlignment(Element.ALIGN_CENTER);//水平居中
                    cell.setVerticalAlignment(Element.ALIGN_MIDDLE);//垂直居中
                    table.addCell(cell);
                    //出库数量4
                    cell = new PdfPCell(new Phrase(String.valueOf(res.getAmount()),font10));
                    cell.setColspan(4);
                    cell.setFixedHeight(size);
                    cell.setHorizontalAlignment(Element.ALIGN_CENTER);//水平居中
                    cell.setVerticalAlignment(Element.ALIGN_MIDDLE);//垂直居中
                    table.addCell(cell);
                    //仓库位置4
                    cell = new PdfPCell(new Phrase(res.getStorName(),font10));
                    cell.setColspan(4);
                    cell.setFixedHeight(size);
                    cell.setHorizontalAlignment(Element.ALIGN_CENTER);//水平居中
                    cell.setVerticalAlignment(Element.ALIGN_MIDDLE);//垂直居中
                    table.addCell(cell);
                    //备注3
                    cell = new PdfPCell(new Phrase("",font10));
                    cell.setColspan(3);
                    cell.setFixedHeight(size);
                    cell.setHorizontalAlignment(Element.ALIGN_CENTER);//水平居中
                    cell.setVerticalAlignment(Element.ALIGN_MIDDLE);//垂直居中
                    table.addCell(cell);
                }

                //空一行
                cell = new PdfPCell(new Phrase("",font6));
                cell.setColspan(24);
                cell.setFixedHeight(size*0.5f);
                cell.setHorizontalAlignment(Element.ALIGN_CENTER);//居中
                cell.setVerticalAlignment(Element.ALIGN_MIDDLE);//垂直居中
                cell.disableBorderSide(15);//隐藏边框
                table.addCell(cell);
                //签字部分
                cell = new PdfPCell(new Phrase("领料人签名:",font10b));
                cell.setColspan(12);
                cell.setFixedHeight(size);
                cell.setHorizontalAlignment(Element.ALIGN_LEFT);//靠左
                cell.setVerticalAlignment(Element.ALIGN_MIDDLE);//垂直居中
                cell.disableBorderSide(2);//隐藏下边框
                table.addCell(cell);

                cell = new PdfPCell(new Phrase("管理员签名:",font10b));
                cell.setColspan(12);
                cell.setFixedHeight(size);
                cell.setHorizontalAlignment(Element.ALIGN_LEFT);//靠左
                cell.setVerticalAlignment(Element.ALIGN_MIDDLE);//垂直居中
                cell.disableBorderSide(2);//隐藏下边框
                table.addCell(cell);

                cell = new PdfPCell(new Phrase("日期:              年    月    日",font10b));
                cell.setColspan(12);
                cell.setFixedHeight(size);
                cell.setHorizontalAlignment(Element.ALIGN_LEFT);//靠左
                cell.setVerticalAlignment(Element.ALIGN_MIDDLE);//垂直居中
                cell.disableBorderSide(1);//隐藏上边框
                table.addCell(cell);

                cell = new PdfPCell(new Phrase("日期:               年    月    日",font10b));
                cell.setColspan(12);
                cell.setFixedHeight(size);
                cell.setHorizontalAlignment(Element.ALIGN_LEFT);//靠左
                cell.setVerticalAlignment(Element.ALIGN_MIDDLE);//垂直居中
                cell.disableBorderSide(1);//隐藏上边框
                table.addCell(cell);
                //底部公司以及电话
                cell = new PdfPCell(new Phrase("xxxx科技有限公司",font8b));
                cell.setColspan(8);
                cell.setFixedHeight(size);
                cell.setHorizontalAlignment(Element.ALIGN_CENTER);//水平居中
                cell.setVerticalAlignment(Element.ALIGN_MIDDLE);//垂直居中
                cell.disableBorderSide(15);//隐藏边框
                table.addCell(cell);
                cell = new PdfPCell(new Phrase("TEL:xxxxxxxx",font8b));
                cell.setColspan(8);
                cell.setFixedHeight(size);
                cell.setHorizontalAlignment(Element.ALIGN_CENTER);//水平居中
                cell.setVerticalAlignment(Element.ALIGN_MIDDLE);//垂直居中
                cell.disableBorderSide(15);//隐藏边框
                table.addCell(cell);
                cell = new PdfPCell(new Phrase("网址:www.xxx.com",font8b));
                cell.setColspan(8);
                cell.setFixedHeight(size);
                cell.setHorizontalAlignment(Element.ALIGN_CENTER);//水平居中
                cell.setVerticalAlignment(Element.ALIGN_MIDDLE);//垂直居中
                cell.disableBorderSide(15);//隐藏边框
                table.addCell(cell);
                document.newPage();
            }
            document.add(table);
        }catch (FileNotFoundException e){
            e.printStackTrace();
        }catch (DocumentException e){
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            document.close();
        }
        return filename;
    }
}

3.参考地址

http://www.blogjava.net/tjyhy590/archive/2009/08/12/290752.html

https://blog.csdn.net/evan_cheerup/article/details/27239641

https://www.cnblogs.com/matrix-zhu/p/6305944.html

4.关于自定义保存地址

4.1 application.yml文件定义路径
path:
  pdf:
    export: "E:\\temp\\"
4.2 获取

在需要使用的类中,直接用@Value注解自动注入

@Value("${path.pdf.export}")
private String EXPORT_PATH;
Spring Boot中导出PDF文件可以使用第三方库,比如iText或Apache PDFBox。以下是使用iText进行PDF导出的示例代码: 首先,需要将iText库添加到项目的依赖中。在pom.xml文件中添加以下依赖: ```xml <dependency> <groupId>com.itextpdf</groupId> <artifactId>itextpdf</artifactId> <version>5.5.13</version> </dependency> ``` 接下来,创建一个用于导出PDF的控制器,在该控制器中定义一个处理请求的方法。在方法中使用iText库来生成PDF文件。 ```java import com.itextpdf.text.Document; import com.itextpdf.text.DocumentException; import com.itextpdf.text.Paragraph; import com.itextpdf.text.pdf.PdfWriter; import org.springframework.http.MediaType; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.OutputStream; @Controller public class PdfController { @GetMapping("/exportpdf") public void exportPdf(HttpServletResponse response) throws IOException, DocumentException { response.setContentType(MediaType.APPLICATION_PDF_VALUE); response.setHeader("Content-Disposition", "attachment; filename=example.pdf"); Document document = new Document(); OutputStream outputStream = response.getOutputStream(); PdfWriter.getInstance(document, outputStream); document.open(); document.add(new Paragraph("Hello, World!")); document.close(); outputStream.close(); } } ``` 在上述代码中,我们使用`@GetMapping`注解来处理GET请求,并指定了导出PDF的URL为`/exportpdf`。在`exportPdf`方法中,我们首先设置响应的内容类型为PDF,然后设置响应头部的Content-Disposition,指定文件名为example.pdf。 接下来,创建一个`Document`实例,并使用`PdfWriter`将文档写入输出流中。在文档中添加内容,这里我们添加了一个简单的段落"Hello, World!"。最后关闭文档和输出流。 当访问`/exportpdf`URL时,将会下载一个名为example.pdfPDF文件,其中包含"Hello, World!"的内容。 这只是一个简单的示例,你可以根据实际需求来生成更复杂的PDF文件。希望对你有所帮助!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值