当前位置:网站首页>C#实战:基于ItextSharp技术标签生成小工具
C#实战:基于ItextSharp技术标签生成小工具
2022-08-10 10:27:00 【IT技术分享社区】
目录
今天给大家分享小编基于ItextSharp制作的一款标签生成小工具,可供大家学习或者二次开发满足实际的需求使用。
使用技术:C#+ItextSharp+Winfrom+Net4.0
1、运行主界面
运行主界面根据窗体输入相应的内容,点击生成pdf按钮会生成对应的pdf文件。
2、标签生成界面
生成的标签pdf文件效果如下图
3、需要引入的依赖包
开发的时候需要导入以下两个包
iTextSharp 版本为5.5.13.13
QRCoder 版本为1.4.3
4、解决方案目录
5、主要代码
1、新建PdfUtils工具类
class PdfUtils {
const string ITextExamplesFolder = "iTextExamples"; const string ResourcesFolder = "resources"; public static string Author => "haogm"; public static string GetBaseDir() {
return Environment.CurrentDirectory; } /// <summary> /// 创建列 插入文本内容 /// </summary> /// <param name="table"></param> /// <param name="content"></param> /// <param name="font"></param> /// <param name="minimumHeight"></param> /// <param name="colspan"></param> /// <param name="rowspan"></param> public static void CreateCell(PdfPTable table, string content, Font font, int minimumHeight = 20, int colspan = 0, int rowspan = 0) {
var cell = new PdfPCell(new Phrase(content, font)); cell.UseAscender = true;// 设置可以居中 cell.MinimumHeight = minimumHeight;// 设置单元格高度 cell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;// 设置水平居中 cell.VerticalAlignment = PdfPCell.ALIGN_MIDDLE;// 设置垂直居中 if (rowspan != 0) {
cell.Rowspan = rowspan; //行合并 } if (colspan != 0) {
cell.Colspan = colspan; //列合并 } table.AddCell(cell); } /// <summary> /// 创建列 插入图片 /// </summary> /// <param name="table"></param> /// <param name="image"></param> /// <param name="minimumHeight"></param> /// <param name="colspan"></param> /// <param name="rowspan"></param> public static void CreateCell(PdfPTable table, Image image, int minimumHeight = 3, int colspan = 0, int rowspan = 0) {
var cell = new PdfPCell(image,true);// 是否填充 cell.Padding = 5.5f; // 设置二维码在单元格中的边距 cell.UseAscender = true;// 设置可以居中 cell.MinimumHeight = minimumHeight;// 设置单元格高度 cell.HorizontalAlignment = Element.ALIGN_CENTER;// 设置水平居中 cell.VerticalAlignment = Element.ALIGN_MIDDLE;// 设置垂直居中 if (rowspan != 0) {
cell.Rowspan = rowspan; //行合并 } if (colspan != 0) {
cell.Colspan = colspan; //列合并 } table.AddCell(cell); } //生成二维码的路径 public static string GetQRFileName() {
return Path.Combine(GetOutputFolder(), $"Qr.jpg"); } public static string GetOutputFolder() {
var dir = Path.Combine(GetBaseDir(), "bin", "out"); if (!Directory.Exists(dir)) {
Directory.CreateDirectory(dir); } return dir; } public static string GetOutputFolderPdf() {
var dir = Path.Combine(GetBaseDir(), "bin", "outpdf\\"); if (!Directory.Exists(dir)) {
Directory.CreateDirectory(dir); } return dir; } /// <summary> /// 验证pdf文件 /// </summary> /// <param name="file"></param> public static void VerifyPdfFileIsReadable(byte[] file) {
PdfReader reader = null; try {
reader = new PdfReader(file); var author = reader.Info["Author"] as string; if (string.IsNullOrWhiteSpace(author) || !author.Equals(Author)) {
throw new InvalidPdfException("This is not a valid PDF file."); } } finally {
reader?.Close(); } } public static void VerifyPdfFileIsReadable(string filePath) {
VerifyPdfFileIsReadable(File.ReadAllBytes(filePath)); } }
2、Form1.cs 窗体主要代码
/// <summary> /// 导出生成标签 /// </summary> /// <returns></returns> public bool ExportReceipt() {
try {
// 生成二维码的内容 string strCode = ""; StringBuilder sb = new StringBuilder(); sb.Append(txtName.Text); sb.Append("$"); sb.Append(txtName.Text); sb.Append("$"); sb.Append(txtAge.Text); sb.Append("$"); sb.Append(txtAddress.Text); sb.Append("$"); sb.Append(txtNation.Text); sb.Append("$$"); sb.Append(txtQQ.Text); sb.Append("$"); strCode = sb.ToString(); QRCodeGenerator qrGenerator = new QRCoder.QRCodeGenerator(); QRCodeData qrCodeData = qrGenerator.CreateQrCode(strCode, QRCodeGenerator.ECCLevel.Q); QRCode qrcode = new QRCode(qrCodeData); // GetGraphic 第一个参数设置图形的大小 Bitmap qrCodeImage = qrcode.GetGraphic(3, Color.Black, Color.White, null, 15, 1, false); MemoryStream ms = new MemoryStream(); qrCodeImage.Save(ms, ImageFormat.Jpeg); // 保存图片 var ImgPath = PdfUtils.GetQRFileName(); qrCodeImage.Save(ImgPath); // 保存pdf文件 var pdfFilePath = PdfUtils.GetOutputFolderPdf() + DateTime.Now.ToString("yyyyMMddHHmmss") + ".pdf"; if (File.Exists(Path.GetFullPath(pdfFilePath))) {
File.Delete(Path.GetFullPath(pdfFilePath)); } var fileStream = new FileStream(pdfFilePath, FileMode.Create); //var pdfDoc = new Document(PageSize.A4); var pdfDoc = new Document(new iTextSharp.text.Rectangle(226.4f, 169.8f)); // 80*60 mm var pdfWriter = PdfWriter.GetInstance(pdfDoc, fileStream); pdfDoc.SetMargins(0.2f, 0.2f, 3.2f, 0.2f); pdfDoc.AddAuthor(PdfUtils.Author); pdfDoc.Open(); // 中文字体,解决中文不能显示问题 BaseFont bfChinese = BaseFont.CreateFont("C:\\WINDOWS\\FONTS\\SIMSUN.TTC,0", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED); // 五号 iTextSharp.text.Font fiveFont = new iTextSharp.text.Font(bfChinese, 8f); // 五号 10.5f 小三号 15 iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(ImgPath); // 新建表格 3列. PdfPTable table0 = new PdfPTable(3) {
WidthPercentage = 98,// 宽度100%填充, }; table0.DefaultCell.VerticalAlignment = Element.ALIGN_CENTER; // 设置列宽 float[] columnWidths0 = { 0.4f, 0.8f, 0.8f }; table0.SetWidths(columnWidths0); //正文第1行 PdfUtils.CreateCell(table0, "姓名", fiveFont); PdfUtils.CreateCell(table0, txtName.Text, fiveFont); PdfUtils.CreateCell(table0, image, 30, 0, 5); PdfUtils.CreateCell(table0, "学历", fiveFont); PdfUtils.CreateCell(table0, txtEducation.Text, fiveFont); PdfUtils.CreateCell(table0, "年龄", fiveFont); PdfUtils.CreateCell(table0, txtAge.Text, fiveFont); PdfUtils.CreateCell(table0, "地址", fiveFont); PdfUtils.CreateCell(table0, txtAddress.Text, fiveFont); PdfUtils.CreateCell(table0, "民族", fiveFont); PdfUtils.CreateCell(table0, txtNation.Text, fiveFont); PdfUtils.CreateCell(table0, "QQ号", fiveFont); PdfUtils.CreateCell(table0, txtQQ.Text, fiveFont,0,2); pdfDoc.Add(table0); pdfDoc.Close(); fileStream.Dispose(); PdfUtils.VerifyPdfFileIsReadable(pdfFilePath); //直接打开pdf文件 System.Diagnostics.Process.Start(pdfFilePath); return true; } catch (Exception ex) {
return false; } }
代码地址:https://gitee.com/hgm1989/itext-sharp-demo
边栏推荐
猜你喜欢
mysql5.7 installation and deployment - yum installation
【C语言】浮点数四舍五入
leetcode:334. 递增的三元子序列
谷歌数据中心发生“电力事故”造成 3 人受伤
"Chief Engineer" Principal (Principal) engineer's way of training
[Concept of Theory of Knowledge] "Progress in the Theory of Reason" University of Leuven 2022 latest 220-page doctoral dissertation
owl.carousel poster card Slider carousel switch
技能大赛训练题:组策略一
快速上手,征服三种不同分布式架构调用方案
文本选中圆角样式border-radius
随机推荐
什么是抽象类
dedecms supports one-click upload of Word content
关于json转换器缺失的问题,报错内容:No converter found for return value of type
数据库的约束
what is rtems
【C语言】浮点数四舍五入
"MySQL Advanced Chapter" 6. Principles of index creation and design
The web project accesses static resources inside the reference jar
ES复杂操作搜索
database transaction
开发模式对测试的影响
bus event bus use
越折腾越好用的 3 款开源 APP
3D rotating text animation js special effects
8月份DB-Engines 数据库排行榜最新战况
Dalian University of Technology & Pengcheng & UAE propose a mixed-scale triple network ZoomNet for camouflaged target detection, with SOTA performance!
Redis (six) - transaction and lock mechanism of Redis6 (unfinished, to be supplemented)
Swin Transformer作者曹越加入智源,开展视觉基础模型研究
兼容移动和PC的loading加载和toast消息插件
网络安全笔记6——数字证书与公钥基础设施