ITextSharp 使用

本文介绍了如何使用ITextSharp库在C#中操作PDF文件,包括填充文本域和在指定区域内添加图片的方法。提供了实用代码示例,帮助开发者快速掌握关键功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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 images

            var 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 firstly
                    if (!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 image
                        if (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函数








<think>好的,我需要帮助用户找到在iTextSharp使用中文字体的示例代码或配置教程。首先,我应该回忆一下iTextSharp的相关知识,特别是处理中文字体的部分。用户提供的引用中提到了创建PDF的基本方法,但没有直接涉及中文字体,所以可能需要结合外部资料。 我知道iTextSharp默认可能不支持中文字体,需要用户手动引入中文字体文件,比如.ttf或.ttc文件。正确的步骤可能包括下载字体、注册字体到iTextSharp,并在代码中设置字体。此外,还需要确保编码正确,避免乱码。 接下来,我需要验证这些步骤是否正确。例如,是否必须使用BaseFont.CreateFont来加载字体文件,以及如何设置字体的大小和样式。同时,还需要考虑不同操作系统下的路径问题,比如在Windows系统中字体通常位于C:\Windows\Fonts目录下。 另外,用户可能需要完整的示例代码,包括创建文档、写入中文内容等步骤。代码中需要用到iTextSharp的Document、PdfWriter等类,以及正确设置字体。同时,要提醒用户关闭文档以保存内容,并处理可能的异常。 还要注意,有些教程可能提到使用不同的编码方式,比如Identity-H,来正确渲染中文。同时,可能需要引用额外的库或命名空间,比如iTextSharp.text.pdf.BaseFont。 最后,需要确保回答结构清晰,分步骤说明,并提供示例代码和注意事项,帮助用户顺利实现中文字体的使用。</think>### 在iTextSharp使用中文字体的配置方法 #### 1. 下载并引入中文字体文件 iTextSharp默认不支持中文字体,需手动引入`.ttf`或`.ttc`格式的中文字体文件(如宋体、黑体等)。Windows系统中字体文件通常位于`C:\Windows\Fonts`目录下。例如: - `simsun.ttc`(宋体) - `msyh.ttf`(微软雅黑) #### 2. 注册字体并设置编码 在代码中通过`BaseFont.CreateFont`方法加载字体文件,并指定编码格式(如`Identity-H`用于水平布局的Unicode编码): ```csharp // 加载中文字体文件 BaseFont baseFont = BaseFont.CreateFont( "C:/Windows/Fonts/simsun.ttc,0", // 字体路径及索引(0表示第一个字体) BaseFont.IDENTITY_H, // 编码方式 BaseFont.EMBEDDED // 嵌入字体到PDF ); // 创建字体对象 Font chineseFont = new Font(baseFont, 12); // 字号12 ``` #### 3. 完整示例代码 以下代码演示了创建包含中文内容的PDF文档: ```csharp using iTextSharp.text; using iTextSharp.text.pdf; using System.IO; public void CreateChinesePDF(string filePath) { // 1. 创建文档对象 Document document = new Document(); try { // 2. 绑定PDF写入器 PdfWriter.GetInstance(document, new FileStream(filePath, FileMode.Create)); // 3. 打开文档 document.Open(); // 4. 添加中文内容 BaseFont baseFont = BaseFont.CreateFont( "C:/Windows/Fonts/simsun.ttc,0", BaseFont.IDENTITY_H, BaseFont.EMBEDDED ); Font font = new Font(baseFont, 12); document.Add(new Paragraph("你好,世界!", font)); document.Add(new Paragraph("这是一段中文字符测试。", font)); } finally { // 5. 关闭文档 document.Close(); } } ``` #### 4. 关键注意事项 - **字体嵌入**:必须设置`BaseFont.EMBEDDED`,否则生成的PDF在未安装该字体的设备上可能无法显示中文[^1]。 - **路径问题**:若将字体文件放入项目目录,需使用相对路径(如`@"fonts/simsun.ttc"`)并确保文件属性设置为“复制到输出目录”。 - **字体索引**:`.ttc`文件可能包含多个字体,索引号(如`,0`)需根据实际情况调整。 #### 5. 扩展配置(可选) - **多字体支持**:可重复注册多个字体文件,通过不同`Font`对象切换样式。 - **粗体/斜体**:需加载对应的粗体或斜体字体文件,例如`simsunb.ttf`(宋体加粗)。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值