C#中使用iTextSharp生成并下载PDF很方便。

首先要将iTextSharp的dll下载并引入项目

主要分成两部分,一部分是PDF的Document生成,另一部分就是将Document输出到页面

这里分别列出aspx页和MVC中ActionResult的下载方式

①aspx

工具类(只是提供Document的输出)

using System.Web;
using iTextSharp.text;
using System.IO;
using iTextSharp.text.pdf; namespace Common
{
public class PdfHelper
{
public event DocRenderHandler DocRenderEvent;
public delegate void DocRenderHandler(ref Document Doc); public void DownLoadPDF(string FileName, HttpContext context)
{
Document Doc = new Document();
HttpResponse Response = context.Response; using (MemoryStream Memory = new MemoryStream())
{
PdfWriter PdfWriter = PdfWriter.GetInstance(Doc, Memory);
if (DocRenderEvent != null)
DocRenderEvent(ref Doc); #region 文件输出及相关设置
Response.Clear();
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.AddHeader("Content-Disposition", "attachment;filename=" + FileName);
Response.ContentType = "application/pdf";
Response.OutputStream.Write(Memory.GetBuffer(), , Memory.GetBuffer().Length);
Response.OutputStream.Flush();
Response.OutputStream.Close();
Response.Flush();
#endregion
}
Response.End();
}
}
}

下载页面

using System;
using iTextSharp.text;
using iTextSharp.text.pdf;
using System.Text; namespace MvcMovie.Common
{
public partial class PdfLoad : System.Web.UI.Page
{ protected void Page_Load(object sender, EventArgs e)
{
string FileName = DateTime.Now.ToShortTimeString() + ".pdf";
PdfHelper ph = new PdfHelper();
ph.DocRenderEvent += RenderPdfDoc;
ph.DownLoadPDF(FileName, this.Context);
} private void RenderPdfDoc(ref Document Doc)
{
Doc.SetPageSize(PageSize.A4);
Doc.SetMargins(, , , ); #region 相关元素准备
BaseFont bfChinese = BaseFont.CreateFont(@"C:\windows\fonts\simsun.ttc,1", BaseFont.IDENTITY_H,
BaseFont.NOT_EMBEDDED);
Font Font16 = new Font(bfChinese, );
Font Font14 = new Font(bfChinese, );
Font Font12 = new Font(bfChinese, );
Font Font12Bold = new Font(bfChinese, , Font.BOLD);
Font Font12Italic = new Font(bfChinese, , Font.BOLDITALIC);
Font Font10Bold = new Font(bfChinese, , Font.BOLD); Paragraph parag;
Chunk chunk;
PdfPTable table;
#endregion #region 文件标题
Doc.Open();
Doc.AddAuthor("TiestoRay");
Doc.AddTitle("相关部分发布的重要通知");
#endregion #region 正文
parag = new Paragraph("------通知------", Font16);
parag.Alignment = Element.ALIGN_CENTER;
Doc.Add(parag); parag = new Paragraph();
parag.SetLeading(20f, 1f);
parag.Add(new Chunk("曾经沧海难为水,心有灵犀一点通", Font12Italic));
Doc.Add(parag); parag = new Paragraph();
parag.Add(new Chunk("取次花丛懒回顾,得来全不费工夫", Font10Bold));
Doc.Add(parag); parag = new Paragraph();
parag.Add(new Chunk(" " + DateTime.Now.ToLongDateString(), Font12));
Doc.Add(parag); parag = new Paragraph();
parag.SetLeading(1f, 1f);
chunk = new Chunk(new StringBuilder().Insert(, " ", ).Append("Come On!").ToString(), Font12);
chunk.SetUnderline(-18f, 1.4f);
parag.Add(chunk);
parag.Alignment = Element.ALIGN_JUSTIFIED_ALL;
Doc.Add(parag); Doc.NewPage();//换页 table = new PdfPTable(new float[] { , , });
table.WidthPercentage = 100f;
table.AddCell(new Phrase("英语老师签字:\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n", Font12));
table.AddCell(new Phrase("同桌签字:", Font12));
table.AddCell(new Phrase("本人签字:", Font12));
Doc.Add(table); parag = new Paragraph();
parag.SetLeading(-30f, 1.4f);
parag.Add(new Chunk(new StringBuilder().Insert(, " ", ).ToString() + "签字日期:", Font12));
Doc.Add(parag);
Doc.Close();
#endregion
}
}
}

②MVC3(以上)版本
写一个继承自ActionResult的Result类,并且将Document输出写到ExecuteResult中

using System.Web;
using System.Web.Mvc;
using iTextSharp.text;
using System.IO;
using iTextSharp.text.pdf; namespace Common
{
public class PdfResult:ActionResult
{
private string FileName;
public event DocRenderHandler DocRenderEvent;
public delegate void DocRenderHandler(ref Document Doc); public PdfResult(string FileName)
{
this.FileName = FileName;
} /// <summary>
/// 向页面输出时才会执行该方法
/// </summary>
public override void ExecuteResult(ControllerContext context)
{
Document Doc = new Document();
using (MemoryStream Memory = new MemoryStream())
{
PdfWriter PdfWriter = PdfWriter.GetInstance(Doc, Memory);
if (DocRenderEvent != null)
DocRenderEvent(ref Doc); #region 文件输出及相关设置
HttpResponseBase Response = context.HttpContext.Response;
Response.Clear();
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.AddHeader("Content-Disposition", "attachment;filename=" + FileName);
Response.ContentType = "application/pdf";
Response.OutputStream.Write(Memory.GetBuffer(), , Memory.GetBuffer().Length);
Response.OutputStream.Flush();
Response.OutputStream.Close();
Response.Flush();
#endregion
}
context.HttpContext.Response.End();
}
}
}

②调用

using System;
using System.Web.Mvc;
using MvcMovie.Common;
using iTextSharp.text;
using iTextSharp.text.pdf;
using System.Text; namespace MvcMovie.Controllers
{
public class HomeController : Controller
{
public ActionResult Index(string name,int? id)
{
ViewBag.Message = "欢迎使用 ASP.NET MVC!";
return View();
} public ViewResult About()
{
return View("About");
} public ActionResult DownLoadPdf(int ID)
{
string FileName = DateTime.Now.ToShortTimeString()+".pdf";
PdfResult pr = new PdfResult(FileName);
pr.DocRenderEvent += RenderPdfDoc;
return pr;
} private void RenderPdfDoc(ref Document Doc)
{
//TO DO
//内容同上
}
}
}

C# PDF打印的更多相关文章

  1. 开源免费且稳定实用的.NET PDF打印组件itextSharp(.NET组件介绍之八)

    在这个.NET组件的介绍系列中,受到了很多园友的支持,一些园友(如:数据之巅. [秦时明月]等等这些大神 )也给我提出了对应的建议,我正在努力去改正,有不足之处还望大家多多包涵.在传播一些简单的知识的 ...

  2. 基于iTextSharp的PDF操作(PDF打印,PDF下载)

    基于iTextSharp的PDF操作(PDF打印,PDF下载) 准备 1. iTextSharp的简介 iTextSharp是一个移植于java平台的iText项目,被封装成c#的组件来用于C#生成P ...

  3. NetSuite实现pdf打印中的条形码的功能

    2020-11-27 提起NS,在程序员这一块应该不怎么被人知道,算是比较小众的一门技术了,毕竟Netsuite兴起的时间算不上早,进入中国的时间更晚,除了从事这一块的程序员,可能都没有见过,恰好我是 ...

  4. .Net下的PDF打印

    简单研究了一下.Net下的PDF打印,一路发现了很多小坑. 第三方组件 这里使用的解析PDF的组件是mupdf,特点和C#调用在 这里 有介绍. 实现的功能 支持页面大小.边距.打印机选择.打印机dp ...

  5. 驰骋CCFlow开源工作流程引擎如何设置PDF打印

    前言 经常有驰骋CCFlow爱好者朋友提问关于打印相关问题.在这篇博文中大家介绍一下工作流引擎CCFlow的HTML打印和PDF打印,针对Java版本和.NET版本有不同的操作步骤,包括开关设置.水印 ...

  6. Java 创建PDF打印小册子

    概述 PDF打印小册子是指将PDF格式文档在打印成刊物前需要提前进行的页面排版,以便在打印后装订成册.下面以Java代码展示如何来实现.这里调用Free Spire.PDF for Java中的Pdf ...

  7. 重命名PDF打印文件名

    Odoo系统默认打印出来的PDF文件都是以当前文档模型对象对应的模板文件名命名的,对用户来说,这样的命名很不友好. 我们希望能够将打印出来的文件名以单号命名,下面是实现这种目的的方法. 在report ...

  8. 两页pdf打印为一页,并且放大(打印英文pdf常用)

    多很英文书籍都是小书,若我们直接打印它的pdf会很厚,比如我要打印一本 thinking in C++,就要800+页.不如把两页打成一页.但是打成一页之后又太小了,需要放大.具体方法如下:   前提 ...

  9. pdf打印乱码问题

    问题: 使用Adobe Reader将一份pdf文件通过我的虚拟打印机输出后(输出的是中间文件,等同于EMF文件),查看的时候发现有时候是乱码.最简单的必现步骤: 1.使用Adobe Reader打开 ...

  10. java原装代码完成pdf在线预览和pdf打印及下载

    这是我在工作中,遇到这样需求,完成需求后,总结的成果,就当做是工作笔记,以免日后忘记,当然,能帮助到别人是最好的啦! 下面进入正题: 前提准备: 1. 项目中至少需要引入的jar包,注意版本: a)  ...

随机推荐

  1. jquery选中下拉列表的某个值

    $('#villageToiletAnn').val('xxx'); id是select的ID,不是option的ID

  2. 扩展KMP --- HDU 3613 Best Reward

    Best Reward Problem's Link:   http://acm.hdu.edu.cn/showproblem.php?pid=3613 Mean: 给你一个字符串,每个字符都有一个权 ...

  3. JAVA - 大数类详解

    写在前面 对于ACMer来说,java语言最大的优势就是BigInteger,Bigdecimal,String三个类. 这三个类分别是高精度整数,高精度浮点数和字符串,之所以说这个是它的优势是因为j ...

  4. jquery.ajax 跨域请求webapi,设置headers

    解决跨域调用服务并设置headers 主要的解决方法需要通过服务器端设置响应头.正确响应options请求,正确设置 JavaScript端需要设置的headers信息 方能实现. 1.第一步 服务端 ...

  5. ADO.net中常用的对象介绍

    ADO.NET的对象主要包括:DataSet,DataTable,DataColumn,DataRow,和DataRelation. DataSet:这个对象是一个集合对象,它可以包含任意数量的数据表 ...

  6. csharp: 用Enterprise Library对象实体绑定数据

    Enterprise Library: https://msdn.microsoft.com/en-us/library/ff648951.aspx /// <summary> /// 是 ...

  7. 树的统计Count---树链剖分

    NEFU专项训练十和十一——树链剖分 Description 一棵树上有n个节点,编号分别为1到n,每个节点都有一个权值w.我们将以下面的形式来要求你对这棵树完成一些操作: I. CHANGE u t ...

  8. Treap树的基础知识

    原文 其它较好的的介绍:堆排序  AVL树 树堆,在数据结构中也称Treap(事实上在国内OI界常称为Traep,与之同理的还有"Tarjan神犇发明的"Spaly),是指有一个随 ...

  9. jsp iframe example

    1. jsp中用iframe的方式在body中展示列表, 可以通过父元素的宽.高来设定iframe的宽高. <div class="wrapper" style=" ...

  10. python函数和常用模块(一),Day3

    set集合 函数 三元运算 lambda表达式 内置函数1 文件操作 set集合 创建 se = {"123", "456"} # 直接创建一个集合 se = ...