zoukankan      html  css  js  c++  java
  • C# 用itextsharp实现导出pdf文件

    DLL库下载

     下载完之后解压dll文件在项目中添加引用

    调用示例如下:

    页面:

       <div>
            <asp:Button ID="Button1" runat="server" Text="保存pdf文件" OnClick="Button1_Click" />
        </div>
    View Code

    后台:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using iTextSharp.text;
    using iTextSharp.text.pdf;
    using System.IO;
    
    namespace Web
    {
        public partial class WebForm2 : System.Web.UI.Page
        {
            protected void Page_Load(object sender, EventArgs e)
            {
    
            }
    
            protected void Button1_Click(object sender, EventArgs e)
            {
                try
                {
                    //获取桌面路径设为文件下载保存路径
                    string Fname = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory)+"//证书.pdf";
                    //Response.Write("<script>alert('桌面的路径是" + Fname + "');</script>");
    //定义下载路径
                    //string Fname = "C://Users//Administrator//Desktop//123.pdf";
                    Rectangle pageSize = new Rectangle(1000, 500);
                    Document document = new Document(pageSize, 10, 10, 120, 80);
                    PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(Fname, FileMode.Create));
                    document.Open();
                    BaseFont bfChinese = BaseFont.CreateFont("C://WINDOWS//Fonts//simsun.ttc,1", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
                    iTextSharp.text.Font fontChinese = new iTextSharp.text.Font(bfChinese, 12, iTextSharp.text.Font.NORMAL, new iTextSharp.text.Color(0, 0, 0));
    
                    //导出文本的内容:
                    document.Add(new Paragraph("你好", fontChinese));
    
                    //向PDF里面添加图片
                    string imgurl = Path.GetFullPath("F:/项目/Web/Images/cp1.png");
                    iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(imgurl);
                    //SetAbsolutePosition方法是设置图片出现的位置
                    img.SetAbsolutePosition(10, 100);
                    writer.DirectContent.AddImage(img);
                    document.Close();
                    writer.Close();
                    Response.Write("<script>alert('导出成功!');</script>");
                }
                catch (Exception ex)
                {
                    throw ex;
                }
               
            }
        }
    }
    View Code
  • 相关阅读:
    PHP实现html字符实体转汉字
    利用 secureCRT 直接上传下载文件 (sz,rz)
    CentOS安装scp命令
    以Apache模块的方式编译安装php-5.5.4
    编译安装 apache 2.4.6
    协方差Covariance的表述推导
    Java _ JDK _ Arrays, LinkedList, ArrayList, Vector 及Stack
    Java_一些特殊的关键字详(?)解
    Java_你应该知道的26种设计模式
    排序与搜索一览
  • 原文地址:https://www.cnblogs.com/chenlihong-886/p/12889995.html
Copyright © 2011-2022 走看看