由于业务需求,根据模板生成word .而我们的模板是使用vsto开发的wps 插件。在生成word 以后需要生成pdf。需求如下:

1、下载是带水印

2、将其中零时编号改成正式编号(审批通过的编号)

3、去掉之前控件背景色

4、生成pdf

完整代码如下:这是一个一般处理程序.ashx

using Microsoft.Office.Interop.Word;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Web;
using Woo.Utility;
using WooDataEntity;namespace Web.ModuleBusiness.ContractText
{/// <summary>/// SaveWpsPDF 的摘要说明/// </summary>public class SaveWpsPDF : IHttpHandler{public void ProcessRequest(HttpContext context){WCMSDATA wd = DataEntity.Initializes();string textId = context.Request["Id"];string previewType = context.Request["previewType"];WOO_CONT_TEXT cont_text = wd.WOO_CONT_TEXT.First(p => p.ID == Convert.ToInt32(textId));var contract = wd.WOO_CONTRACT.First(h => h.ID == Convert.ToInt32(cont_text.CONTRACT_ID));//获取机构下的手印路径var water = contract.MAIN_DEPARTMENT_.WATER_MARK;var is_wateremark = contract.IS_WATERMARK;//if (is_wateremark == 0)//不带 水印//{//    return;//}string newContractNo = contract.NO;string fileName = is_wateremark == 0 ? "ContractTextWordTemplate.docx" : System.IO.Path.GetFileName(water);// context.Request["filename"] == null ? "ContractTextWordTemplate.docx" : context.Request["filename"];string pdfFileName = "";if (fileName.IndexOf('.') > 0){pdfFileName = fileName.Substring(0, fileName.LastIndexOf('.'));}string dir = HttpContext.Current.Request.PhysicalApplicationPath;string date = string.Format("{0}-{1}-{2}-{3}-", DateTime.Now.ToString("yyyy-M-d"), DateTime.Now.Hour, DateTime.Now.Minute, DateTime.Now.Second);string savePath = string.Format("{0}Upload\\TextField\\{1}", dir, pdfFileName + ".pdf");string newWordPath = string.Format("{0}Upload\\TextField\\{1}{2}", dir, date, "newWord.docx");string contextPath = "";string templatePath = string.Format("{0}Upload\\WordTemplate\\{1}", dir, fileName);//"ContractTextWordTemplate.docx");string filePath = cont_text.PATH;string firstDir = "", endFileName = "", showPdf = "";if (filePath.LastIndexOf(".pdf") < 0)//没转换pdf{var fileNameSub = filePath == "" ? "" : filePath.Substring(filePath.LastIndexOf('/'));contextPath = string.Format("{0}Upload\\TextField\\{1}", dir, fileNameSub);//生成PDFstring reValue = ConvertPDF(templatePath, savePath, newWordPath, contextPath, newContractNo);if (reValue != ""){firstDir = filePath.Substring(0, filePath.LastIndexOf('/'));endFileName = savePath.Substring(savePath.LastIndexOf("\\") + 1);showPdf = firstDir + "/" + endFileName;cont_text.PATH = firstDir + "/" + endFileName;wd.SubmitChanges();}else{context.Response.ContentType = "text/plain";context.Response.Write(showPdf);return;}}if ("showPdf".Equals(previewType)){if ("".Equals(showPdf)){firstDir = filePath.Substring(0, filePath.LastIndexOf('/'));endFileName = savePath.Substring(savePath.LastIndexOf("\\") + 1);showPdf = firstDir + "/" + endFileName;}context.Response.ContentType = "text/plain";context.Response.Write(showPdf);}else{//实现下载FileInfo fileInfo = new FileInfo(savePath);//savePathcontext.Response.Clear();context.Response.ClearContent();context.Response.ClearHeaders();context.Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(fileInfo.Name, Encoding.UTF8));context.Response.AddHeader("Content-Length", fileInfo.Length.ToString());context.Response.AddHeader("Content-Transfer-Encoding", "binary");context.Response.ContentType = "application/octet-stream";context.Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8");context.Response.WriteFile(fileInfo.FullName);context.Response.Flush();context.Response.End();}}public string updateContText(string textId, string pdfPath){WCMSDATA wd = DataEntity.Initializes();WOO_CONT_TEXT cont_text = wd.WOO_CONT_TEXT.First(p => p.ID == Convert.ToInt32(textId));string filePath = cont_text.PATH;string firstDir = "", endFileName = "";if (filePath.LastIndexOf(".pdf") < 0)//没转换pdf{firstDir = filePath.Substring(0, filePath.LastIndexOf('/'));endFileName = pdfPath.Substring(pdfPath.LastIndexOf("\\") + 1);cont_text.PATH = firstDir + "/" + endFileName;wd.SubmitChanges();return pdfPath;}else{return filePath;}}/// <summary>/// 生成水印PDF/// </summary>/// <param name="templatePath">水印模板</param>/// <param name="savePath">保存PDF的路径</param>/// <param name="wordPath">Copy的新word模板</param>/// <param name="contextPath">合同文本</param>public string ConvertPDF(string templatePath, string savePath, string wordPath, string contextPath, string contractNo){Application wordApp = null;try{File.Copy(contextPath, wordPath, true);wordApp = new Application();//操作新合同文档Document docNewWord = wordApp.Documents.Open(wordPath);//DocProtectOrUnProtect(wordApp,1);SetRichTextContentValue(IsReView:true, wordApp, docNewWord);Document docWaterMark = wordApp.Documents.Add(templatePath);//使用word模板添加构建基块Template template = (Template)docNewWord.get_AttachedTemplate();Range templateHeaderRange = docNewWord.Sections[1].Headers[WdHeaderFooterIndex.wdHeaderFooterPrimary].Range;WdParagraphAlignment headerAlignment = templateHeaderRange.ParagraphFormat.Alignment;Range waterHeaderRange = docWaterMark.Sections[1].Headers[WdHeaderFooterIndex.wdHeaderFooterPrimary].Range;BuildingBlock waterMark = template.BuildingBlockEntries.Add("newWaterMark", WdBuildingBlockTypes.wdTypeWatermarks, "General", waterHeaderRange);//插入已添加到模板的水印生成块templateHeaderRange.Collapse(WdCollapseDirection.wdCollapseEnd);waterMark.Insert(templateHeaderRange, true);//docWaterMark.Content.Copy();//var leftWidth = docWaterMark.PageSetup.LeftMargin;//var rightWidth = docWaterMark.PageSetup.RightMargin;//var topWidth = docWaterMark.PageSetup.TopMargin;//var bottomWidth = docWaterMark.PageSetup.BottomMargin;//var seekView = docWaterMark.ActiveWindow.ActivePane.View.SeekView;//读取模板文件,模板路径是固定的//Document docTemplate = wordApp.Documents.Open(wordPath);//docTemplate.Content.PasteSpecial(Type.Missing, Type.Missing, Type.Missing, Type.Missing, WdPasteDataType.wdPasteRTF);//docTemplate.PageSetup.LeftMargin = leftWidth;//docTemplate.PageSetup.RightMargin = rightWidth;//docTemplate.PageSetup.TopMargin = topWidth;//docTemplate.PageSetup.BottomMargin = bottomWidth;//docWaterMark.ActiveWindow.ActivePane.View.SeekView = seekView;//页眉格式调整Range rg = docNewWord.Sections[1].Headers[WdHeaderFooterIndex.wdHeaderFooterPrimary].Range;var rText = rg.Text.Replace("\r", "").Replace("\n", "");var leng = rText.Length;if (leng > 0){docNewWord.Sections[1].Borders[WdBorderType.wdBorderBottom].LineStyle = WdLineStyle.wdLineStyleNone;rg.ParagraphFormat.Alignment = headerAlignment;rg.Collapse(WdCollapseDirection.wdCollapseEnd);rg.MoveStart(WdUnits.wdCharacter, 1);rg.Delete(WdUnits.wdCharacter, 1);}//更新合同编号foreach (ContentControl CCtrl in docNewWord.SelectContentControlsByTitle("合同编号")){CCtrl.LockContentControl = false;CCtrl.LockContents = false;CCtrl.Range.Text = contractNo;}docNewWord.Save();docNewWord.ActiveWindow.View.Type = WdViewType.wdNormalView;docNewWord.ActiveWindow.View.Type = WdViewType.wdPrintView;docNewWord.ActiveWindow.View.ShowRevisionsAndComments = false;docNewWord.ExportAsFixedFormat(savePath, WdExportFormat.wdExportFormatPDF);return "ok";}catch (Exception e){return "";e.Message.ToString();LogUtility.WriteErrorLog(e);}finally{wordApp.Quit();System.Runtime.InteropServices.Marshal.ReleaseComObject(wordApp);}}/// <summary>/// 去掉控件所有样式/// </summary>/// <param name="IsReView">true:预览</param>public static void SetRichTextContentValue(bool IsReView, Application wordApp, Document document){DocProtectOrUnProtect(wordApp,1);//取消文档保护//Document currentDocument = document;//WordTool.Document document = Globals.Factory.GetVstoObject(currentDocument);foreach (ContentControl nativeControl in document.ContentControls){if (nativeControl.Type == Microsoft.Office.Interop.Word.WdContentControlType.wdContentControlRichText){nativeControl.LockContents = false;nativeControl.LockContentControl = false;nativeControl.Range.Shading.BackgroundPatternColor = WdColor.wdColorWhite;nativeControl.Range.Shading.ForegroundPatternColor = WdColor.wdColorWhite;nativeControl.LockContentControl = true;nativeControl.LockContents = true;}}//if (!IsReView)//{//    WordBarsUtility.ExcuteCommbandBarMso("ReviewTrackChanges");//}}#region 加密解密/// <summary>/// 设置文档状态/// </summary>/// <param name="State">0:标识锁定,其他标识解锁</param>/// <param name="protType">/// 锁定时的状态:/// 比如:MsWord.WdProtectionType.wdAllowOnlyFormFields 标示文档锁定了,但是文档内容控件是可以编辑的/// </param>public static void DocProtectOrUnProtect(Application wordApp, int State = 0, WdProtectionType protType = WdProtectionType.wdAllowOnlyComments){Object missing = Type.Missing;Object Password = "2021111111195B13B93E52C7C1FD2D2A1F341844C71QAZ";//WordShare.WordPassword;别动与插件必须一致if (State == 0){DocProtect(protType, wordApp, ref missing, ref Password);}else{Password = DocUnprotect(Password, wordApp);}wordApp.ActiveDocument.Save();}/// <summary>/// 加密/// </summary>/// <param name="protType">文档类型</param>/// <param name="missing">System.Type</param>/// <param name="Password">密码</param>private static void DocProtect(WdProtectionType protType, Application wordApp, ref Object missing, ref Object Password){object objFalse = true;if (wordApp.ActiveDocument.ProtectionType != WdProtectionType.wdNoProtection){wordApp.ActiveDocument.Unprotect(ref Password);}//在加密wordApp.ActiveDocument.Protect(protType, ref objFalse, ref Password, ref missing, ref missing);}/// <summary>/// 解密/// </summary>/// <param name="Password"></param>/// <returns></returns>private static object DocUnprotect(Object Password, Application wordApp){if (wordApp.ActiveDocument.ProtectionType != WdProtectionType.wdNoProtection){wordApp.ActiveDocument.Unprotect(ref Password);}return Password;}#endregion 加密解密private string createWords(ApplicationClass wordApp, string wordPath){if (File.Exists(wordPath)){File.Delete(wordPath);}object path;string strContent;path = wordPath;Object Nothing = Missing.Value;Document wordDoc = wordApp.Documents.Add(ref Nothing, ref Nothing, ref Nothing, ref Nothing);strContent = "你好!\n";wordDoc.Paragraphs.Last.Range.Text = strContent;object format = Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatDocumentDefault;//将wordDoc文档对象的内容保存为DOCX文档wordDoc.SaveAs(ref path, ref format, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing);//关闭wordDoc文档对象wordDoc.Close(ref Nothing, ref Nothing, ref Nothing);return (string)path;}public bool IsReusable{get{return false;}}}
}

C# word 转换成pdf 并且修改其中控件内容相关推荐

  1. word转换成pdf,包括导航目录和图片不变黑

    1.word转换成pdf,包括导航目录和图片不变黑: 有些时候将word转换成pdf,我们会发现生成的文件要么不带导航目录,要么就是图片显示有问题,比如变黑.变黑是因为某些图片在作图时修改了透明度,因 ...

  2. 迅捷word转换成pdf转换器最新版

    怎样把Word转换成PDF格式的好呢?随着PDF格式文件使用的范围越来越广,很多时候我们就需要把Word格式转换成PDF进行使用,很多朋友都会觉得手上都没有辅助软件而无法进行操作.也可能是没有找到正确 ...

  3. 能把word转换成pdf好用的工具

    在很多工作当中都会遇到PDF文件格式的转换问题,却因为目前互联网上存在的PDF转换器质量的差别,导致了转换出来的文件质量参差不齐.所以很多人在寻找PDF转换器的时候往往不知道怎样去选择一款真正具备高质 ...

  4. 好用的word转换成pdf转换器!你值得拥有

    平时工作的时候,我们常常使用word文档对一些内容进行编辑和修改,但是你想将文档发给另一个人,但是又担心对方不小心修改到你的文档内容的话,就可以将word文档转换成pdf,然后再发送给对方,这样对方查 ...

  5. word转换成pdf转换器

    word转换成pdf转换器     很多朋友向我苦诉,经常办公中遇到PD格式转换时,用普通的PDF转化出来的文字都成一堆密密麻麻的乱码字,内容也缩短了不少,里面的插图都转换不了,这时候她们不得不花上大 ...

  6. WORD转换成PDF转换器2015官方版?

    WORD转换成PDF转换器2015官方版 Word是我们工作中或多或少都要接触的文件格式,自己做一份文件的话一般都是以Word来做,因为是最常用的一种文档.可是当我们做出的文件要发给同事或者领导的话, ...

  7. C# 使用Microsoft.Office.Interop将Excel、Word转换成PDF遇到的问题总结

    首先应用中引入Microsoft.Office.Interop.Excel.Microsoft.Office.Interop.Word两个dll,将嵌入式互操作类型设为False, WORD转换成PD ...

  8. 用什么方法可以将Word转换成PDF文档?

    我们有时编辑完Word文件需要打印或发送给他人查看,一般会先转换为PDF格式,这样在别的电脑上打开时就不会出现格式的变动,也不会出现因为版本而无法打开的问题,那么用什么方法可以将Word转换成PDF文 ...

  9. 生成目录_将word转换成PDF

    word2010生成目录_将word转换成PDF.doc 一, 概要 1.1 在 Microsoft Word2010 中 自动 生成目录 1.2 在 WPS 中 将 word 转换 成 PDF 1. ...

最新文章

  1. 有空间感的图片环形滚动代码
  2. BUTTONS V. 2.0.0——CSS按钮库
  3. JAVA设计模式--结构型模式
  4. 源码安装gcc各种情况的解决
  5. S3C2440扩展SDRAM
  6. Django(一)预热
  7. 剖析Caffe源码之Blob
  8. 20145226夏艺华 《Java程序设计》第2周学习总结
  9. 调整手机titlebar与app的titlebar相衔接
  10. qt 按钮 gradient_少造轮子!推荐一个Qt的Python组件库
  11. Toad:基于 Python 的标准化评分卡模型
  12. 云计算与大数据技术应用2020.10.21
  13. 立体视觉相机使用JetsonTX2提升图像
  14. 一文彻底读懂三极管的工作原理,最通俗的解释,看完就明白了!
  15. js将中国标准时间转化为年月日时分秒(yyyy-mm-dd)格式以及时间戳,日期,天数之间的转换
  16. 亚马逊又收新费用;沃尔玛销售不合格产品被罚超34万;长荣10亿美元将订造26艘新船…|洞悉跨境
  17. 融云CEO韩迎:如何基于云通讯构建企业竞争力
  18. 批判马斯洛需求层次模型
  19. 全球及中国反渗透膜市场品牌竞争格局与应用前景调研报告2022年
  20. 腾讯文字识别API使用

热门文章

  1. java no arguments_java中的arguement是什么意思?
  2. python处理金融数据_Python之获取与简单处理金融数据
  3. 这两款好用的配音软件,自媒体小白也能轻松上手
  4. 友盟QQ第三方授权登陆(精简)
  5. 湖北省小学生计算机大赛,喜讯!我市文昌小学雷梓铭斩获湖北省中小学电脑制作活动创客项目一等奖...
  6. VS下实现将多张图片合成视频
  7. WIN10 锐炬核显 屏幕显示方向快捷键设置 启用/关闭
  8. Linux虚拟机克隆一键修改IP脚本 伸手党速速来取
  9. pajek03-05:分类
  10. 保险公司全面预算管理