由于业务需求,根据模板生成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);
//生成PDF
string 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);//savePath
context.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;
}
}
}
}