springboot+itextpdf初尝试

本文详细介绍了如何通过iTextPDF库在Java开发中创建PDF文档,包括设置文档标题、作者、主题等元数据,并演示了如何构造表格展示数据,如产品列表。实例代码涵盖了从依赖引入、核心类创建到实际调用的完整流程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在日常开发中,经常会遇见导出word、exce、pdf文档的需求,本次尝试通过itextpdf实现导出pdf文档。

实例如下:

pom文件

        <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>

核心代码

public class PdfUtil {

    public static void createPDF(Document document, PdfWriter writer, List<Product> products) throws IOException {
        try {
            document.addTitle("sheet of product");
            document.addAuthor("ldc");
            document.addSubject("product sheet.");
            document.addKeywords("product.");
            document.open();
            PdfPTable table = createTable(writer, products);
            document.add(table);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (DocumentException e) {
            e.printStackTrace();
        } finally {
            document.close();
        }
    }

    public static void createPDF(HttpServletResponse response, List<Product> products) throws IOException, DocumentException {
        Document document = new Document(PageSize.A4);
        PdfWriter pdfWriter = PdfWriter.getInstance(document, response.getOutputStream());
        try {
            document.addTitle("sheet of product");
            document.addAuthor("ldc");
            document.addSubject("product sheet.");
            document.addKeywords("product.");
            document.open();
            PdfPTable table = createTable(pdfWriter, products);
            document.add(table);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (DocumentException e) {
            e.printStackTrace();
        } finally {
            document.close();
        }
    }

    public static PdfPTable createTable(PdfWriter writer, List<Product> products) throws IOException, DocumentException {
        PdfPTable table = new PdfPTable(3);//生成一个三列的表格
        PdfPCell cell;
        int size = 20;
        //设置中文字体
        BaseFont bf = BaseFont.createFont( "STSong-Light", "UniGB-UCS2-H", false, false, null, null);
        Font font = new Font(bf,8);
        //Font font = new Font(BaseFont.createFont( "STSongStd-Light" ,"UniGB-UCS2-H",BaseFont.NOT_EMBEDDED));
        for (int i = 0; i < products.size(); i++) {
            cell = new PdfPCell(new Phrase(products.get(i).getProductCode(), font));//产品编号
            cell.setFixedHeight(size);
            table.addCell(cell);
            cell = new PdfPCell(new Phrase(products.get(i).getProductName(), font));//产品名称
            cell.setFixedHeight(size);
            table.addCell(cell);
            cell = new PdfPCell(new Phrase(products.get(i).getPrice() + "", font));//产品价格
            cell.setFixedHeight(size);
            table.addCell(cell);
        }
        return table;
    }
}

public class Product {

    private String productName;

    private String productCode;

    private float price;

    public Product(String productName,String productCode,float price){
        this.productName = productName;
        this.productCode = productCode;
        this.price = price;
    }

    public String getProductName() {
        return productName;
    }

    public void setProductName(String productName) {
        this.productName = productName;
    }

    public String getProductCode() {
        return productCode;
    }

    public void setProductCode(String productCode) {
        this.productCode = productCode;
    }

    public float getPrice() {
        return price;
    }

    public void setPrice(float price) {
        this.price = price;
    }

}

@RestController
public class PdfController {

    @RequestMapping("/printPdf")
    public Object printPdf(HttpServletRequest request, HttpServletResponse response) throws IOException, DocumentException {
        Product product1 = new Product("产品一","cp01",120);
        Product product2 = new Product("产品二","cp02",130);
        Product product3 = new Product("产品三","cp03",140);
        List<Product> products = new ArrayList<>();
        products.add(product1);
        products.add(product2);
        products.add(product3);
        // 生成文件位置
        String filename = System.getProperty("user.dir") + "/src/main/resources/pdf/" + "template.pdf";
        Document document = new Document(PageSize.A4);
        PdfWriter pdfWriter = PdfWriter.getInstance(document, new FileOutputStream(filename));
        PdfUtil.createPDF(document,pdfWriter,products);
        return "ok";
    }

    @RequestMapping("/printPdf2")
    public Object printPdf2(HttpServletRequest request, HttpServletResponse response) throws IOException, DocumentException {
        Product product1 = new Product("产品一","cp01",120);
        Product product2 = new Product("产品二","cp02",130);
        Product product3 = new Product("产品三","cp03",140);
        List<Product> products = new ArrayList<>();
        products.add(product1);
        products.add(product2);
        products.add(product3);
        PdfUtil.createPDF(response, products);
        // 设置response方式,使执行此controller时候自动出现下载页面,而非直接使用excel打开
        String fileName = System.currentTimeMillis() + "_template.pdf";
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/pdf");
        // 直接下载
        response.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes(), "iso8859-1"));
        //response.setHeader("Content-Disposition", "filename=" + new String(fileName.getBytes(), "iso8859-1"));
        return "ok";
    }
}

测试结果

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值