/// <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) { object missing = Type.Missing; // ApplicationClass wordApp = null; Microsoft.Office.Interop.Word.Application wordApp = null; Document docNewWord = null; try { if (!IOUtility.CopyFile(contextPath, wordPath, true)) { LogUntitly.WriteLog(typeof(LhWordAddinUntitly), contextPath + "此路径文件不存在!"); return ""; } //File.Copy(contextPath, wordPath, true); //wordApp = new ApplicationClass(); wordApp = new Microsoft.Office.Interop.Word.Application();
//操作新合同文档 docNewWord = wordApp.Documents.Open(wordPath); 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);
//页眉格式调整 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); }
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) { LogUntitly.WriteLog(typeof(LhWordAddinUntitly), e); return ""; } finally { if (docNewWord != null) { object notsavechange = WdSaveOptions.wdDoNotSaveChanges; docNewWord.Close(ref notsavechange, ref missing, ref missing); } if (wordApp != null) { wordApp.Quit(); System.Runtime.InteropServices.Marshal.ReleaseComObject(wordApp); } } }
|