• MemoryStream 转 pdf


    在项目开发中用到将MemoryStream 转pdf,在转化过程中需要建了一个.dom格式的模板,先保存为.doc文件,然后再转换为.pdf。

    有一个插件感觉好不错,给大家推荐一下。 
    dll下载链接 
    http://pan.baidu.com/s/1skWPBAX 
    提取码: 
    fu4r 
    重点内容

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using Microsoft.Office.Interop.Word;
    using Word = Microsoft.Office.Interop.Word;
    
    namespace MyTools
    {
        public class WordHelper
        {
            private Word.Document wDoc = null;
            private Word.Application wApp = null;
            public Word.Document Document
            {
                get { return wDoc; }
                set { wDoc = value; }
            }
    
            public Word.Application Application
            {
                get { return wApp; }
                set { wApp = value; }
            }
            #region 从模板创建新的Word文档
            /// <summary>  
            /// 从模板创建新的Word文档  
            /// </summary>  
            /// <param name="templateName">模板文件名</param>  
            /// <returns></returns>  
            public bool CreateNewWordDocument(string templateName)
            {
                try
                {
                    return CreateNewWordDocument(templateName, ref wDoc, ref wApp);
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
            #endregion
    
            #region 从模板创建新的Word文档,并且返回对象Document,Application
            /// <summary>  
            /// 从模板创建新的Word文档,  
            /// </summary>  
            /// <param name="templateName">模板文件名</param>  
            /// <param name="wDoc">返回的Word.Document对象</param>  
            /// <param name="WApp">返回的Word.Application对象</param>  
            /// <returns></returns>  
            public static bool CreateNewWordDocument(string templateName, ref Word.Document wDoc, ref  Word.Application WApp)
            {
                Word.Document thisDocument = null;
                Word.Application thisApplication = new Word.ApplicationClass();
                thisApplication.Visible = false;
                thisApplication.Caption = "";
                thisApplication.Options.CheckSpellingAsYouType = false;
                thisApplication.Options.CheckGrammarAsYouType = false;
    
                Object Template = templateName;// Optional Object. The name of the template to be used for the new document. If this argument is omitted, the Normal template is used.  
                Object NewTemplate = false;// Optional Object. True to open the document as a template. The default value is False.  
                Object DocumentType = Word.WdNewDocumentType.wdNewBlankDocument; // Optional Object. Can be one of the following WdNewDocumentType constants: wdNewBlankDocument, wdNewEmailMessage, wdNewFrameset, or wdNewWebPage. The default constant is wdNewBlankDocument.  
                Object Visible = true;//Optional Object. True to open the document in a visible window. If this value is False, Microsoft Word opens the document but sets the Visible property of the document window to False. The default value is True.  
    
                try
                {
                    Word.Document wordDoc = thisApplication.Documents.Add(ref Template, ref NewTemplate, ref DocumentType, ref Visible);
    
                    thisDocument = wordDoc;
                    wDoc = wordDoc;
                    WApp = thisApplication;
                    return true;
                }
                catch (Exception ex)
                {
                    string err = string.Format("创建Word文档出错,错误原因:{0}", ex.Message);
                    throw new Exception(err, ex);
                }
            }
            #endregion
    
            #region 文档另存为其他文件名
            /// <summary>  
            /// 文档另存为其他文件名  
            /// </summary>  
            /// <param name="fileName">文件名</param>  
            /// <param name="wDoc">Document对象</param>  
            public bool SaveAs(string fileName)
            {
                try
                {
                    return SaveAs(fileName, wDoc);
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
            #endregion
    
            #region 文档另存为其他文件名
            /// <summary>  
            /// 文档另存为其他文件名  
            /// </summary>  
            /// <param name="fileName">文件名</param>  
            /// <param name="wDoc">Document对象</param>  
            public static bool SaveAs(string fileName, Word.Document wDoc)
            {
                Object FileName = fileName; // 文档的名称。默认值是当前文件夹名和文件名。如果文档在以前没有保存过,则使用默认名称(例如,Doc1.doc)。如果已经存在具有指定文件名的文档,则会在不先提示用户的情况下改写文档。  
                Object FileFormat = Word.WdSaveFormat.wdFormatDocument; // 文档的保存格式。可以是任何 WdSaveFormat 值。要以另一种格式保存文档,请为 SaveFormat 属性指定适当的值。  
                Object LockComments = false; // 如果为 true,则锁定文档以进行注释。默认值为 false。  
                Object Password = System.Type.Missing; // 用来打开文档的密码字符串。(请参见下面的备注。)  
                Object AddToRecentFiles = false; // 如果为 true,则将该文档添加到“文件”菜单上最近使用的文件列表中。默认值为 true。  
                Object WritePassword = System.Type.Missing; // 用来保存对文件所做更改的密码字符串。(请参见下面的备注。)  
                Object ReadOnlyRecommended = false; // 如果为 true,则让 Microsoft Office Word 在打开文档时建议只读状态。默认值为 false。  
                Object EmbedTrueTypeFonts = false; //如果为 true,则将 TrueType 字体随文档一起保存。如果省略的话,则 EmbedTrueTypeFonts 参数假定 EmbedTrueTypeFonts 属性的值。  
                Object SaveNativePictureFormat = true; // 如果图形是从另一个平台(例如,Macintosh)导入的,则 true 表示仅保存导入图形的 Windows 版本。  
                Object SaveFormsData = false; // 如果为 true,则将用户在窗体中输入的数据另存为数据记录。  
                Object SaveAsAOCELetter = false; // 如果文档附加了邮件程序,则 true 表示会将文档另存为 AOCE 信函(邮件程序会进行保存)。  
                Object Encoding = System.Type.Missing; // MsoEncoding。要用于另存为编码文本文件的文档的代码页或字符集。默认值是系统代码页。  
                Object InsertLineBreaks = true; // 如果文档另存为文本文件,则 true 表示在每行文本末尾插入分行符。  
                Object AllowSubstitutions = false; //如果文档另存为文本文件,则 true 允许 Word 将某些符号替换为外观与之类似的文本。例如,将版权符号显示为 (c)。默认值为 false。  
                Object LineEnding = Word.WdLineEndingType.wdCRLF;// Word 在另存为文本文件的文档中标记分行符和换段符。可以是任何 WdLineEndingType 值。  
                Object AddBiDiMarks = true;//如果为 true,则向输出文件添加控制字符,以便保留原始文档中文本的双向布局。  
                try
                {
                    wDoc.SaveAs(ref FileName, ref FileFormat, ref LockComments, ref Password, ref AddToRecentFiles, ref WritePassword
                            , ref ReadOnlyRecommended, ref EmbedTrueTypeFonts, ref SaveNativePictureFormat
                            , ref SaveFormsData, ref SaveAsAOCELetter, ref Encoding, ref InsertLineBreaks, ref AllowSubstitutions
                            , ref LineEnding, ref AddBiDiMarks);
                    return true;
                }
                catch (Exception ex)
                {
                    string err = string.Format("另存文件出错,错误原因:{0}", ex.Message);
                    throw new Exception(err, ex);
                }
            }
            #endregion
    
            #region 关闭文档
            /// <summary>  
            /// 关闭文档  
            /// </summary>  
            public void Close()
            {
                Close(wDoc, wApp);
                wDoc = null;
                wApp = null;
            }
            #endregion
    
            #region 关闭文档
            /// <summary>  
            /// 关闭文档  
            /// </summary>  
            /// <param name="wDoc">Document对象</param>  
            /// <param name="WApp">Application对象</param>  
            public static void Close(Word.Document wDoc, Word.Application WApp)
            {
                Object SaveChanges = Word.WdSaveOptions.wdSaveChanges;// 指定文档的保存操作。可以是下列 WdSaveOptions 值之一:wdDoNotSaveChanges、wdPromptToSaveChanges 或 wdSaveChanges。  
                Object OriginalFormat = Word.WdOriginalFormat.wdOriginalDocumentFormat;// 指定文档的保存格式。可以是下列 WdOriginalFormat 值之一:wdOriginalDocumentFormat、wdPromptUser 或 wdWordDocument。  
                Object RouteDocument = false;// 如果为 true,则将文档传送给下一个收件人。如果没有为文档附加传送名单,则忽略此参数。  
                try
                {
                    if (wDoc != null) wDoc.Close(ref SaveChanges, ref OriginalFormat, ref RouteDocument);
                    if (WApp != null) WApp.Quit(ref SaveChanges, ref OriginalFormat, ref RouteDocument);
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
            #endregion
    
            #region 填充书签
            /// <summary>  
            /// 填充书签  
            /// </summary>  
            /// <param name="bookmark">书签</param>  
            /// <param name="value">值</param>  
            public void Replace(string bookmark, string value)
            {
                try
                {
                    object bkObj = bookmark;
                    if (wApp.ActiveDocument.Bookmarks.Exists(bookmark) == true)
                    {
                        wApp.ActiveDocument.Bookmarks.get_Item(ref bkObj).Select();
                    }
                    else return;
                    wApp.Selection.TypeText(value);
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
            #endregion
    
            /// <summary>
            /// 插入图片
            /// </summary>
            /// <param name="bookmark">书签</param>
            /// <param name="picturePath">图片路径</param>
            /// <param name="width">图片宽度</param>
            /// <param name="hight">图片高度</param>
            public void InsertPicture(string bookmark, string picturePath, float width, float hight)
            {
                object miss = System.Reflection.Missing.Value;
                object oStart = bookmark;
                Object linkToFile = false;       //图片是否为外部链接
                Object saveWithDocument = true;  //图片是否随文档一起保存 
                object range = wDoc.Bookmarks.get_Item(ref oStart).Range;//图片插入位置
                //Object range = wDoc.Paragraphs.Last.Range;
                InlineShape pic = wDoc.InlineShapes.AddPicture(picturePath, ref linkToFile, ref saveWithDocument, ref range);
                pic.Width = width;
                pic.Height = hight;
                //wDoc.Application.ActiveDocument.InlineShapes[1].Width = width;   //设置图片宽度
                //wDoc.Application.ActiveDocument.InlineShapes[1].Height = hight;  //设置图片高度
                //Microsoft.Office.Interop.Word.Shape s = wDoc.Application.ActiveDocument.InlineShapes[1].ConvertToShape();
                //s.WrapFormat.Type = Microsoft.Office.Interop.Word.WdWrapType.wdWrapSquare; //将图片设置为四周环绕型
            }
    
            /// <summary>
            /// 找到表格
            /// </summary>
            /// <param name="bookmarkTable"></param>
            /// <returns></returns>
            public bool FindTable(string bookmarkTable)
            {
                try
                {
                    object bkObj = bookmarkTable;
                    if (wApp.ActiveDocument.Bookmarks.Exists(bookmarkTable) == true)
                    {
                        wApp.ActiveDocument.Bookmarks.get_Item(ref bkObj).Select();
                        return true;
                    }
                    else
                        return false;
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
            /// <summary>
            /// 移动到下一个单元格
            /// </summary>
            public void MoveNextCell()
            {
                try
                {
                    Object unit = Word.WdUnits.wdCell;
                    Object count = 1;
                    wApp.Selection.Move(ref unit, ref count);
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
            /// <summary>
            /// 填充单元格
            /// </summary>
            /// <param name="value"></param>
            public void SetCellValue(string value)
            {
                try
                {
                    wApp.Selection.TypeText(value);
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
            /// <summary>
            /// 移动到下一行
            /// </summary>
            public void MoveNextRow(int nextCount)
            {
                try
                {
                    Object extend = Word.WdMovementType.wdExtend;
                    Object unit = Word.WdUnits.wdCell;
                    Object count = nextCount;
                    wApp.Selection.MoveRight(ref unit, ref count, ref extend);
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
    
            /// <SUMMARY></SUMMARY>    
            /// 换行    
            ///     
            public void NewLine()
            {
                //换行    
                wApp.Application.Selection.TypeParagraph();
            }
    
            public void InsertTable(int rowCount, string header, int cellCount)
            {
                Object Nothing = System.Reflection.Missing.Value;
                //文档中创建表格  
                Microsoft.Office.Interop.Word.Table newTable = wDoc.Tables.Add(wApp.Selection.Range, rowCount, cellCount, ref Nothing, ref Nothing);
    
                //设置表格样式  
                newTable.Borders.OutsideLineStyle = WdLineStyle.wdLineStyleOutset;// outStyle;
                newTable.Borders.InsideLineStyle = WdLineStyle.wdLineStyleInset;// intStyle;
                //newTable.Columns[1].Width = 60f;
                //newTable.Columns[2].Width = 60f;
                //newTable.Columns[3].Width = 60f;
    
                string[] strHeader = header.Split(',');
                for (int i = 0; i < strHeader.Length; i++)
                {
                    newTable.Cell(1, i + 1).Range.Text = strHeader[i];
                    newTable.Cell(1, i + 1).Range.Bold = 1;//设置单元格中字体为粗体
                    newTable.Cell(1, i + 1).Range.Font.Size = 9;
                }
    
            }
        }
    }
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135
    • 136
    • 137
    • 138
    • 139
    • 140
    • 141
    • 142
    • 143
    • 144
    • 145
    • 146
    • 147
    • 148
    • 149
    • 150
    • 151
    • 152
    • 153
    • 154
    • 155
    • 156
    • 157
    • 158
    • 159
    • 160
    • 161
    • 162
    • 163
    • 164
    • 165
    • 166
    • 167
    • 168
    • 169
    • 170
    • 171
    • 172
    • 173
    • 174
    • 175
    • 176
    • 177
    • 178
    • 179
    • 180
    • 181
    • 182
    • 183
    • 184
    • 185
    • 186
    • 187
    • 188
    • 189
    • 190
    • 191
    • 192
    • 193
    • 194
    • 195
    • 196
    • 197
    • 198
    • 199
    • 200
    • 201
    • 202
    • 203
    • 204
    • 205
    • 206
    • 207
    • 208
    • 209
    • 210
    • 211
    • 212
    • 213
    • 214
    • 215
    • 216
    • 217
    • 218
    • 219
    • 220
    • 221
    • 222
    • 223
    • 224
    • 225
    • 226
    • 227
    • 228
    • 229
    • 230
    • 231
    • 232
    • 233
    • 234
    • 235
    • 236
    • 237
    • 238
    • 239
    • 240
    • 241
    • 242
    • 243
    • 244
    • 245
    • 246
    • 247
    • 248
    • 249
    • 250
    • 251
    • 252
    • 253
    • 254
    • 255
    • 256
    • 257
    • 258
    • 259
    • 260
    • 261
    • 262
    • 263
    • 264
    • 265
    • 266
    • 267
    • 268
    • 269
    • 270
    • 271
    • 272
    • 273
    • 274
    • 275
    • 276
    • 277
    • 278
    • 279
    • 280
    • 281
    • 282
    • 283
    • 284
    • 285
    • 286
    • 287
    • 288
    • 289
    • 290
    • 291
    • 292
    • 293
    • 294
    • 295
    • 296
    • 297
    • 298
    • 299
    • 300
    • 301
    • 302
    • 303
    • 304
    • 305
    • 306
    • 307
    • 308
    • 309
    • 310
    • 311
    • 312
    • 313
    • 314
    • 315
    • 316
    • 317
    • 318
    • 319
    • 320
    • 321
    • 322
    • 323
    • 324
    • 325
    • 326
    • 327
    • 328
    • 329
    • 330

    重点内容 
    使用时直接进行引用using MyTools; 
    使用示例:

    helper.CreateNewWordDocument(System.Web.HttpContext.Current.Server.MapPath(“/MyFile/MyTools.dot”)); 
    helper.Replace(“手机号”, phonenum); 
    helper.Replace(“姓名”, name); 
    string strFileSavePath = System.Web.HttpContext.Current.Server.MapPath(“/File/MyTools.doc”); 
    helper.SaveAs(strFileSavePath); 
    helper.Close(); 
    string strPdfPath = System.Web.HttpContext.Current.Server.MapPath(“/File/MyTools.pdf”); 
    Aspose.Words.Document doc = new Aspose.Words.Document(strFileSavePath); 
    //保存为PDF文件,此处的SaveFormat支持很多种格式,如图片,epub,rtf 等等 
    doc.Save(strPdfPath, SaveFormat.Pdf);

    插入图片用到InsertPicture(string bookmark, string picturePath, float width, float hight);方法。 
    bookmark为dom文件中所标记的标签,picturePath为索要插入图片的路径,width、hight用来设置插入图片的宽和高。

    http://blog.csdn.net/yhd0916/article/details/52876077

  • 相关阅读:
    vscode编辑器markdow文档导出为pdf
    js 原型
    部分前端知识总结
    js获取本地ip
    angular项目线上地址跳转或刷新报错的解决
    一种js异步处理方式
    初始化git repo到远程
    点击任意位置隐藏键盘
    UIButton设置按钮点击范围大于可视范围
    Unknown class xxx in Interface Builder file. / NSUnknownKeyException
  • 原文地址:https://www.cnblogs.com/zcm123/p/6088974.html
Copyright © 2020-2023  润新知