itext自定义pdf

news/2024/10/23 6:01:04/

pom坐标

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

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

java">
public class CreatePdfWithIText {public static void main(String[] args) {String dest = "example.pdf";// 创建 File 对象File file = new File(dest);try {// 注册字体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");// 插入图片Image image = Image.getInstance("src/main/resources/static/lQLPJx8kenVARDfNBfrNC0CwMrMiu82UNQUG_l2o6frWAA_2880_1530.png");image.scaleToFit(100, 100); // 设置图片大小image.setAbsolutePosition(50, 750); // 设置图片位置 (x, y)// 设置透明度PdfContentByte canvas = writer.getDirectContent();PdfGState gState = new PdfGState();gState.setFillOpacity(0.5f); // 设置透明度,0.0f 完全透明,1.0f 完全不透明canvas.setGState(gState);canvas.addImage(image);pdf.add(image);// 关闭文档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 {@Overridepublic 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;}@Overridepublic 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.ppmy.cn/news/1541247.html

相关文章

go 包相关知识

在Go语言中&#xff0c;包的引用和搜索路径是由环境变量GOPATH和GO111MODULE共同决定的。 GOPATH环境变量&#xff1a;这个变量定义了默认的工作目录&#xff0c;Go命令行工具将会在这个目录下查找包文件。这个目录通常包含三个子目录&#xff1a;src、bin和pkg。 src目录包含…

解决Eclipse中’Run As’菜单缺少’Run on Server’选项的问题

解决Eclipse中’Run As’菜单缺少’Run on Server’选项的问题 问题描述&#xff1a; 当您在Eclipse中导入一个Web项目后&#xff0c;可能会发现在’Run As’菜单中没有’Run on Server’选项。这可能会让您无法方便地在本地服务器上运行和调试Web应用程序。 可能原因&#…

Qml-CheckBox的使用

Qml-CheckBox的使用 CheckBox属性 CheckBox的继承关系&#xff1a; CheckBox – AbstractButton – Control – Item; CheckBox的属性主要继承于AbstractButton。属性checkState&#xff1a;勾选状态&#xff0c;值为&#xff1a;Qt.Unchecked、Qt.Checked、Qt.PartiallyChec…

iOS弹出系统相册选择弹窗

直接上代码 if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {UIImagePickerController *imagePickerController [[UIImagePickerController alloc] init];imagePickerController.delegate self; //设置代理imagePicke…

Greenhills学习总结

学习背景&#xff1a;近期参与xx项目过程中&#xff0c;遇到较多的关于代码集成编译的知识盲区&#xff0c;因此需要进行相关知识的学习和扫盲。 参考资料&#xff1a;GreenHills2017.7编译手册:本手册是GreenHills 2017.7.14版编译器的软件使用手册。该手册详细介绍了GreenHi…

Electron+Vue实现两种方式的截屏功能

本次介绍的截屏功能一共有两种分别是在electron环境中与非electron环境中 非electron环境 这个环境下会有一些限制&#xff1a; 1.只能截浏览器中的画面 2.如果里面有iframe或者base64的图片会加载不出来&#xff08;这个会有解决办法&#xff09; yarn add -D js-web-scree…

UE5遇到问题-UE5可正常打包出来但是运行不了

遇到问题&#xff1a; UE5可正常打包出来但是运行不了 解决办法&#xff1a; 首先先在本地运行跑一下工程&#xff1b; 发现是没有关闭插件的问题&#xff0c;点开插件关闭掉相应的插件重新打包就可以了。 参考视频&#xff1a;(新手向)虚幻5打包 打包后双击exe没反应怎么办…

【Unity】Unity中获取网络时间进行每日和每月刷新

直接上代码 using System; using System.Collections; using System.Collections.Generic; using UnityEngine;public class DateChecker : MonoBehaviour {private DateTime lastCheckedDate; //上次刷新日数据的日期private DateTime lastMonthUtc; //上次刷新月数据的日期T…