Я пытаюсь избавиться от пустых страниц, которые сливаются, когда пользователи просматривают и печатают документ. Я использую редактор Dev express, поэтому пользователь вставляет текст, который переводит страницу на другую страницу (rtf), и создает пустое пространство. любой способ остановить это?>asp.net Microsoft.Office.Interop.Word
вот мой код:
using System;
using System.Collections.Generic;
using System.Drawing.Imaging;
using System.Linq;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Linq;
using DocumentFormat.OpenXml.Packaging;
using Microsoft.Office.Interop.Word;
using WordApplication = Microsoft.Office.Interop.Word.Application;
namespace DocumentMapper
{
public class XmlDocumentMapper
{
/// <summary>
/// Use to replace all text elements included in template text.
/// </summary>
/// <param name="mergeDocInfo"></param>
/// <param name="html"></param>
/// <returns></returns>
public static string MergeHtml(MergeDocInfo mergeDocInfo, string html)
{
return MergeText(mergeDocInfo.MergeValues, html);
}
public static string MergeHtml(Dictionary<string, string> mergeValues, string html)
{
return MergeText(mergeValues, html);
}
public static string MergeHtml(MergeDocInfo mergeDocInfo)
{
string htmlText = null;
string template = string.Format("{0}{1}", mergeDocInfo.TemplatePath, mergeDocInfo.TemplateName.Replace(".docx", ".html"));
using (Stream stream = new FileStream(template, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
using (StreamReader sr = new StreamReader(stream))
{
htmlText = sr.ReadToEnd();
}
}
return MergeText(mergeDocInfo.MergeValues, htmlText);
}
public static void SearchAndReplace(MergeDocInfo mergeDocInfo)
{
string template = string.Format("{0}{1}", mergeDocInfo.TemplatePath, mergeDocInfo.TemplateName);
string document = string.Format("{0}{1}", mergeDocInfo.MergeDocPath, mergeDocInfo.MergeDocName);
using (Stream stream = new FileStream(template, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
using (WordprocessingDocument wordTemplate = WordprocessingDocument.Open(stream, false))
using (WordprocessingDocument wordDocument = WordprocessingDocument.Create(document, DocumentFormat.OpenXml.WordprocessingDocumentType.Document))
{
foreach (var part in wordTemplate.Parts)
wordDocument.AddPart(part.OpenXmlPart, part.RelationshipId);
string docText = null;
using (StreamReader sr = new StreamReader(wordTemplate.MainDocumentPart.GetStream()))
{
docText = sr.ReadToEnd();
}
docText = MergeText(mergeDocInfo.MergeValues, docText);
using (StreamWriter sw = new StreamWriter(wordDocument.MainDocumentPart.GetStream(FileMode.Create)))
{
sw.Write(docText);
}
}
FileInfo tempFile = new FileInfo(document);
FileInfo mergeFile = new FileInfo(document.Replace(".docx", ".pdf"));
DoIt(tempFile, mergeFile);
}
private static string MergeText(Dictionary<string, string> mergeValues, string text)
{
var dateValues = new Dictionary<string, string>();
foreach (KeyValuePair<string, string> pair in mergeValues)
{
DateTime dt;
if (DateTime.TryParse(pair.Value, out dt))
{
dateValues.Add(pair.Key, pair.Value);
}
}
foreach (KeyValuePair<string, string> pair in dateValues)
{
mergeValues[pair.Key] = DateTime.Parse(pair.Value).ToShortDateString();
}
foreach (KeyValuePair<string, string> pair in mergeValues)
{
if (!string.IsNullOrEmpty(pair.Key))
{
text = new Regex(pair.Key).Replace(text, string.IsNullOrEmpty(pair.Value) ? "_____" : pair.Value);
}
}
return text;
}
/// <summary>
/// Obsolete
/// </summary>
/// <param name="tempFile"></param>
/// <param name="mergeFile"></param>
private static void DoIt(FileInfo tempFile, FileInfo mergeFile)
{
WordApplication word = new WordApplication()
{
Visible = false,
ScreenUpdating = false
};
object oMissing = System.Reflection.Missing.Value;
Object filename = (Object)tempFile.FullName;
Document doc = word.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);
doc.Activate();
object outputFileName = (Object)mergeFile.FullName;
object fileFormat = WdSaveFormat.wdFormatPDF;
doc.SaveAs(ref outputFileName,
ref fileFormat, 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);
object saveChanges = WdSaveOptions.wdDoNotSaveChanges;
((_Document)doc).Close(ref saveChanges, ref oMissing, ref oMissing);
doc = null;
((_Application)word).Quit(ref oMissing, ref oMissing, ref oMissing);
word = null;
tempFile.Delete();
}
}
}
Корпорация Майкрософт настоятельно рекомендует использовать автоматизацию Office (и, следовательно, Word Interop) на сервере. Прежде чем перейти к чему-либо еще, я бы предложил рефакторинг для удаления кода автоматизации из любых связанных с сервером процессов, возможно, путем получения пользовательских запросов и запуска автоматизации в автономном режиме, которые будут отправлены пользователю позже. https://support.microsoft.com/en-us/kb/257757 – maniak1982
При написании вопроса о переполнении стека задайте свой вопрос заголовком, который соответствующим образом описывает проблему (не просто бросайте теги в заголовок) и потратьте некоторое время, убедившись, что ваш вопрос имеет правильную грамматику. – mason