当前位置: 首页 > news >正文

Java简单生成pdf

生成这样的PDF

 

直接上代码

    public static void main(String[] args) {
        String logoPath = "Q:\\IdeaWork\\Demo\\src\\main\\webapp\\images\\logo.jpg"; // 替换为实际路径
        String baseDir = "E:/Demo/TEST/problem/Generate"; // 基础目录
        int year = 2025; // 动态年份
        String issueId = "100002"; // 动态问题ID

        // 生成完整路径(自动处理斜杠)
        String outputDir = Paths.get(baseDir, String.valueOf(year), issueId).toString();
        String outputFilePath = Paths.get(outputDir, "重大事件通报.pdf").toString();

        try {
            // 确保目录存在,不存在则创建
            Path dirPath = Paths.get(outputDir);
            if (!Files.exists(dirPath)) {
                Files.createDirectories(dirPath);
                System.out.println("目录创建成功: " + dirPath);
            }

            // 生成PDF
            generatePdf(logoPath, outputFilePath);
            System.out.println("PDF生成成功: " + outputFilePath);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
public static void generatePdf(String logoPath, String outputPath)
            throws DocumentException, IOException {
        // 其余代码保持不变(和之前一样)
        Document document = new Document(PageSize.A4, 50, 50, 50, 50);
        PdfWriter.getInstance(document, new FileOutputStream(outputPath));
        document.open();

        // 设置中文字体
        BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
        Font titleFont = new Font(bfChinese, 16, Font.BOLD);
        Font headerFont = new Font(bfChinese, 12, Font.BOLD);
        Font normalFont = new Font(bfChinese, 10, Font.NORMAL);
        Font underlineFont = new Font(bfChinese, 16, Font.BOLD);
        //underlineFont.setStyle(Font.UNDERLINE);

        // 添加logo
        try {
            Image logo = Image.getInstance(logoPath);
            logo.scaleToFit(80f, 40f); // 调整logo大小
            logo.setAlignment(Element.ALIGN_CENTER);
            document.add(logo);
        } catch (Exception e) {
            System.out.println("无法加载logo图片: " + e.getMessage());
        }

        // 添加标题
        Paragraph title = new Paragraph("重 大 事 件 通 报", underlineFont);
        title.setAlignment(Element.ALIGN_CENTER);
        title.setSpacingAfter(20f);
        document.add(title);

        // 添加基本信息表格
        // 创建表格(2列)
        PdfPTable infoTable = new PdfPTable(2);
        infoTable.setWidthPercentage(80); // 缩小表格总宽度
        infoTable.setHorizontalAlignment(Element.ALIGN_LEFT); // 整体左对齐

// 设置列宽(左边固定30mm,右边自适应)
        infoTable.setWidths(new float[]{30, 70}); // 单位:毫米

// 添加表格内容(":"后加空格)
        addTableCell(infoTable, "操作:", "王峰", headerFont, normalFont);
        addTableCell(infoTable, "职位:", "考核师", headerFont, normalFont);
        addTableCell(infoTable, "被通报单位名称:", "XXX公司", headerFont, normalFont);
        addTableCell(infoTable, "日期:", "2025年03月07日", headerFont, normalFont);

        document.add(infoTable);


        // 添加称呼
        Paragraph greeting = new Paragraph("尊敬的XXX合作伙伴:", normalFont);
        greeting.setSpacingAfter(10f);
        document.add(greeting);

        Paragraph content = new Paragraph("为确保双方合作的顺利进行,现就以下关键事项进行通知,请您知悉并按要求执行。", normalFont);
        content.setSpacingAfter(20f);
        document.add(content);

        // 添加事件主题
        Paragraph eventTitle = new Paragraph("事件主题", headerFont);
        eventTitle.setSpacingAfter(5f);
        document.add(eventTitle);

        Paragraph eventContent = new Paragraph("交付异常", normalFont);
        eventContent.setSpacingAfter(15f);
        document.add(eventContent);


        // 添加事件说明
        Paragraph descriptionTitle = new Paragraph("事件说明", headerFont);
        descriptionTitle.setSpacingAfter(5f);
        document.add(descriptionTitle);

        Paragraph descriptionContent = new Paragraph("12月收货异常,记录一次性开箱不良关键事件", normalFont);
        descriptionContent.setSpacingAfter(15f);
        document.add(descriptionContent);


        // 添加关键得分
        Paragraph scoreTitle = new Paragraph("关键得分", headerFont);
        scoreTitle.setSpacingAfter(5f);
        document.add(scoreTitle);

        Paragraph scoreContent = new Paragraph("-3分", normalFont);
        scoreContent.setSpacingAfter(15f);
        document.add(scoreContent);

        // 添加关键要求
        Paragraph requirementTitle = new Paragraph("关键要求", headerFont);
        requirementTitle.setSpacingAfter(5f);
        document.add(requirementTitle);

        Paragraph requirementContent = new Paragraph("请供应商按我司关键事件通报,提交整改方案及相关文件材料", normalFont);
        requirementContent.setSpacingAfter(15f);
        document.add(requirementContent);


        // 添加截止时间
        Paragraph deadlineTitle = new Paragraph("截止时间", headerFont);
        deadlineTitle.setSpacingAfter(5f);
        document.add(deadlineTitle);

        Paragraph deadlineContent = new Paragraph("请于2025年03月15日前组织整改回复,谢谢", normalFont);
        deadlineContent.setSpacingAfter(20f);
        document.add(deadlineContent);

        // 添加联系方式
        Paragraph contactTitle = new Paragraph("六、联系方式", headerFont);
        contactTitle.setSpacingAfter(5f);
        document.add(contactTitle);

        Paragraph contactContent = new Paragraph();
        contactContent.add(new Chunk("联系人:", headerFont));
        contactContent.add(new Chunk("123456 王峰 (创建人)", normalFont));
        contactContent.add(Chunk.NEWLINE);
        contactContent.add(new Chunk("邮箱:", headerFont));
        contactContent.add(new Chunk("chenxiaogang@xxx.com", normalFont));
        contactContent.add(Chunk.NEWLINE);
        contactContent.add(new Chunk("发通报公司:", headerFont));
        contactContent.add(new Chunk("具体梓公司", normalFont));
        contactContent.setSpacingAfter(20f);
        document.add(contactContent);

        // 添加结尾
        Paragraph ending = new Paragraph("感谢您的配合与支持,期待我们继续携手共进,实现互利共赢!此致,敬礼!", normalFont);
        ending.setSpacingAfter(10f);
        document.add(ending);

        Paragraph company = new Paragraph("********有限公司", normalFont);
        company.setAlignment(Element.ALIGN_RIGHT);
        company.setSpacingAfter(5f);
        document.add(company);

        Paragraph date = new Paragraph("日期:2025年03月07日", normalFont);
        date.setAlignment(Element.ALIGN_RIGHT);
        document.add(date);

        // 关闭文档
        document.close();
    }
    private static void addTableCell(PdfPTable table, String header, String content,
                                     Font headerFont, Font contentFont) {
        // 左边单元格(标签)
        PdfPCell headerCell = new PdfPCell(new Phrase(header + " ", headerFont));
        headerCell.setBorder(Rectangle.NO_BORDER);
        headerCell.setPaddingRight(5f); // 标签右侧内边距
        table.addCell(headerCell);

        // 右边单元格(内容)
        PdfPCell contentCell = new PdfPCell(new Phrase(content, contentFont));
        contentCell.setBorder(Rectangle.NO_BORDER);
        contentCell.setHorizontalAlignment(Element.ALIGN_LEFT); // 内容左对齐
        contentCell.setPaddingRight(15f); // 内容右侧内边距
        table.addCell(contentCell);
    }

注意事项:

  1. 您需要将logoPath变量替换为实际的logo图片路径,确保图片存在且可访问。

  2. 此代码使用了iText库,您需要在项目中添加以下依赖:

  3. <dependency>
        <groupId>com.itextpdf</groupId>
        <artifactId>itextpdf</artifactId>
        <version>5.5.13.3</version>
    </dependency>

  4. 代码中使用了中文字体"STSong-Light",这是iText自带的中文字体。如果您需要其他字体,可以指定其他支持中文的字体文件路径。

  5. 生成的PDF文件将保存在outputPath指定的路径。

  6. 如果您在Servlet环境中使用此代码,可以将logoPath设置为:

  7. String logoPath = session.getServletContext().getRealPath("/") + "/images/envicool.jpg";

http://www.dtcms.com/a/99908.html

相关文章:

  • 在Wincc中使用Dapper读写数据库
  • Go/Python(Nuitka)/Rust/Zig 技术对比
  • 记一次关于云的渗透过程
  • Git配置
  • C# 的Lambda表达式‌常见用法和示例
  • C++中常见符合RAII思想的设计有哪些
  • c++使用iconv进行字符编码格式转换
  • 小红书多账号运营:如何实现每个账号独立 IP发布文章
  • ubuntu 安装 postgresql
  • Dubbo(23)如何配置Dubbo的服务消费者?
  • 蓝桥杯_DS18B20温度传感器
  • 【Java】Java核心知识点与相应面试技巧(六)——类与对象(一)
  • 什么是CMS?常用CMS有哪些?
  • Oracle数据库数据编程SQL<2.3 DML增、删、改及merge into>
  • 【学Rust写CAD】15 定点数实现(fixed.rs)
  • CSS中的em,rem,vm,vh详解
  • PipeWire 音频设计与实现分析一——介绍
  • C# 字符串(String)
  • 前端路由守卫与后端权限验证,仅使用路由守卫是否安全?
  • docker日志大小和保存管理
  • 常用的排序算法
  • 浅析Android Jetpack ACC之ViewModel
  • vector之内存分配详解
  • 23 种设计模式中的迭代器模式
  • Three.js 快速入门教程【十九】CSS2DRenderer(CSS2D渲染器)介绍,实现场景中物体或设备标注标签信息
  • QML中刷新图片的三种方法对比分析
  • [ComfyUI] 如何升级自定义节点(Custom Nodes)
  • 计算机网络和因特网
  • AGI 的概念、意义与未来展望
  • 【AI论文】挑战推理的边界:大型语言模型的数学基准测试