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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM