首页 > 编程语言 >java导出PDF文件

java导出PDF文件

时间:2024-07-10 11:54:23浏览次数:15  
标签:10 java 导出 new cell param table PDF Font

我们需要将生成的PDF文件直接导出到浏览器而不是保存到本地,需要对HttpServletResponse进行配置,将PDF写入到响应流中。
以下是可以将PDF导出到浏览器进行下载:

我们首先先编写PDF工具类:

package com.scenic.util;

import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;

import java.io.IOException;

public class PdfFUtil {
    // 最大宽度
    private static int maxWidth = 720;

/**------------------------创建表格单元格的方法start----------------------------*/
    /**
     * 创建单元格(指定字体)
     *
     * @param value
     * @param font
     * @return
     */
    public static PdfPCell createCell(String value, Font font) {
        PdfPCell cell = new PdfPCell();
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE); //垂直居中
        cell.setHorizontalAlignment(Element.ALIGN_CENTER); //水平居中
        cell.setPhrase(new Phrase(value, font));
        return cell;
    }

    /**
     * 创建单元格(指定字体、设置单元格高度)
     *
     * @param value
     * @param font
     * @return 申请事由——这行使用的方法
     */
    public static PdfPCell createCell(String value, Font font, float f) {
        PdfPCell cell = new PdfPCell();
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell.setPhrase(new Phrase(value, font));
        cell.setFixedHeight(f); // 设置表格中的单行高度
        return cell;
    }

    /**
     * 创建单元格(指定字体、水平局左/中/右)
     *
     * @param value
     * @param font
     * @param align
     * @return
     */
    public static PdfPCell createCell(String value, Font font, int align) {
        PdfPCell cell = new PdfPCell();
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE); //垂直居中
        cell.setHorizontalAlignment(align); //水平居中
        cell.setPhrase(new Phrase(value, font));
        return cell;
    }

    /**
     * 创建单元格(指定字体、水平局左/中/右、单元格跨x列合并)
     *
     * @param value
     * @param font
     * @param align
     * @param colspan
     * @return
     */
    public PdfPCell createCell(String value, Font font, int align, int colspan) {
        PdfPCell cell = new PdfPCell();
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE); //垂直居中
        cell.setHorizontalAlignment(align); //水平居中
        cell.setColspan(colspan);
        cell.setPhrase(new Phrase(value, font));
        return cell;
    }

    /**
     * 创建单元格(指定字体、水平居..、单元格跨x列合并、设置单元格内边距)
     *
     * @param value
     * @param font
     * @param align
     * @param colspan
     * @param boderFlag
     * @return
     */
    public static PdfPCell createCell(String value, Font font, int align, int colspan, boolean boderFlag) {
        PdfPCell cell = new PdfPCell();
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell.setHorizontalAlignment(align);
        cell.setColspan(colspan);
        cell.setPhrase(new Phrase(value, font));
        cell.setPadding(3.0f);
        if (!boderFlag) {
            cell.setBorder(0);
            cell.setPaddingTop(10.0f);
            cell.setPaddingBottom(7.0f);
        } else if (boderFlag) {
            cell.setBorder(0);
            cell.setPaddingTop(0.0f);
            cell.setPaddingBottom(15.0f);
        }
        return cell;
    }

    /**
     * 创建单元格(指定字体、水平..、边框宽度:0表示无边框、内边距)
     *
     * @param value
     * @param font
     * @param align
     * @param borderWidth
     * @param paddingSize
     * @param flag
     * @return
     */
    public static PdfPCell createCell(String value, Font font, int align, float[] borderWidth, float[] paddingSize, boolean flag) {
        PdfPCell cell = new PdfPCell();
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell.setHorizontalAlignment(align);
        cell.setPhrase(new Phrase(value, font));
        cell.setBorderWidthLeft(borderWidth[0]);
        cell.setBorderWidthRight(borderWidth[1]);
        cell.setBorderWidthTop(borderWidth[2]);
        cell.setBorderWidthBottom(borderWidth[3]);
        cell.setPaddingTop(paddingSize[0]);
        cell.setPaddingBottom(paddingSize[1]);
        if (flag) {
            cell.setColspan(2);
        }
        return cell;
    }
/**------------------------创建表格单元格的方法end----------------------------*/


/**--------------------------创建表格的方法start----------------------------*/
    /**
     * 创建默认列宽,指定列数、水平(居中、右、左)的表格
     *
     * @param colNumber
     * @param align
     * @return
     */
    public PdfPTable createTable(int colNumber, int align) {
        PdfPTable table = new PdfPTable(colNumber);
        try {
            table.setTotalWidth(maxWidth);
            table.setLockedWidth(true);
            table.setHorizontalAlignment(align);
            table.getDefaultCell().setBorder(1);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return table;
    }

    /**
     * 创建指定列宽、列数的表格
     *
     * @param widths
     * @return
     */
    public static PdfPTable createTable(float[] widths) {
        PdfPTable table = new PdfPTable(widths);
        try {
            table.setTotalWidth(maxWidth);
            table.setLockedWidth(true);
            table.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.getDefaultCell().setBorder(1);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return table;
    }

    /**
     * 创建空白的表格
     *
     * @return
     */
    public PdfPTable createBlankTable() throws IOException, DocumentException {
        BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
        Font keyfont = new Font(bfChinese, 10, Font.BOLD);
        PdfPTable table = new PdfPTable(1);
        table.getDefaultCell().setBorder(0);
        table.addCell(createCell("", keyfont));
        table.setSpacingAfter(20.0f);
        table.setSpacingBefore(20.0f);
        return table;
    }
/**--------------------------创建表格的方法end----------------------------*/
    /**
     * --------------------------页码方法start----------------------------
     */
    public static void onEndPage(PdfWriter writer, Document document) throws IOException, DocumentException {
        PdfContentByte cb = writer.getDirectContent();
        PdfTemplate tpl; // 页码模板用来固定显示数据
        BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
        tpl = writer.getDirectContent().createTemplate(100, 100);
        cb.saveState();
        String text = "第" + writer.getPageNumber() + "页";
        cb.beginText();
        cb.setFontAndSize(bfChinese, 8);
        cb.setTextMatrix(480, 35);//定位“第x页” 在具体的页面调试时候需要更改这xy的坐标
        cb.showText(text);
        cb.endText();
        //** 创建以及固定显示总页数的位置
        cb.addTemplate(tpl, 283, 10);//定位“y页” 在具体的页面调试时候需要更改这xy的坐标
        cb.stroke();
        cb.restoreState();
        cb.closePath();
/**--------------------------页码方法end----------------------------*/
    }
}

接着我们编写controller层进行实现代码


/**
     * 导出pdf格式文档
     *
     * @return
     * @throws Exception
     */
    @PostMapping("/pdf")
    public void getUser(HttpServletResponse response) throws Exception {
        List<ActivityVo> list = activityService.searchActivityByConditions(new ActivityDTO());
        long currentTime = System.currentTimeMillis();
        int total = list.size();

        try {
            // 1.新建Document对象
            Document document = new Document(PageSize.A4.rotate());  //建立一个Document对象

            // 2.建立一个书写器(writer)与document对象关联
            PdfWriter writer = PdfWriter.getInstance(document, response.getOutputStream());

            // 3.打开文档
            document.open();

            // 设置响应头信息
            response.setContentType("application/pdf");
            response.setHeader("Content-Disposition", "attachment;filename=user_" + currentTime + ".pdf");

            // 标题
            Paragraph paragraph = new Paragraph("用户表", titlefont_16);
            paragraph.setAlignment(1); //设置文字居中,0靠左,1居中,2靠右
            paragraph.setIndentationLeft(12); //设置左缩进
            paragraph.setIndentationRight(12);  //设置右缩进
            paragraph.setFirstLineIndent(24); //设置首行缩进
            paragraph.setLeading(20f);  //设置行间距
            paragraph.setSpacingBefore(5f);  //设置段落上空白
            paragraph.setSpacingAfter(10f);  //设置段落下空白

            document.add(paragraph);   //标题
            // 表格
            PdfPTable table = PdfFUtil.createTable(new float[]{75, 110, 75, 140, 75});
            table.addCell(PdfFUtil.createCell("ID", textfont_10));
            table.addCell(PdfFUtil.createCell("姓名", textfont_10));
            table.addCell(PdfFUtil.createCell("年龄", textfont_10));
            table.addCell(PdfFUtil.createCell("住址", textfont_10));
            table.addCell(PdfFUtil.createCell("住址2", textfont_10));

            for (int i = 0; i < total; i++) {
                table.addCell(PdfFUtil.createCell(String.valueOf(list.get(i).getId()), textfont_10));
                table.addCell(PdfFUtil.createCell(list.get(i).getActivityName(), textfont_10));
                table.addCell(PdfFUtil.createCell(String.valueOf(list.get(i).getActivityInstructions()), textfont_10));
                table.addCell(PdfFUtil.createCell(String.valueOf(list.get(i).getActivityAddr()), textfont_10));
                table.addCell(PdfFUtil.createCell(String.valueOf(list.get(i).getActivityPerson()), textfont_10));
            }
            document.add(table);
            PdfFUtil.onEndPage(writer, document);

            // 5.关闭文档
            document.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 全局变量
     */
//    定义全局的字体静态变量
    private static Font titlefont_16;
    private static Font titlefontnormal_16;
    private static Font headfont_14;
    private static Font headfontnormal_14;
    private static Font headfont_12;
    private static Font headfontnormal_12;
    private static Font keyfont_10;
    private static Font textfont_10;
    private static Font underlinefont_10;

    //    静态代码块
    static {
        try {
            // 定义字体样式
            BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
            titlefont_16 = new Font(bfChinese, 16, Font.BOLD);
            headfont_14 = new Font(bfChinese, 14, Font.BOLD);
            headfont_12 = new Font(bfChinese, 12, Font.BOLD);
            keyfont_10 = new Font(bfChinese, 10, Font.BOLD);

            titlefontnormal_16 = new Font(bfChinese, 16, Font.NORMAL);
            headfontnormal_14 = new Font(bfChinese, 14, Font.NORMAL);
            headfontnormal_12 = new Font(bfChinese, 12, Font.NORMAL);
            textfont_10 = new Font(bfChinese, 10, Font.NORMAL);
            underlinefont_10 = new Font(bfChinese, 10, Font.UNDERLINE);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

到这里基本就可以测试了,我使用的是postman来测试的

然后就到这里就结束了!!

标签:10,java,导出,new,cell,param,table,PDF,Font
From: https://www.cnblogs.com/dinopell/p/18293690

相关文章

  • Java中的SpringAOP、代理模式、常用AspectJ注解详解
      这篇文章主要介绍了Java中的SpringAOP、代理模式、常用AspectJ注解详解,Spring提供了面向切面编程的丰富支持,允许通过分离应用的业务逻辑与系统级服务,例如审计和事务管理进行内聚性的开发,需要的朋友可以参考下 +目录一、AOP简述回到主题,何为AOP?AOP即面向切面编......
  • java类的加载顺序及复杂案例(阿里)
    一.无继承关系的情况下在Java中,类的初始化顺序涉及到多个方面,包括静态变量、静态初始化块、实例变量、实例初始化块(也称为构造器初始化块或初始化块)以及构造器的执行顺序。这里是一个详细的顺序说明:静态变量和静态初始化块:当类被加载到JVM时,类的静态成员(静态变量和静态初......
  • JavaScript复习记录(2)— 浅拷贝&深拷贝
    1、前情概要1.1、基本数据类型    Number、String、Boolean、Null、Undefined、Symbol、BigInt。基本数据类型是直接存储在栈中的数据。1.2、引用数据类型    Object、Array、Function、Date、RegExp、Map、Set、WeekMap、WeekSet、Promise、Error、Buffe......
  • 基于JavaWeb的酒店管理系统(源码+数据库+项目展示文档+部署文档)
    酒店管理系统报告系统概述酒店管理系统是为酒店设计开发的管理平台,旨在提供完善的管理功能以支持酒店的日常运营和管理。该系统基于JavaWeb技术栈开发,使用Servlet和JSP作为主要服务端技术,前端设计采用Layui和jQuery框架,通过美观的Windows风格界面提供用户友好的操作体验。系......
  • [0033]基于JAVA的OA办公智慧管理系统的设计与实现
    毕业设计(论文)开题报告表姓名学院专业班级题目基于JAVA的OA办公智慧管理系统的设计与实现指导老师(一)选题的背景和意义随着社会的发展,越来越多的企业开始使用办公自动化系统来提高工作效率,减少人力成本,增强协同工作的能力。但是现有的办公自动化系统......
  • 计算机毕业设计必看必学18363+健康码采集系统原创定制程序,java、PHP、python、小程序
    springboot健康码采集系统摘 要随着科学技术的飞速发展,社会的方方面面、各行各业都在努力与现代的先进技术接轨,通过科技手段来提高自身的优势,校园当然也不例外。健康码采集系统是以实际运用为开发背景,运用软件工程原理和开发方法,采用Java技术构建的一个管理系统。整个开......
  • 基于java+springboot+vue实现的音乐网站(文末源码+Lw)102
     功能介绍:本音乐网站管理员功能有个人中心,用户管理,歌曲分类管理,歌曲信息管理,管理员管理,系统管理等。用户可以注册登录,试听歌曲,可以下载歌曲。因而具有一定的实用性。本站是一个B/S模式系统,采用SpringBoot框架,MYSQL数据库设计开发,充分保证系统的稳定性。系统具有界面清晰、......
  • 基于java+springboot+vue实现的校园社团管理平台(文末源码+Lw)101
     本校园社团信息管理系统功能有个人中心,学生管理,社长管理,社团分类管理,社团信息管理,加入社团管理,社团成员管理,社团活动管理,活动报名管理,系统管理等。社长添加社团,管理员审核社团,学生加入社团,社长审核社团。因而具有一定的实用性。本站是一个B/S模式系统,采用SpringBoot框架,MY......
  • 【转】-Java并发编程:CountDownLatch、CyclicBarrier和Semaphore
    Java并发编程:CountDownLatch、CyclicBarrier和Semaphore该博客转载自​Matrix海子​的​Java并发编程:CountDownLatch、CyclicBarrier和Semaphore在java1.5中,提供了一些非常有用的辅助类来帮助我们进行并发编程,比如CountDownLatch,CyclicBarrier和Semaphore,今天我们就来学习一下......
  • 基于java+springboot+vue实现的音乐网站(文末源码+Lw)102
     功能介绍:本音乐网站管理员功能有个人中心,用户管理,歌曲分类管理,歌曲信息管理,管理员管理,系统管理等。用户可以注册登录,试听歌曲,可以下载歌曲。因而具有一定的实用性。本站是一个B/S模式系统,采用SpringBoot框架,MYSQL数据库设计开发,充分保证系统的稳定性。系统具有界面清晰、......