首页 > 编程语言 >java-导出pdf

java-导出pdf

时间:2023-12-08 16:47:19浏览次数:31  
标签:java ALIGN 导出 Element cell Paragraph new pdf document

前言:

  纯代码画pdf格式

        <!-- iText PDF -->
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itextpdf</artifactId>
            <version>5.5.13.2</version>
        </dependency>
        <!-- pdf 字体需要 -->
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itext-asian</artifactId>
            <version>5.2.0</version>
        </dependency>

 

示例代码:

 

生成PDF文件(无表格版)

  Controller

@PostMapping("exportPDF")
    public void registrationNoticeExport(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
        //防止日志记录获取session异常
        request.getSession();

        HashMap<String, String> dataMap = new HashMap<>();

        dataMap.put("year","2023");
        dataMap.put("sort","12");
        dataMap.put("inspectionCompany","这是第一行的标题");
        dataMap.put("planName","这是第二行的标题xxxxxxxxx");
        dataMap.put("qymc","这是发文公司/人");
        dataMap.put("kdmc","内容测试");
        dataMap.put("attachmentNameStr","attachmentNameStr测试");
        dataMap.put("date","日期测试");
        dataMap.put("inspectionTeamLeaderInfo","落款测试");

        //导出pdf
        PdfUtil.setResponseContentType(response,  "文件名称测试" );
        PdfUtil.downloadPdf(dataMap,response);

    }

  Util

import com.itextpdf.text.*;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.draw.LineSeparator;

import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Map;

public class PdfUtil {

    public static void setResponseContentType(HttpServletResponse response, String fileName) throws UnsupportedEncodingException {
        response.setContentType("application/pdf");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "utf-8") + ".pdf");
        response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
    }


    public static void downloadPdf(Map<String,String> dataMap, HttpServletResponse response){
        // 定义全局的字体静态变量
        Font titlefont;
        Font headfont;
        Font keyfont = null;
        Font textfont = null;
        Font content = null;
        Font space = null;
        Font space1 = null;
        Font space2 = null;
        Font space3 = null;
        // 最大宽度
        try {
            // 不同字体(这里定义为同一种字体:包含不同字号、不同style)
            BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
            titlefont = new Font(bfChinese, 16, Font.BOLD);
            headfont = new Font(bfChinese, 14, Font.BOLD);
            keyfont = new Font(bfChinese, 22, Font.BOLD);
            textfont = new Font(bfChinese, 15, Font.NORMAL);
            content = new Font(bfChinese, 16, Font.NORMAL);
            space = new Font(bfChinese, 5, Font.NORMAL);
            space1 = new Font(bfChinese, 20, Font.NORMAL);
            space2 = new Font(bfChinese, 20, Font.NORMAL);
            space3 = new Font(bfChinese, 3, Font.NORMAL);

        } catch (Exception e) {
            e.printStackTrace();
        }
        BaseFont bf;
        Font font = null;
        try {
            //可以引用自己想要的字体
            bf = BaseFont.createFont("D:\\cbd-marketSurvey-service\\src\\main\\resources\\templates\\simsun.ttc,1",
                    BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
            //创建字体 
//            bf = BaseFont.createFont( "STSong-Light", "UniGB-UCS2-H",
//                    BaseFont.NOT_EMBEDDED);
            //使用字体并给出颜色
            font = new Font(bf,36,Font.BOLD, BaseColor.RED);
        } catch (Exception e) {
            e.printStackTrace();
        }
        Document document = new Document(new Rectangle(com.itextpdf.text.PageSize.A4));

        try {
            com.itextpdf.text.pdf.PdfWriter.getInstance(document, response.getOutputStream());
            //打开PDF文件
            document.open();
            //设置内容
            Paragraph paragraph = new Paragraph("标题内容测试", font);
            //居中设置
            paragraph.setAlignment(Element.ALIGN_CENTER);
            document.add(paragraph);

            //页眉横线
            document.add(new Paragraph("\n", space2));
            LineSeparator line = new LineSeparator(3f, 100, BaseColor.RED, Element.ALIGN_CENTER, 0f);
            document.add(line);
            document.add(new Paragraph("\n", space3));
            LineSeparator lineStart = new LineSeparator(1f, 100, BaseColor.RED, Element.ALIGN_CENTER, 0f);
            document.add(lineStart);

            document.add(new Paragraph("\n", space));
            String text = "标注测试〔" + dataMap.get("year") + "〕" + dataMap.get("sort") + "号";
            Paragraph paragraph0 = new Paragraph(text, content);
            paragraph0.setAlignment(Element.ALIGN_RIGHT);
            document.add(paragraph0);

            document.add(new Paragraph("\n"));
            Paragraph paragraph1 = new Paragraph(dataMap.get("inspectionCompany"), keyfont);
            paragraph1.setAlignment(Element.ALIGN_CENTER);
            document.add(paragraph1);

            document.add(new Paragraph("\n", space));
            String concent = dataMap.get("planName");
            Paragraph paragraph2 = new Paragraph(concent, keyfont);
            paragraph2.setAlignment(Element.ALIGN_CENTER);
            document.add(paragraph2);

            document.add(new Paragraph("\n"));
            Paragraph paragraph3 = new Paragraph(dataMap.get("qymc") + ":", content);
            paragraph3.setAlignment(Element.ALIGN_LEFT);
            document.add(paragraph3);

            document.add(new Paragraph("\n", space));
            String concent1 = "             现将" + dataMap.get("kdmc")
                    + "这是一段内容测试:知识密集型行业往往有着这样的特点,一方面对于从业者有着高度专业化的知识要求,需要具备高度专业化的背景和经验,准入门槛较高;同时,知识密集型行业往往也是文档密集型行业,文档的厚度和复杂性较高,让行业的数字化转型与应用创新面临更大挑战。。";
            Paragraph paragraph4 = new Paragraph(concent1, content);
            //设置首行缩进
            paragraph4.setIndentationRight(2);
            document.add(paragraph4);

            document.add(new Paragraph("\n", space));
            Paragraph paragraph5 = new Paragraph("              特此通知。", content);
            //右缩进2格
            paragraph5.setIndentationRight(2);
            document.add(paragraph5);

            document.add(new Paragraph("\n", space1));
            document.add(new Paragraph("\n", space1));
            //附件
            Paragraph paragraph6 = new Paragraph("              附件:", content);
            //右缩进2格
            paragraph6.setIndentationRight(2);
            document.add(paragraph6);

            document.add(new Paragraph("\n", space));
            Paragraph paragraph7 = new Paragraph("              "+dataMap.get("attachmentNameStr"), content);
            document.add(paragraph7);

            document.add(new Paragraph("\n", space1));
            document.add(new Paragraph("\n", space1));
            document.add(new Paragraph("\n", space1));

            //日期
            Paragraph paragraph8 = new Paragraph(dataMap.get("date"), content);
            //向右
            paragraph8.setAlignment(Element.ALIGN_RIGHT);
            document.add(paragraph8);

            document.add(new Paragraph("\n", space1));
            //落款
            Paragraph paragraph9 = new Paragraph(dataMap.get("inspectionTeamLeaderInfo"), content);
            paragraph9.setAlignment(Element.ALIGN_CENTER);
            document.add(paragraph9);

            //页尾横线
            document.add(new Paragraph("\n", space2));
            document.add(new Paragraph("\n", space2));
            LineSeparator lineEnd = new LineSeparator(3f, 100, BaseColor.RED, Element.ALIGN_CENTER, 0f);
            document.add(lineEnd);
            document.add(new Paragraph("\n", space3));
            LineSeparator lineEnd1 = new LineSeparator(1f, 100, BaseColor.RED, Element.ALIGN_CENTER, 0f);
            document.add(lineEnd1);
            
            //关闭文档
            document.close();

        } catch (Exception e) {
            e.printStackTrace();
            //log.error("导出pdf失败:{}", e);
        }

    }
}

  效果图

 

 生成PDF文件(表格版)

  Controller

    @PostMapping("/download")
    public void download(HttpServletResponse response, HttpServletRequest request) throws IOException {
        // 防止日志记录获取session异常
        request.getSession();
        // 设置编码格式
        response.setContentType("application/pdf;charset=UTF-8");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("下载的PDF名称", "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".pdf");
        List<String> list = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            list.add(String.valueOf(i));
        }
        PdfUtil.download(list, response);
    }

  Util



    public static void download(List<String> list, HttpServletResponse response) throws IOException {
        //要下载的数据查询数据部分我去掉了有需要自己根据业务取

        // 定义全局的字体静态变量
        Font content = null;
        // 最大宽度
        try {
            // 不同字体(这里定义为同一种字体:包含不同字号、不同style) 
            BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
            content = new Font(bfChinese, 10, Font.NORMAL);

        } catch (Exception e) {
            e.printStackTrace();
        }
        BaseFont bf;
        Font font = null;
        try {
            //创建字体
            bf = BaseFont.createFont( "STSong-Light", "UniGB-UCS2-H",
                    BaseFont.NOT_EMBEDDED);
            //使用字体并给出颜色
            font = new Font(bf,20,Font.BOLD, BaseColor.BLACK);
        } catch (Exception e) {
            e.printStackTrace();
        }

        Document document = new Document(new RectangleReadOnly(842F, 595F));
        try {
            PdfWriter.getInstance(document,response.getOutputStream());
            //打开生成的pdf文件
            document.open();
            //设置内容
            Paragraph paragraph = new Paragraph("主题名称",font);
            paragraph.setAlignment(1);
            //引用字体
            document.add(paragraph);

            // 设置表格的列宽和列数
            float[] widths = {25f,25f,25f,25f,25f,25f};
            PdfPTable table = new PdfPTable(widths);
            table.setSpacingBefore(20f);
            // 设置表格宽度为100%
            table.setWidthPercentage(100.0F);
            table.setHeaderRows(1);
            table.getDefaultCell().setHorizontalAlignment(1);
            PdfPCell cell = null;
            //第一行
            cell = new PdfPCell(new Paragraph("标题",content));
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setFixedHeight(30);
            table.addCell(cell);

            cell = new PdfPCell(new Paragraph("内容测试",content));
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.addCell(cell);

            cell = new PdfPCell(new Paragraph("标题",content));
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.addCell(cell);

            cell = new PdfPCell(new Paragraph("内容测试",content));
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.addCell(cell);

            cell = new PdfPCell(new Paragraph("标题",content));
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.addCell(cell);

            cell = new PdfPCell(new Paragraph("内容测试",content));
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.addCell(cell);
            //第二行
            cell = new PdfPCell(new Paragraph("标题",content));
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setFixedHeight(30);
            table.addCell(cell);

            cell = new PdfPCell(new Paragraph("内容测试",content));
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.addCell(cell);

            cell = new PdfPCell(new Paragraph("标题",content));
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.addCell(cell);

            cell = new PdfPCell(new Paragraph("内容测试",content));
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.addCell(cell);

            cell = new PdfPCell(new Paragraph("标题",content));
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.addCell(cell);

            cell = new PdfPCell(new Paragraph("内容测试",content));
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.addCell(cell);
            //第三行
            cell = new PdfPCell(new Paragraph("标题",content));
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setFixedHeight(30);
            table.addCell(cell);

            cell = new PdfPCell(new Paragraph("内容测试",content));
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.addCell(cell);

            cell = new PdfPCell(new Paragraph("标题",content));
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.addCell(cell);

            cell = new PdfPCell(new Paragraph("内容测试",content));
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.addCell(cell);

            cell = new PdfPCell(new Paragraph(" ",content));
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.addCell(cell);

            cell = new PdfPCell(new Paragraph(" ",content));
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.addCell(cell);

            // 设置表格的列宽和列数
            float[] widths2 = {25f,25f,25f,25f,25f,25f};
            PdfPTable table2 = new PdfPTable(widths2);
            table2.setSpacingBefore(20f);
            // 设置表格宽度为100%
            table2.setWidthPercentage(100.0F);
            table2.setHeaderRows(1);
            table2.getDefaultCell().setHorizontalAlignment(1);

            //人员列表-第四行
            cell = new PdfPCell(new Paragraph("标题",content));
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setFixedHeight(20);
            table2.addCell(cell);

            cell = new PdfPCell(new Paragraph("标题",content));
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            table2.addCell(cell);

            cell = new PdfPCell(new Paragraph("标题",content));
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            table2.addCell(cell);

            cell = new PdfPCell(new Paragraph("标题",content));
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            table2.addCell(cell);

            cell = new PdfPCell(new Paragraph("标题",content));
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            table2.addCell(cell);

            cell = new PdfPCell(new Paragraph("标题",content));
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            table2.addCell(cell);
            //人员列表数据-第五行
            if(list.size() > 0){
                for (String prople : list) {
                    PdfPCell cell1 = new PdfPCell(new Paragraph(prople, content));
                    PdfPCell cell2 = new PdfPCell(new Paragraph(prople, content));
                    PdfPCell cell3 = new PdfPCell(new Paragraph(prople, content));
                    PdfPCell cell4 = new PdfPCell(new Paragraph(prople, content));
                    PdfPCell cell5 = new PdfPCell(new Paragraph(prople, content));
                    PdfPCell cell6 = new PdfPCell(new Paragraph(prople, content));

                    //单元格对齐方式
                    cell1.setHorizontalAlignment(Element.ALIGN_CENTER);
                    cell1.setVerticalAlignment(Element.ALIGN_MIDDLE);
                    cell1.setFixedHeight(20);
                    //单元格垂直对齐方式
                    cell2.setHorizontalAlignment(Element.ALIGN_CENTER);
                    cell2.setVerticalAlignment(Element.ALIGN_MIDDLE);

                    cell3.setHorizontalAlignment(Element.ALIGN_CENTER);
                    cell3.setVerticalAlignment(Element.ALIGN_MIDDLE);

                    cell4.setHorizontalAlignment(Element.ALIGN_CENTER);
                    cell4.setVerticalAlignment(Element.ALIGN_MIDDLE);

                    cell5.setHorizontalAlignment(Element.ALIGN_CENTER);
                    cell5.setVerticalAlignment(Element.ALIGN_MIDDLE);

                    cell6.setHorizontalAlignment(Element.ALIGN_CENTER);
                    cell6.setVerticalAlignment(Element.ALIGN_MIDDLE);

                    table2.addCell(cell1);
                    table2.addCell(cell2);
                    table2.addCell(cell3);
                    table2.addCell(cell4);
                    table2.addCell(cell5);
                    table2.addCell(cell6);
                }
            }

            document.add(new Paragraph("\n"));
            document.add(new Paragraph("▋ 基本信息",content));
            document.add(new Paragraph("\n"));

            document.add(table);

            document.add(new Paragraph("\n"));
            document.add(new Paragraph("▋ 基本信息",content));
            document.add(new Paragraph("\n"));

            document.add(table2);

            //关闭文档
            document.close();
            
        } catch (DocumentException e) {
            e.printStackTrace();
            log.error("导出pdf失败:{}",e);
        }
    }

  效果图

标签:java,ALIGN,导出,Element,cell,Paragraph,new,pdf,document
From: https://www.cnblogs.com/Kikai/p/17879144.html

相关文章

  • Java中<where>和<if>标签的组合使用
    在Java中,并没有<where>和<if>标签的组合使用。这两个标签不是Java编程语言或Java标准库的一部分,它们可能是你所使用的特定框架或库提供的自定义标签。如果你正在使用某个特定的Java框架或模板引擎(如MyBatis、Thymeleaf等),这些框架或引擎可能提供了自定义标签,使得在代码中使用类似于<......
  • 使用freemarker,导出制作好的ftl模板,并写入数据
    使用freemarker,导出制作好的ftl模板,并写入数据一、背景1.1项目背景最近在开发一个项目,需要导出一些数据,然后写入到word文档中,然后再导出到本地,这个需求是比较常见的,但是我在网上找了很多资料,都没有找到一个比较好的解决方案,所以就自己写了一个,这里分享给大家,希望能帮助到大家......
  • JetBrains WebStorm 2023.3 (macOS, Linux, Windows) - 最智能的 JavaScript IDE
    JetBrainsWebStorm2023.3(macOS,Linux,Windows)-最智能的JavaScriptIDE请访问原文链接:https://sysin.org/blog/jb-webstorm-2023/,查看最新版。原创作品,转载请保留出处。作者主页:sysin.orgJetBrainsWebStorm-最智能的JavaScriptIDEWebStorm是一个适用于JavaSc......
  • 使用Java实现面向对象编程 第八章 File IO 总结笔记
    java里操作文件1.第一步一定是获得这个文件(获得的文件,你是无法解析获得里面的内容,约等于获得冰。你只能知道大小颜色等。外表能够获取信息.)。2.第二步获得这个文件将这个文件转换成流。然后从这个io流里读取数据io流里又分为字符流(专门处理文字)字节流(专门处理2进制等文件)3.......
  • 在gitlab中如何导出、导入某个项目(提交记录不变),对某个项目进行迁移
    1、需求说明 在项目的迁移中遇到,需要将gitlab中的某个项目进行迁移的过程。关键点是,需要保持提交记录不变。 本文档下面的内容,就介绍这个过程。 2、项目导出、导入的过程 2.1、导出项目 a、登录到gitlab页面  b、点击要迁移的项目   可以看到项目......
  • 如何实现Java file.mkdir()失败的具体操作步骤
    如何实现Javafile.mkdir()失败的具体操作步骤Java中的file.mkdir()失败问题解析在Java中,使用file.mkdir()方法可以创建一个新的文件夹。然而,有时候我们可能会遇到file.mkdir()失败的情况,这可能导致程序没有按照预期创建文件夹。本篇文章将详细解析file.mkdir()失败的原因,并提供......
  • Java Agent有什么作用?
     JavaAgent概述JavaAgent是一种特殊类型的软件组件,它允许在Java虚拟机(JVM)运行时修改应用程序的字节码。这种技术通常用于性能监控、日志记录、系统调试等。JavaAgent主要分为两类:1.启动时加载的Agent(Pre-MainAgent)这种类型的Agent在应用程序的主方法(main)执行之前加载......
  • 转载:ReportLab生成带表格和图文的PDF
    转载来自于:https://zhuanlan.zhihu.com/p/456486769龙在天涯 项目环境:环境:AnacondaPython3.10编辑器:PyCharm2021.2.3Packages:Reportlab3.6.2ReportLab简介“ThisisasoftwarelibrarythatletsyoudirectlycreatedocumentsinAdobe'sPortableDocumentForma......
  • java实例化的五种方式
    1.创建新对象五种方式1.用new语句创建对象,这是最常见的创建对象的方法。2.使用Class类的newInstance方法3.使用Constructor类的newInstance方法运用反射手段,调用java.lang.Class或者java.lang.reflect.Constructor类的newInstance()实例方法。如:Objectobj=Class.forName("java......
  • Java synchronized
    synchronized是Java中最基本的线程同步机制之一,通过在方法或代码块上添加synchronized关键字,可以确保只有一个线程可以访问该方法或代码块。它是Java中实现线程安全的重要机制之一。synchronized关键字的使用方式有两种:1、修饰实例方法当synchronized关键字修饰一个实例方法时,......