前段时间公司的产品,要做一个新功能,签章(就是把需要的数据整理成PDF很标准的文件,然后在盖上我们在服务器上面的章)

然后我就在百度上找了找,发现搞PDF的类库很少,要么就要钱,要么就有水印,破解版的没找到。

先讲一讲我是怎么生成PDF的

1、生成PDF

  这里用到了 Spire.Pdf    这个类库可以在NuGet里面搜索到,上面带个小红标的就是免费版本。  

  当然也可以去他们的官网,上面还有文档(https://www.e-iceblue.cn/Introduce/Spire-PDF-NET.html)。

  代码(这是我自己写的一个测试的表格)

  

        public static void abc()
{
//创建PDF文档
Spire.Pdf.PdfDocument doc = new Spire.Pdf.PdfDocument(); //添加一页
PdfPageBase page = doc.Pages.Add();
    //设置字体
PdfTrueTypeFont font = new PdfTrueTypeFont(new System.Drawing.Font("Microsoft Yahei", 20f), true);
PdfTrueTypeFont font1 = new PdfTrueTypeFont(new System.Drawing.Font("Microsoft Yahei", 11f), true); //创建一个PdfGrid对象
PdfGrid grid = new PdfGrid();         //这一段的内容是在表格只玩显示一些数据 根据坐标定位 第一个是内容,第二个是字体,第三个是颜色,第四第五是坐标
page.Canvas.DrawString("XXXXXXXX管理中心回单",
font,
new PdfSolidBrush(System.Drawing.Color.Black), , );
page.Canvas.DrawString("编号:31231",
font1,
new PdfSolidBrush(System.Drawing.Color.Black), , );
page.Canvas.DrawString("经办人:XXXX",
font1,
new PdfSolidBrush(System.Drawing.Color.Black), , );
page.Canvas.DrawString("打印日期:2020/06/15",
font1,
new PdfSolidBrush(System.Drawing.Color.Black), , );
//设置单元格边距
grid.Style.CellPadding = new PdfPaddings(, , , ); //设置表格默认字体
grid.Style.Font = new PdfTrueTypeFont(new System.Drawing.Font("Microsoft Yahei", 12f), true); //添加4行4列
PdfGridRow row1 = grid.Rows.Add();
PdfGridRow row2 = grid.Rows.Add();
PdfGridRow row3 = grid.Rows.Add();
PdfGridRow row4 = grid.Rows.Add();
PdfGridRow row5 = grid.Rows.Add();
PdfGridRow row6 = grid.Rows.Add();
grid.Columns.Add(); //设置列宽
foreach (PdfGridColumn col in grid.Columns)
{
col.Width = 120f;
} //写入数据 第一行第一个格式的值,第一行第二个格子的值
row1.Cells[].Value = "收款单位";
row1.Cells[].Value = "{DW}";
row2.Cells[].Value = "收款单位";
row2.Cells[].Value = "{DW}";
row3.Cells[].Value = "汇款时间";
row3.Cells[].Value = "2016/06/02";
row3.Cells[].Value = "金额小写";
row3.Cells[].Value = "¥231";
row4.Cells[].Value = "金额合计大写";
row4.Cells[].Value = "大苏打实打实";
row5.Cells[].Value = "用途:" +
"付XXXX2020年04月至2020年04月";
row6.Cells[].Value = "提示:回单可重复打印,请勿重复XXX"; //row5.Cells[0].Height = (float)20;
//水平和垂直合并单元格 从那个格子开始合并几个(包含当前格子)
row1.Cells[].ColumnSpan = ;
row2.Cells[].ColumnSpan = ;
row4.Cells[].ColumnSpan = ;
row5.Cells[].ColumnSpan = ;
row5.Cells[].ColumnSpan = ;
row6.Cells[].ColumnSpan = ;
row6.Cells[].ColumnSpan = ;
        //这个是垂直合并,但是我之前合并的没有效果
row5.Cells[].RowSpan = ; //设置单元格内文字对齐方式
row1.Cells[].StringFormat = new PdfStringFormat(PdfTextAlignment.Center);
row1.Cells[].StringFormat = new PdfStringFormat(PdfTextAlignment.Center);
row2.Cells[].StringFormat = new PdfStringFormat(PdfTextAlignment.Center);
row2.Cells[].StringFormat = new PdfStringFormat(PdfTextAlignment.Center);
row3.Cells[].StringFormat = new PdfStringFormat(PdfTextAlignment.Center);
row3.Cells[].StringFormat = new PdfStringFormat(PdfTextAlignment.Center);
row3.Cells[].StringFormat = new PdfStringFormat(PdfTextAlignment.Center);
row3.Cells[].StringFormat = new PdfStringFormat(PdfTextAlignment.Center);
row4.Cells[].StringFormat = new PdfStringFormat(PdfTextAlignment.Center);
row4.Cells[].StringFormat = new PdfStringFormat(PdfTextAlignment.Center);
row5.Cells[].StringFormat = new PdfStringFormat(PdfTextAlignment.Center);
row6.Cells[].StringFormat = new PdfStringFormat(PdfTextAlignment.Center);
//设置单元格背景颜色
//row1.Cells[0].Style.BackgroundBrush = PdfBrushes.Gray;
//row3.Cells[3].Style.BackgroundBrush = PdfBrushes.Green;
//row4.Cells[3].Style.BackgroundBrush = PdfBrushes.MediumVioletRed; //设置边框颜色、粗细
PdfBorders borders = new PdfBorders();
borders.All = new PdfPen(System.Drawing.Color.Black, 0.1f);
foreach (PdfGridRow pgr in grid.Rows)
{
foreach (PdfGridCell pgc in pgr.Cells)
{
pgc.Style.Borders = borders;
}
}
//保存到文档
//在指定为绘入表格
grid.Draw(page, new PointF(, ));
doc.SaveToFile(@"路径");
       //这句是在浏览器重打开这个PDF  
System.Diagnostics.Process.Start(@"路径");
}

  保存我们看一下

  

2、之后就是关于PDF一些转换的操作了(PDF转base64,转图片之类的,我把代码贴到下面)

  • 这个用到了iTextSharp类库,也可以在Nuget下载到
/// <summary>
/// 图片转pdf
/// </summary>
/// <param name="jpgfile"></param>
/// <param name="pdf"></param>
public static bool ConvertJPG2PDF(string jpgfile, string pdf)
{
try
{
var document = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4, , , , );
using (var stream = new FileStream(pdf, FileMode.Create, FileAccess.Write, FileShare.None))
{
PdfWriter.GetInstance(document, stream);
document.Open();
using (var imageStream = new FileStream(jpgfile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
var image = iTextSharp.text.Image.GetInstance(imageStream);
if (image.Height > iTextSharp.text.PageSize.A4.Height - )
{
image.ScaleToFit(iTextSharp.text.PageSize.A4.Width - , iTextSharp.text.PageSize.A4.Height - );
}
else if (image.Width > iTextSharp.text.PageSize.A4.Width - )
{
image.ScaleToFit(iTextSharp.text.PageSize.A4.Width - , iTextSharp.text.PageSize.A4.Height - );
}
image.Alignment = iTextSharp.text.Image.ALIGN_MIDDLE;
document.NewPage();
document.Add(image);
}
document.Close();
} return true; }
catch (Exception ex)
{
throw ex;
}
}
  • 这个用的是(O2S.Components.PDFRender4NET)
/// <summary>
/// pdf转img
/// </summary>
/// <param name="path">pdf位置</param>
/// <param name="path2">img位置</param>
public static void Pdf2Img(string path, string path2)
{
PDFFile pdfFile = PDFFile.Open(path);
//实例化一个PdfDocument类对象,并加载PDF文档
using (Spire.Pdf.PdfDocument doc = new Spire.Pdf.PdfDocument())
{
doc.LoadFromFile(path);
//调用方法SaveAsImage()将PDF第一页保存为Bmp格式
System.Drawing.Image bmp = doc.SaveAsImage();
// //调用另一个SaveAsImage()方法,并将指定页面保存保存为Emf、Png
System.Drawing.Image emf = doc.SaveAsImage(, Spire.Pdf.Graphics.PdfImageType.Bitmap);
System.Drawing.Image zoomImg = new Bitmap((int)(emf.Size.Width * ), (int)(emf.Size.Height * ));
using (Graphics g = Graphics.FromImage(zoomImg))
{
g.ScaleTransform(2.0f, 2.0f);
g.DrawImage(emf, new System.Drawing.Rectangle(new System.Drawing.Point(, ), emf.Size), new System.Drawing.Rectangle(new System.Drawing.Point(, ), emf.Size), GraphicsUnit.Pixel);
zoomImg.Save(path2, ImageFormat.Jpeg); zoomImg.Dispose();
emf.Dispose();
bmp.Dispose();
}
doc.Close();
doc.Dispose();
} }
  • 这个和上面用的也是同一个(我觉得这个比较好用一些)
/// <summary>
        /// 将PDF文档转换为图片的方法
        /// </summary>
        /// <param name="pdfInputPath">PDF文件路径</param>
        /// <param name="imageOutputPath">图片输出路径</param>
        /// <param name="imageName">生成图片的名字</param>
        /// <param name="startPageNum">从PDF文档的第几页开始转换</param>
        /// <param name="endPageNum">从PDF文档的第几页开始停止转换</param>
        /// <param name="imageFormat">设置所需图片格式</param>
        /// <param name="definition">设置图片的清晰度,数字越大越清晰</param>
public static void ConvertPDF2Image(string pdfInputPath, string imageOutputPath,
string imageName, int startPageNum, int endPageNum, ImageFormat imageFormat, Definition definition)
{
PDFFile pdfFile = null;
FileStream fs = null;
try
{
fs = new FileStream(pdfInputPath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite);
pdfFile = PDFFile.Open(fs); if (startPageNum <= )
{
startPageNum = ;
}
if (endPageNum > pdfFile.PageCount)
{
endPageNum = pdfFile.PageCount;
}
if (startPageNum > endPageNum)
{
int tempPageNum = startPageNum;
startPageNum = endPageNum;
endPageNum = startPageNum;
}
string path = imageOutputPath + imageName + "" + "." + imageFormat.ToString();
Logger.WriteLogs("PDFIMG:" + path);
using (Bitmap pageImage = pdfFile.GetPageImage(, * (int)definition))
{
if (File.Exists(path))
{
using (FileStream f = new FileStream(path, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite))
{
pageImage.Save(f, ImageFormat.Jpeg);
pageImage.Dispose();
}
}
}
fs.Flush();
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
finally
{
if (pdfFile != null)
{
pdfFile.Dispose();
}
else if (fs != null)
{
fs.Close();
fs.Dispose();
}
}
} public enum Definition
{
One = , Two = , Three = , Four = , Five = , Six = , Seven = , Eight = , Nine = , Ten =
}
  • PDF转Base64
  •         /// <summary>
    /// pdf转base64
    /// </summary>
    /// <param name="filePath"></param>
    /// <returns></returns>
    public static string PdfWord_To_Base64(string filePath)
    {
    try
    {
    if (!string.IsNullOrWhiteSpace(filePath.Trim()))
    { FileStream fileStream = new FileStream(filePath, FileMode.OpenOrCreate);
    byte[] bt = new byte[fileStream.Length];
    fileStream.Read(bt, , bt.Length);
    fileStream.Close();
    fileStream.Dispose();
    return Convert.ToBase64String(bt);
    }
    else
    {
    return "请输入正确的路径";
    } }
    catch (Exception ex)
    {
    throw ex;
    }
    }

    我主要也就用到这些,之后在发现,我在网上加

.Net 对于PDF生成以及各种转换的操作的更多相关文章

  1. 赞!jsPDF – 基于 HTML5 的强大 PDF 生成工具

    jsPDF 是一个基于 HTML5 的客户端解决方案,用于生成各种用途的 PDF 文档.使用方法很简单,只要引入 jsPDF 库,然后调用内置的方法就可以了.浏览器兼容性: IE 10, Firefo ...

  2. PDF创建及动态转换控件程序包ActivePDF Portfolio

    ActivePDF Portfolio是将4个activePDF最优秀的服务器产品捆绑成一个价格适中的控件程序包.它提供了开发一个完整的服务器端的PDF解决方案所需的一切. 具体功能: activeP ...

  3. keytool和openssl生成的证书转换

    keytool和openssl生成的证书转换 keytool生成证书示例 生成私钥+证书: keytool -genkey -alias client -keysize 2048 -validity ...

  4. jsPDF – 基于 HTML5 的强大 PDF 生成工具

    jsPDF 是一个基于 HTML5 的客户端解决方案,用于生成各种用途的 PDF 文档. 使用方法很简单,只要引入 jsPDF 库,然后调用内置的方法就可以了. 米扑科技项目用到了HHTML5生成PD ...

  5. Spark RDD基本概念、宽窄依赖、转换行为操作

    目录 RDD概述 RDD的内部代码 案例 小总结 转换.行动算子 宽.窄依赖 Reference 本文介绍一下rdd的基本属性概念.rdd的转换/行动操作.rdd的宽/窄依赖. RDD:Resilie ...

  6. PDF.NET数据开发框架实体类操作实例

    PDF.NET数据开发框架实体类操作实例(MySQL)的姊妹篇,两者使用了同一个测试程序,不同的只是使用的类库和数据库不同,下面说说具体的使用过程. 1,首先在App.config文件中配置数据库连接 ...

  7. iBatis——自动生成DAO层接口提供操作函数(详解)

    iBatis——自动生成DAO层接口提供操作函数(详解) 在使用iBatis进行持久层管理时,发现在使用DAO层的updateByPrimaryKey.updateByPrimaryKeySelect ...

  8. pdf生成

    要用本文的方法生成PDF文件,需要两个控件:itextsharp.dll和ICSharpCode.SharpZipLib.dll,由于示例代码实在太多,我将代码全部整理出来,放在另外一个文件“示例代码 ...

  9. pdf生成(itextSharp)

    最近在工作中遇到一个问题,客户要求将系统中的表格全部导出成PDF格式.经过搜索,基本是三种思路: 直接用byte写PDF文件.(算你狠,霸王硬上弓) 通过Com组件转换.以Adobe Acrobat为 ...

随机推荐

  1. Istio ServiceEntry 引入外部服务

    概念及示例 使用服务入口Service Entry来添加一个入口到 Istio 内部维护的服务注册中心.添加了服务入口后,Envoy 代理可以向服务发送流量,就好像它是网格内部的服务一样.配置服务入口 ...

  2. 关于docker的常见使用命令

    1. Docker的启动与停止 systemctl命令是系统服务管理器指令 启动docker: systemctl start docker 停止docker: systemctl stop dock ...

  3. day20 函数闭包与装饰器

    装饰器:本质就是函数,功能是为其他函数添加新功能 原则: 1.不修改被装饰函数的源代码(开放封闭原则) 2.为被装饰函数添加新功能后,不修改被修饰函数的调用方式 装饰器的知识储备: 装饰器=高阶函数+ ...

  4. Istio Polit-agent & Envoy 启动流程

    开篇 通过上一篇 Istio Sidecar注入原理 文章可以发现,在应用提交到kubernate部署时已经同时注入了Sidecar应用. 细心的话应该还可以发现,除了注入了istio-proxy应用 ...

  5. 7z命令行简单使用

    7z命令行简单使用 网上有很多博客都有记录7z的命令行使用方式,但看起来乱起八糟的,不知所云. 急于使用者可以直接看实例 注:我仅仅记录我认为常用的命令,毕竟没有那么多的精力去学习不常用的东西. 简介 ...

  6. axios发送post form请求

    axios发送post form请求 只需修改url和data即可 axios({ url: '/user', method: 'post', data: { firstName: 'Fred', l ...

  7. Rocket - debug - TLDebugModule

    https://mp.weixin.qq.com/s/EhUb1z5oiIw6dJ-90ifDJA 简单介绍TLDebugModule中的实现. 1. device device是一个设备描述符,包含 ...

  8. Rocket - debug - TLDebugModuleInner - Abstract Command State Machine

    https://mp.weixin.qq.com/s/RcXI8uEHvZHGCvX3DoVR4Q 简单介绍TLDebugModuleInner中处理抽象命令时的状态机. 1. CtrlState 定 ...

  9. URL跳转与钓鱼

    从登录页跳转到另一个页面就叫做URL跳转. 1.URL跳转 URL跳转一般分为两种,(1)客户端跳转:(2)服务端跳转.对用户来说,两种跳转都是透明的,都是指向或者跳转到另一个页面,页面发生了改变.但 ...

  10. doReleaseShared源码分析及唤醒后继节点的过程分析

    文章结构 源码:对doReleaseShared()方法的源码进行一些注释 使用场景:介绍doReleaseShared()使用位置,及目的 以写锁开始的队列:分析写锁开始得同步等待队列在唤醒后续读锁 ...