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. [Latex]实现行内高亮

    Latex的行内高亮 前两天想要在做的小操作系统实验指导书里使用行内高亮,一开始虽然有命令 \mint{Language}|contents| 但是无奈只能实现跳行高亮,即不能实现行内高亮.即代码高亮 ...

  2. [Tool] PowerDesigner

    一般项目的生命周期: 1.需求分析 2.需求规格说明书 3.总体设计 4.详细设计 5.编码实现 6.测试,试运行. 7.验收 8.后期维护 PowerDesigner 可以把软件生命周期的每一个阶段 ...

  3. MyBatis动态SQL使用,传入参数Map中的Key判断

    <select id="" parameterType="Map" resultMap="commodityResultMap" &g ...

  4. MVC,布局页面

    一>>> 在_ViewStart.cshtml文件中,加入: @{ Layout = "~/Views/Shared/_Layout.cshtml"; PageD ...

  5. Entity FrameWork 增删查改的本质

    之前的文章里面已经说了,EF的增删查改.那时候的修改,删除,只能是先查询出来要修改的数据,再修改,删除...现在来一个改进版的,增删查改. 1.Add static void Add() { //1. ...

  6. 设计模式--中介(Mediator)模式

    时隔很长一段时,现在又重温设计模式,上个星期学习<设计模式--代理(Proxy)模式>http://www.cnblogs.com/insus/p/4128814.html. 温故而知新, ...

  7. c# 文件另存为代码

    利用.NET中的File.Copy方法 命名空间:System.IO 重载列表:Copy(string sourceFilePath,string targetFilePath) sourceFile ...

  8. EasyUI中Base(基础)的基本用法

    EasyUI中Base(基础)的用法 一.Base(基础) 1.parser 解析器 2.easyloader 简单加载 3.draggable 拖动 4.droppable 放置 5.resizab ...

  9. 重新想象 Windows 8 Store Apps (36) - 通知: Tile 详解

    [源码下载] 重新想象 Windows 8 Store Apps (36) - 通知: Tile 详解 作者:webabcd 介绍重新想象 Windows 8 Store Apps 之 通知 Tile ...

  10. 重新想象 Windows 8.1 Store Apps (73) - 新增控件: DatePicker, TimePicker

    [源码下载] 重新想象 Windows 8.1 Store Apps (73) - 新增控件: DatePicker, TimePicker 作者:webabcd 介绍重新想象 Windows 8.1 ...