Asp.Net实现生成WORD或PDF文件

       按照客户的需求,需要用ASP.NET实现生成WORD和PDF文件,现把实现过程写下来,以供以后参考。

      一.配置生成WORD开发运行环境:    

         1. 部署服务器必须操作系统安装为windows2003

         2. 部署服务器必须安装Office Word 2007

         3. 服务器必须设置组件服务 Microsoft Office word

      4.打开组件服务

      5.设置标志属性页为下列用户,用户为administrator

      6.设置安全属性页为自定义,加上NetWork Service用户,加上全部权限

      7.完整代码:

 

using System;
using System.Diagnostics;
using System.Collections;
using System.Data;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.Office.Interop.Word;
using System.IO;


using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using Epower.ITSM.SqlDAL;
using Epower.DevBase.BaseTools;

namespace Epower.ITSM.Web.Common
{
    public class DataToWord
    {
        /// <summary>
        ///
        /// </summary>
        /// <param name="path"></param>
        /// <param name="pathdest"></param>
        public static void WordSaveAs(string path, string pathdest)
        {
            File.Copy(path, pathdest, true);
        }

        #region 生成Word
        /// <summary>
        ///
        /// </summary>
        /// <param name="filePath"></param>
        /// <param name="strFileID"></param>
        /// <param name="lngflowmodelid"></param>
        /// <param name="dt"></param>
        /// <returns></returns>
        public static bool CreateWord(string filePath,string strFileID, long lngflowmodelid,DataTable dt)
        {
            _Document WordDoc = null;
            Object oMissing = System.Reflection.Missing.Value;
            Microsoft.Office.Interop.Word._Application WordApp = new Microsoft.Office.Interop.Word.ApplicationClass();
            WordApp.Visible = true;
            object filename = filePath;
            try
            {
               WordDoc = WordApp.Documents.Open(ref filename, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
                    ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing);

               //替换模板中的书签,生成内容
               if (WordApp.ActiveDocument.Bookmarks.Exists("flowname"))     //流程名称
               {
                   object oBookMark = "flowname";
                   WordDoc.Bookmarks.get_Item(ref oBookMark).Range.Text = dt.Rows[0]["flowname"].ToString();
               }
               if (WordApp.ActiveDocument.Bookmarks.Exists("flowDes"))     //流程描述
               {
                   object oBookMark = "flowDes";
                   WordDoc.Bookmarks.get_Item(ref oBookMark).Range.Text = dt.Rows[0]["Remark"].ToString();
               }

               if (WordApp.ActiveDocument.Bookmarks.Exists("flowlist"))   //流程列表
               {
                   object oContent = "flowlist";
                   Microsoft.Office.Interop.Word.Range startRange = WordApp.ActiveDocument.Bookmarks.get_Item(ref oContent).Range;  //取得位置
                 
                   CreateTable(lngflowmodelid, WordDoc, startRange, ref oMissing);
               }

                //流程图形
               if (WordApp.ActiveDocument.Bookmarks.Exists("flowimage"))
               {
                   object oPreMoney = "flowimage";
                   if (dt.Rows[0]["CHARTS"] != null)
                   {
                       System.IO.MemoryStream ms = new System.IO.MemoryStream((byte[])dt.Rows[0]["CHARTS"]);
                       System.Drawing.Image img = System.Drawing.Image.FromStream(ms);
                       //System.Drawing.Image img = System.Drawing.Image.FromFile(sfile);
                       string strFileCatalog = CommonDP.GetConfigValue("TempCataLog", "FileCataLog");
                       string pictureFileName = strFileCatalog + @"\" + oPreMoney + DateTime.Now.ToString("yyyyMMdd") + DateTime.Now.Hour + DateTime.Now.Minute + DateTime.Now.Millisecond;
                       img.Save(pictureFileName, System.Drawing.Imaging.ImageFormat.Emf);
                       //img.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);

                       //string pictureFileName = @"c:\km.jpg";
                       object LinkToFile = false;
                       object SaveWithDocument = true;
                       object orange = WordApp.ActiveDocument.Bookmarks.get_Item(ref oPreMoney).Range; //取得位置;
                       WordDoc.InlineShapes.Application.ActiveDocument.InlineShapes.AddPicture(pictureFileName, ref LinkToFile, ref SaveWithDocument, ref orange);

                       //图片宽度
                       WordDoc.Application.ActiveDocument.InlineShapes[1].Width = 420f;
                       //图片高度
                       WordDoc.Application.ActiveDocument.InlineShapes[1].Height = 380f;
                       //将图片设置为四周环绕型
                       //Microsoft.Office.Interop.Word.Shape s = WordDoc.Application.ActiveDocument.InlineShapes[1].ConvertToShape();
                       //s.WrapFormat.Type = Microsoft.Office.Interop.Word.WdWrapType.wdWrapSquare;    

                       if (File.Exists(pictureFileName))
                       {
                           File.Delete(pictureFileName);
                       }
                   }
               }

                //保存
                WordDoc.Save();

                WordDoc.Close(ref oMissing, ref oMissing, ref oMissing);
                WordApp.Quit(ref oMissing, ref oMissing, ref oMissing);
                return true;
            }
            catch (Exception e)
            {
                WordDoc.Close(ref oMissing, ref oMissing, ref oMissing);
                WordApp.Quit(ref oMissing, ref oMissing, ref oMissing);
                throw e;
            }
            finally
            {
              
            }
        }
        #endregion

        #region 生成流程列表
        /// <summary>
        ///
        /// </summary>
        /// <param name="lngFlowModeID"></param>
        /// <param name="WordDoc"></param>
        /// <param name="startRange"></param>
        /// <param name="oMissing"></param>
        private static void CreateTable(long lngFlowModeID, Microsoft.Office.Interop.Word._Document WordDoc, Microsoft.Office.Interop.Word.Range startRange, ref Object oMissing)
        {
             DataTable dt = App_CheckFlowModelDP.GetFlowNodeModelInfo(lngFlowModeID);

            Microsoft.Office.Interop.Word.Table newTable = WordDoc.Tables.Add(startRange, dt.Rows.Count + 1,
               4, ref oMissing, ref oMissing);
            newTable.Spacing = 0;
            newTable.TopPadding = 0;
            //为表格划线
            startRange.Tables[1].Borders[WdBorderType.wdBorderTop].LineStyle = WdLineStyle.wdLineStyleSingle;
            startRange.Tables[1].Borders[WdBorderType.wdBorderLeft].LineStyle = WdLineStyle.wdLineStyleSingle;
            startRange.Tables[1].Borders[WdBorderType.wdBorderRight].LineStyle = WdLineStyle.wdLineStyleSingle;
            startRange.Tables[1].Borders[WdBorderType.wdBorderBottom].LineStyle = WdLineStyle.wdLineStyleSingle;
            startRange.Tables[1].Borders[WdBorderType.wdBorderHorizontal].LineStyle = WdLineStyle.wdLineStyleSingle;
            startRange.Tables[1].Borders[WdBorderType.wdBorderVertical].LineStyle = WdLineStyle.wdLineStyleSingle;

            newTable.Cell(1, 1).Range.Text = "序号";
            newTable.Cell(1, 2).Range.Text = "环节名称";
            //newTable.Cell(1, 3).Range.Text = "环节权限";
            newTable.Cell(1, 3).Range.Text = "时限";
            newTable.Cell(1, 4).Range.Text = "描述";

            object LinkToFile = false;
            object SaveWithDocument = true;

            newTable.Rows[1].Range.Shading.BackgroundPatternColor = WdColor.wdColorPaleBlue;

            int RowCount = 2;
            foreach (DataRow dr in dt.Rows)     //流程列表
            {
                //Hashtable htbRights= EpowerCom.FlowModel.GetNodeSpecRights20090610(lngFlowModeID, long.Parse(dr["NodeModelID"].ToString()));
                //string strRights = string.Empty;
                //for (int i = 0; i < htbRights.Count; i++)
                //{
                //    strRights += "|" + htbRights[i].ToString();
                //}
                newTable.Cell(RowCount, 1).Range.Text = dr["NodeSort"].ToString().Trim();    //序号
                newTable.Cell(RowCount, 2).Range.Text = dr["NodeName"].ToString().Trim();    //环节名称
                //newTable.Cell(RowCount, 3).Range.Text = strRights;                           //权限
                newTable.Cell(RowCount, 3).Range.Text = dr["TotalHours"].ToString().Trim();  //时限
                newTable.Cell(RowCount, 4).Range.Text = dr["Remark"].ToString().Trim();    //描述
                RowCount++;
            }
        }
        #endregion
    }
}

     8.调用代码: 

/// <summary>
        /// 导出文档
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnword_Click(object sender, EventArgs e)
        {
            CreateDoc();
        }

        /// <summary>
        ///
        /// </summary>
        private void CreateDoc()
        {
            long lngFlowModelID = long.Parse(Request.QueryString["FlowModelID"]);
            DataTable dt = App_CheckFlowModelDP.GetFlowModelInfo(lngFlowModelID);    //取得流程模型信息

            if (dt.Rows.Count <= 0)   //没有数据
            {
                PageTool.MsgBox(this, "没有流程相关数据,不能生成文档!");
                return;
            }

            string strFileCatalog = CommonDP.GetConfigValue("TempCataLog", "FileCataLog");
            Random rnd = new Random();
            int n = int.Parse(Request.QueryString["FlowModelID"]);
            string lngFileID = n.ToString();
            string filepath = strFileCatalog + "WordFile";
            if (!Directory.Exists(filepath))
            {
                Directory.CreateDirectory(filepath);//报价单主文件夹
            }

            string strcopypath = Server.MapPath("../ExcelTemplate/wordtemplet.doc");
           
            Epower.ITSM.Web.Common.DataToWord.WordSaveAs(strcopypath, filepath + @"\" + lngFileID);   //模板另存文件


            bool breturn = Epower.ITSM.Web.Common.DataToWord.CreateWord(filepath + @"\" + lngFileID, lngFileID, lngFlowModelID, dt);    //生成文档

           

            string sousPath = String.Format(filepath + "\\{0}}", lngFileID);
            string filename = dt.Rows[0]["FlowName"].ToString() + "流程文档.doc";
            FileDown(sousPath, filename);


            //删除临时文件
            if (File.Exists(filepath + @"\" + lngFileID))
            {
                File.Delete(filepath + @"\" + lngFileID);
            }
        }

        #region 文件下载
        /// <summary>
        ///
        /// </summary>
        /// <param name="sousPath"></param>
        /// <param name="FileName"></param>
        private void FileDown(string sousPath, string FileName)
        {
            if (File.Exists(sousPath))
            {
                System.IO.FileInfo file = new FileInfo(sousPath);
                Response.Clear();
                Response.ClearHeaders();

                //add by 郭亮 2009/08/10  解决部分长中文文件名下载被截断的BUG
                System.Text.Encoding code = System.Text.Encoding.GetEncoding("gb2312");
                Response.ContentEncoding = code;
                Response.HeaderEncoding = code;
                // 如果是其它环境,以上代码去掉

                // 屏蔽此代码 郭亮 2009/08/10  解决部分长中文文件名下载被截断的BUG  如果其它环境,此代码恢复
                //filename = HttpUtility.UrlEncode(filename);

                Response.ContentType = "application/octet-stream";
                Response.AddHeader("Content-Disposition", "attachment; filename=\"" + FileName + "\"");
                Response.AddHeader("Content-Length", file.Length.ToString());
                Response.Flush();
                Response.WriteFile(file.FullName);
                Response.End();
            }
            else
            {
                Response.Write("<script>alert('附件所对应的物理文件已经在应用程序外被删除!')</script>");
                Response.Write("<script>window.history.back()</script>");
            }
        }
        #endregion

 

转载于:https://www.cnblogs.com/mczhu/archive/2011/08/31/2160698.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
asp.net生成PDF详解 asp.net生成PDF PDF详解 用C#制作PDF文件全攻略 丽水市汽车运输集团有限公司信息中心 苟安廷 目 录 前 言 3 第一部分 iText的简单应用 4 第一章 创建一个Document 4 第一步 创建一个Document实例: 5 第二步 创建Writer实例 6 第三步 打开Document 6 第四步 添加内容 10 第五步,关闭 document 11 第二章 块、短句和段落 11 块 11 短句 12 段落 12 字体的延续 13 第三章 锚点、列表和注释 14 锚点 14 列表 14 注释 15 第四章 页眉页脚、章节、区域和绘图对象 16 页眉页脚 16 章节和区域 17 图形 17 第五章 表格 18 一些简单的表格 18 一些表格参数 18 大表格 20 内存管理 20 嵌套表格 21 表格偏移 21 表格的绝对位置 21 第六章 图片 21 Image对象 21 图片的位置 22 缩放和旋转图片 23 原始图片数据 23 System.Drawing.Bitmap 23 TIFF和CCITT 24 图片和其他对象 24 第二部分 其他文档格式 25 第七章 XML和 (X)HTML 25 第八章 RTF文件 25 RTF包 25 创建一个RTF文档 25 不支持的特性 26 RTF中扩展的页眉和页脚 26 第三部分 iText的高级应用 27 第九章 字体 27 TrueType字体应用 27 TruType字体集合的应用 28 第十章 图象和文本的绝对位置 28 pdfContentByte 28 简单图形 29 文本 29 模板(Form xObjects) 30 分栏 31 PdfTable 32 颜色(SpotColors)和图案(Patterns) 33 第十一章 本地和异地转向、目标和概要 33 本地转向 33 异地转向 33 第十二章 页面和表格事件 34
ASP.NET Core是微软推出的一种全新的跨平台开发框架,而ASP.NET Core 6则是最新的版本。在ASP.NET Core 6中,对于PDF文件的处理提供了更加便捷和灵活的方式。 ASP.NET Core 6中可以使用第三方库来生成和处理PDF文件。常见的有iTextSharp、PDFSharp、Syncfusion等。这些库提供了丰富的API和功能,可以通过代码生成和编辑PDF文件。例如,可以设置PDF的样式、布局、文本内容、表格、图片等。同时,还可以实现PDF的导出、打印、加密等操作。 除了使用第三方库外,ASP.NET Core 6还提供了一些原生的功能来处理PDF文件。例如,可以使用Razor视图引擎生成动态的PDF文件,将视图转化为PDF格式输出。使用这种方式,可以直接在视图中使用HTML和CSS来定义PDF的样式和布局,非常方便。此外,还可以通过.NET内置的Web API来生成PDF文件,并通过HTTP请求将PDF文件发送给客户端。 ASP.NET Core 6中的PDF处理还提供了一些额外的功能,如文本搜索、书签、目录生成、水印、添加标记等。这些功能使得生成PDF文件更加丰富和多样化。同时,ASP.NET Core 6还支持将PDF文件与其他文件格式进行转换,如将PDF转成Word、Excel、HTML等格式,方便用户的使用和转载。 总而言之,ASP.NET Core 6提供了多种方法和工具来处理PDF文件,使得开发人员可以更加方便地生成和编辑PDF文件,并实现各种复杂的需求。无论是使用第三方库还是原生的功能,都能够满足开发人员对于PDF处理的需求。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值