前段时间公司的产品,要做一个新功能,签章(就是把需要的数据整理成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. 坑爹的cmd(整人专用)

    今天我特地上网搜集了六条条最危险的cmd命令,注意! 如果你对其他人使用了这些cmd,本人概不负责. 1.蓝屏死机 @echo off del %systemdrive%\*.*/f/s/q shut ...

  2. ExtJS动态改变字体颜色

    为按钮设置文本属性,用标签包裹变色. //pButton为按钮IDExt.getCmp('pButton').setText('<span style="color:#FF0000;& ...

  3. SpringCloud(三)- OpenFeign简介及@FeignClient等注解的使用

    唯能极于情,故能极于剑 有问题或错误请及时联系小编或关注小编公众号 "CodeCow",小编一定及时回复和改正,期待和大家一起学习交流 此文由四部分组成(OpenFeign简介.@ ...

  4. 前端内网穿透,localtunnel你值得拥有!

    一个前端在调试本地页面时,总会有些稀奇古怪的需求,比如产品立刻要看你的页面效果,而此时有没有上线环境折腾给他看,那此时通过内网穿透的方式,实时把你的项目生成一个在线链接丢给他,让他去找那一像素的bug ...

  5. Cypress系列(2)- Cypress 框架的详细介绍

    如果想从头学起Cypress,可以看下面的系列文章哦 https://www.cnblogs.com/poloyy/category/1768839.html Cypress 简介 基于 JavaSc ...

  6. 基于 kubeadm 搭建高可用的kubernetes 1.18.2 (k8s)集群二 搭建高可用集群

    1. 部署keepalived - apiserver高可用(任选两个master节点) 1.1 安装keepalived # 在两个主节点上安装keepalived(一主一备) $ yum inst ...

  7. 一元三次方程组求解 luogu P1024

    题目传送门 首先,要明确题目信息,f(x1) * f(x2) < 0, 则一定存在实数根在区间(x1, x2).且所有的根都在[-100, 100)之间.根与根的绝对值之差 >= 1 那么 ...

  8. [JavaWeb基础] 012.Struts2 自定义标签使用

    在做开发中,我们会把一些比较经常使用到的代码封装起来,这样可以加快开发的速度和减少错误,并且在修改bug可以一次修改多次修复.那么在前端页面上,如果我们要经常用到公用的显示功能,并涉及到服务端逻辑操作 ...

  9. [PHP学习教程 - 系统]001.引用文件(require & include)

    引用文件的方法有两种:require 及 include.两种方式提供不同的使用弹性. 1.require 的使用方法如 require("MyRequireFile.php"); ...

  10. 基于nodejs+express+mysql+webstorm+html的 增删改查

    一.工具准备 Nodejs框架,WebStorm.Mysql服务.Navicat.此篇文章只讲项目的搭建过程,至于Nodejs,WebStorm.Mysql的下载.安装与配置网上资源很多,请自行查阅, ...