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

itext自定义pdf

pom坐标

<!-- https://mvnrepository.com/artifact/com.itextpdf/itextpdf -->
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itextpdf</artifactId>
            <version>5.5.13.3</version>
        </dependency>

字体文件可以再电脑系统中复制

package com.example.demo.PacketCapture;

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

import java.awt.*;
import java.io.*;

public class CreatePdfWithIText {

    public static void main(String[] args) {
        String dest = "example.pdf";
        // 创建 File 对象
        File file = new File(dest);
        try {
            // 注册字体
//            BaseFont baseFont = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
//            BaseFont baseFont = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.NOT_EMBEDDED);
            BaseFont baseFont = BaseFont.createFont("src/main/resources/static/STFANGSO.TTF", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);

            Font font = new Font(baseFont, 12, Font.NORMAL);



            // 创建输出流
            FileOutputStream fileOutputStream = new FileOutputStream(file);
            // 创建 Document 对象
            Document pdf = new Document();
            // 创建 PdfWriter 对象
            PdfWriter writer = PdfWriter.getInstance(pdf, fileOutputStream);

            // 添加页面事件监听器(例如,添加页眉和页脚)
            writer.setPageEvent(new HeaderFooterPageEvent());

            // 打开文档
            pdf.open();

            // 添加标题
            pdf.add(new Paragraph("     测试1111",font));

            // 添加段落
            pdf.add(new Paragraph("This is an example of a PDF document created using iText."));
            pdf.add(new Paragraph(" "));
            // 添加表格
            PdfPTable table = new PdfPTable(3);
            PdfPCell cell = new PdfPCell(new Paragraph("Header 1",font));

            table.addCell(cell);
            table.addCell("Header 2");
            table.addCell("Header 3");
            table.addCell("Row 1, Cell 1");
            table.addCell("Row 1, Cell 2");
            table.addCell("Row 1, Cell 3");


            // 合并单元格
            PdfPCell mergedCell = new PdfPCell(new Paragraph("Merged Cell"));
            mergedCell.setCellEvent(new GradientBackgroundEvent(mergedCell,BaseColor.BLUE, BaseColor.WHITE,writer));
            mergedCell.setColspan(2); // 合并两列
            mergedCell.setHorizontalAlignment(Element.ALIGN_CENTER);//内容居中

            table.addCell(mergedCell);
            table.addCell(new PdfPCell(new Paragraph("测试数据23车上",font)));
            table.completeRow();

            pdf.add(table);


            // 添加带下划线的文字
            Chunk underlinedChunk = new Chunk("测试数据.",font);
            underlinedChunk.setUnderline(0.1f, -2f); // 设置下划线的粗细和位置
            Phrase underlinedPhrase = new Phrase(underlinedChunk);
            pdf.add(new Paragraph(underlinedPhrase));

            // 添加书签
            PdfOutline root = writer.getRootOutline();
            PdfOutline bookmark1 = new PdfOutline(root, new PdfDestination(PdfDestination.FITH, pdf.getPageSize().getTop(pdf.getPageSize().getHeight() - 72)), "Title 1");
            PdfOutline bookmark2 = new PdfOutline(bookmark1, new PdfDestination(PdfDestination.FITH, pdf.getPageSize().getTop(pdf.getPageSize().getHeight() - 144)), "Sub-title 1.1");

            // 关闭文档
            pdf.close();

            System.out.println("PDF created successfully.");

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (DocumentException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    // 自定义页面事件监听器
    static class HeaderFooterPageEvent extends PdfPageEventHelper {
        @Override
        public void onEndPage(PdfWriter writer, Document document) {
            PdfContentByte cb = writer.getDirectContent();
            cb.beginText();
            try {
                cb.setFontAndSize(BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.NOT_EMBEDDED), 12);
            } catch (DocumentException e) {
                throw new RuntimeException(e);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            cb.showTextAligned(PdfContentByte.ALIGN_CENTER, "Header", document.right()/2 , document.top() + 10, 0);
            cb.showTextAligned(PdfContentByte.ALIGN_CENTER, "Footer", document.right()/2, document.bottom() - 10, 0);
            cb.endText();
        }
    }

    // 自定义渐变色背景事件
    static class GradientBackgroundEvent implements PdfPCellEvent {
        private BaseColor startColor;
        private BaseColor endColor;
        private PdfWriter writer;
        private PdfPCell rectangleItem;

        public GradientBackgroundEvent(PdfPCell rectangleItem,BaseColor startColor, BaseColor endColor, PdfWriter writer) {
            this.startColor = startColor;
            this.endColor = endColor;
            this.writer = writer;
            this.rectangleItem = rectangleItem;
        }

        @Override
        public void cellLayout(PdfPCell cell, Rectangle position, PdfContentByte[] canvases) {
            PdfShading shading = PdfShading.simpleAxial(
                    this.writer,
                    position.getLeft(), position.getBottom(),
                    position.getRight(), position.getTop(),
                    startColor, endColor
            );
            PdfShadingPattern pattern = new PdfShadingPattern(shading);
            PdfGState gstate = new PdfGState();
            gstate.setFillOpacity(0.5f);//不透明度
            canvases[PdfPTable.BACKGROUNDCANVAS].saveState();
            canvases[PdfPTable.BACKGROUNDCANVAS].setGState(gstate);
            canvases[PdfPTable.BACKGROUNDCANVAS].setShadingFill(pattern);//命中单元格,仅填充单元格填充
            canvases[PdfPTable.BACKGROUNDCANVAS].paintShading(pattern);//整个文档的填充
            canvases[PdfPTable.BACKGROUNDCANVAS].setShadingStroke(pattern);// 颜色灰色,仅单元格填充
            canvases[PdfPTable.BACKGROUNDCANVAS].rectangle(position.getLeft(), position.getBottom(), position.getWidth(), position.getHeight());
            canvases[PdfPTable.BACKGROUNDCANVAS].fill();
            canvases[PdfPTable.BACKGROUNDCANVAS].restoreState();
        }
    }
}

http://www.kler.cn/news/360223.html

相关文章:

  • 【Python实战】---- 自动生成前端项目图标管理文件
  • windows安装mysql,跳过自定义的密码验证
  • 【力扣打卡系列】滑动窗口与双指针(两数之和)
  • “射线沿其正向平移可变为其真子集”这一中学“常识”其实是几百年重大错误——百年病态集论的症结
  • 【Qt】绘图API
  • YashanDB学习-服务启停
  • 【Java 22 | 7】 深入解析Java 22 :密封类(Sealed Classes)增强详解
  • LTD助力经营数字化,浙商数智营销学堂开讲入站营销新理念
  • 【视频编码】视频编码中拉格朗日乘子法的简单理解
  • 基于SSM+微信小程序的家庭记账本管理系统(家庭1)
  • 08_实现 reactive
  • DAPLINK 源码学习(1)BL 之 main() 函数
  • typescript 的类型注解和类型断言
  • C#学习笔记(十)
  • 拥抱“新市民” ,数字银行的“谋与变”
  • jetson agx orin 的pytorch、torchvision安装
  • el-table表格数据处理,列表将变更前数据放置在前面,变更后数据放在表格后面
  • 第1篇:计算机网络概述与基础
  • 【小白学机器学习15】 概率论的世界观
  • Web,RESTful API 在微服务中的作用是什么?