ITextSharp 使用
ITextSharp是一个在C#平台下操作pdf的一个工具dll
但是,自从4.1.6版本之后的ITextSharp的license变成了AGPL,所以不能商用。所以说version 4.1.6就是目前为止可以商用的最新版本
所以让我们下载4.1.6版本的ITextSharp,然后把它加载到我们的工程之中来。
1. ITextSharp操作文本域
我们经常遇到这种需求:使用一个pdf模板,填充上数据,最后导出一个填充好数据的pdf
ITextSharp可以很好的解决这个问题,
第一步,先用Adobe Acrobat做好模板(具体步骤请自行google)
第二步,使用ITextSharp来填充模板中的文本域
这里,提供一个我自己写的共同方法
private void MakeEnPdf(string pdfTemplate, string tempFilePath, Dictionary<string, string> parameters){PdfReader pdfReader = null;PdfStamper pdfStamper = null;try{//When the temp file already exists, delete it.if (File.Exists(tempFilePath)){File.Delete(tempFilePath);}pdfReader = new PdfReader(pdfTemplate);pdfStamper = new PdfStamper(pdfReader, new FileStream(tempFilePath, FileMode.Create));// Get the collection of domain.AcroFields pdfFormFields = pdfStamper.AcroFields;//pdfFormFields.GenerateAppearances = false;pdfStamper.FormFlattening = true;// Set value for the required domain.foreach (KeyValuePair<string, string> parameter in parameters){if (pdfFormFields.Fields[parameter.Key] != null){pdfFormFields.SetField(parameter.Key, parameter.Value);}}}catch (Exception ex){throw ex;}finally{pdfStamper.Close();pdfReader.Close();pdfStamper = null;pdfReader = null;}}
其中, pdfTemplate是template的路径,tempFilePath是要生成的pdf的路径,parameters是一个词典,
使用这个共同方法可以参考如下代码
#region Create temporary pdf file without imagesvar tempGuid = Guid.NewGuid().ToString();var tempFileName = "Product_Data_Sheet_template_2016_Base_" + tempGuid + ".pdf";var tempFilePath = Path.Combine(tempUserFolder, tempFileName);MakeEnPdf(pdfTemplate, tempFilePath, parameters);#endregion
2. ITextSharp添加图片
这个地方,相信大家都可以搜索到一个很好的网址 http://www.mikesdotnetting.com/article/87/itextsharp-working-with-images
基本的操作这里说的比较完全了,但是有一个方面他没有说到,就是: 在pdf的一个rectangle里面放置图片,这个地方我提供一下我的解决思路
首先要得到rectangle的位置信息及它的大小,提供一个类
public class CanvasContainerRectangle{public CanvasContainerRectangle(float startX, float startY, float rectWidth, float rectHeight){this.StartX = startX;this.StartY = startY;this.RectWidth = rectWidth;this.RectHeight = rectHeight;}public float StartX { get; set; }public float StartY { get; set; }public float RectWidth { get; set; }public float RectHeight { get; set; }}
我们在把图片放置在container里面的时候,需要把图片进行缩放,我们需要得到这个缩放的百分比
private float GetPercentage(float width, float height, CanvasContainerRectangle containerRect){float percentage = 0;if(height > width){percentage = containerRect.RectHeight / height;if(width * percentage > containerRect.RectWidth){percentage = containerRect.RectWidth / width;}}else{percentage = containerRect.RectWidth / width;if(height * percentage > containerRect.RectHeight){percentage = containerRect.RectHeight / height;}}return percentage;}
最后调用方法PutImages把图片加载到pdf之中
public class PdfImage{public PdfImage(string imageUrl, float fitWidth, float fitHeight, float absolutX, float absoluteY, bool scaleParent){this.ImageUrl = imageUrl;this.FitWidth = fitWidth;this.FitHeight = fitHeight;this.AbsoluteX = absolutX;this.AbsoluteY = absoluteY;this.ScaleParent = scaleParent;}public PdfImage(string imageUrl, float fitWidth, float fitHeight, float absolutX, float absoluteY, bool scaleParent, byte[] imgBytes){this.ImageUrl = imageUrl;this.FitWidth = fitWidth;this.FitHeight = fitHeight;this.AbsoluteX = absolutX;this.AbsoluteY = absoluteY;this.ScaleParent = scaleParent;this.ImgBytes = imgBytes;}public string ImageUrl { get; set; }public float FitWidth { get; set; }public float FitHeight { get; set; }public float AbsoluteX { get; set; }public float AbsoluteY { get; set; }public byte[] ImgBytes { get; set; }public bool ScaleParent { get; set; }public CanvasContainerRectangle ContainerRect { get; set; }}
/// <summary>/// Create a pdf with images putting/// </summary>/// <param name="tempFilePath">The source pdf file</param>/// <param name="createdPdfPath">The destination pdf file which will be created</param>/// <param name="pdfImages">Images list</param>private void PutImages(string tempFilePath, string createdPdfPath, List<PdfImage> pdfImages){PdfReader pdfReader = null;PdfStamper pdfStamper = null;try{pdfReader = new PdfReader(tempFilePath);pdfStamper = new PdfStamper(pdfReader, new FileStream(createdPdfPath, FileMode.Create));var pdfContentByte = pdfStamper.GetOverContent(1);foreach(var pdfImage in pdfImages){Uri uri = null;Image img = null;var imageUrl = pdfImage.ImageUrl;//If imageUrl is a relative path, get the absolute path firstlyif (!imageUrl.StartsWith("http")){//var absolutePath = Path.Combine(System.Web.HttpContext.Current.Server.MapPath(".."), imageUrl);var absolutePath = System.Web.HttpContext.Current.Server.MapPath("..") + imageUrl;uri = new Uri(absolutePath);img = Image.GetInstance(uri);}else{//Get the image first, and then transfer it to ITextSharp imageif (pdfImage.ImgBytes != null){img = Image.GetInstance(new MemoryStream(pdfImage.ImgBytes));}}if(img != null){if (pdfImage.ScaleParent){var containerRect = pdfImage.ContainerRect;float percentage = 0.0f;percentage = GetPercentage(img.Width, img.Height, containerRect);img.ScalePercent(percentage * 100);pdfImage.AbsoluteX = (containerRect.RectWidth - img.Width * percentage) / 2 + containerRect.StartX;pdfImage.AbsoluteY = (containerRect.RectHeight - img.Height * percentage) / 2 + containerRect.StartY;}else{img.ScaleToFit(pdfImage.FitWidth, pdfImage.FitHeight);}img.SetAbsolutePosition(pdfImage.AbsoluteX, pdfImage.AbsoluteY);pdfContentByte.AddImage(img);}}pdfStamper.FormFlattening = true;}catch(Exception ex){throw ex;}finally{if (pdfStamper != null){pdfStamper.Close();}if (pdfReader != null){pdfReader.Close();}pdfStamper = null;pdfReader = null;}}
我们在使用的时候,首先要把要加载的图片,做成PdfImage格式,然后调用PutImages方法,把这些图片加载到pdf之中
注意,我这里是把图片加载到rectangle的正中间位置,如果要到其他的位置,可以自己改一下PutImages函数
ITextSharp 使用相关推荐
- 一些关于iText和iTextSharp的旧闻(some old news about iText and iTextSharp)
Google Calendar使用iText来输出PDF(iText used in Google Calendar) The calendars are generated as PDF files ...
- ITextSharp使用说明
ITextSharp是一个生成Pdf文件的开源项目,最近在项目中有使用到这个项目,对使用中的经验作一个小结. ITextSharp中相关的概念: 一.Document 这个对象有三个构造函数: 隐藏行 ...
- 通过iTextSharp为PDF添加带有超链接的Bookmark
最近有这样一个需求,即为PDF加入带有超链接的Bookmark.PDF的开发有个特点,就是虽然相关的开发工具很多,但大都是收费的,PDFOne就是这么一个PDF开发组件,接口调用很简单,但是需要收费, ...
- 【译】在Asp.Net中操作PDF – iTextSharp -利用块,短语,段落添加文本
本篇文章是讲述使用iTextSharp这个开源组件的系列文章的第三篇,iTextSharp可以通过Asp.Net创建PDFs,就像HTML和ASP.Net为文本提供了多种容器一样,iTextSharp ...
- 在.NET中使用iTextSharp创建/读取PDF报告: Part I [翻译]
原文地址:Create/Read Advance PDF Report using iTextSharp in C# .NET: Part I By Debopam Pal, 27 Nov 20 ...
- c# 使用 itextsharp 实现生成Pdf报表
由于项目需要,所以学习Itextsharp 此项目需求是 某一角色提交申请,然后从后台查出数据生成pdf报表 打印出来用于查看 以下是代码: string sql = "select ...
- iTextSharp.text.Rectangle 使用方法说明
iTextSharp.text.Rectangle 使用过程中,由于这方面的中文资料较少,带来了很多不便,消耗了工作时间, iTextSharp.text.Rectangle 的构造函数如下: pub ...
- itextsharp php,C#_C#使用iTextSharp设置PDF所有页面背景图功能实例,本文实例讲述了C#使用iTextSharp - phpStudy...
C#使用iTextSharp设置PDF所有页面背景图功能实例 本文实例讲述了C#使用iTextSharp设置PDF所有页面背景图功能的方法.分享给大家供大家参考.具体如下: 在生成PDF 的时候,虽然 ...
- HTML转PDF(C#---itextsharp)(转自别人的文章)
HTML转PDF(C#---itextsharp) HTML转PDF(C#---itextsharp) 一. 需求:将HTML转PDF打印.Web项目中总是有这样的需求,很是让人苦恼. 二. 分析:如 ...
- ASP.Net MVC——使用 ITextSharp 完美解决HTML转PDF(中文也可以)
前言: 最近在做老师交代的一个在线写实验报告的小项目中,有这么个需求:把学生提交的实验报告(HTML形式)直接转成PDF,方便下载和打印. 以前都是直接用rdlc报表实现的,可这次牵扯到图片,并且更为 ...
最新文章
- 没有最快,只有更快!富士通74.7秒在ImageNet上训练完ResNet-50
- 实力封装:Unity打包AssetBundle(大结局)
- IE6.0,ie7.0与Firefox的CSS兼容性问题
- JavaScript函数节流和函数防抖
- feature改变属性表的值
- 牛客 - Gaming with Mia(dp)
- WebRTC视频编解码器性能评估
- 浅谈Nginx负载均衡与F5的区别
- MySQL排序ORDER BY与分页LIMIT,SQL,减少数据表的网络传输量,完整详细可收藏
- 强推!盘点阿里巴巴 15 款开发者工具 | 程序员硬核评测
- linux nginx编译详解,Linux下nginx编译安装教程和编译参数详解
- 易语言API HOOK DeviceIOControl修改磁盘序列号
- 注意力机制论文:CCNet: Criss-Cross Attention for Semantic Segmentation及其PyTorch实现
- 如何使用Google的Draco项目
- js解决m3u8视频无法播放问题
- 《决胜B端》读书笔记04:互联网领域常见产品方向、盈利模式、盈利模式对产品方向的诉求
- 还在问java架构师路线?学习路线?十年京东架构师教你这样做
- P1456 Monkey King 左偏树模板题
- Python Pandas操作Excel表格文件:创建新表格,追加数据
- operator用法