• 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
  • 相关阅读:
    java String 转Json报错 java.lang.NoClassDefFoundError: org/apache/commons/lang/exception/NestableRuntim
    Idea 进行断点调试的 快捷键
    spring AOP的使用步骤
    AOP的定义和原理
    SpringBoot入门篇--使用IDEA创建一个SpringBoot项目
    详解CI、CD相关概念
    intellij idea 的全局搜索快捷键方法
    面向对象之工厂模式与构造函数模式的区别
    冒泡排序和快速排序
    java里的数组和list分别在什么情况下使用?
  • 原文地址:https://www.cnblogs.com/chenlihong-886/p/12889995.html
Copyright © 2020-2023  润新知