Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.IO;
- using System.Text;
- using Microsoft.Office.Interop.Word;
- namespace MyProjectNS
- {
- public class HtmlWordDocument : IDisposable
- {
- private Application application;
- private Document document;
- private string path;
- private bool editing;
- public enum DocumentSection { Content, Header, Footer }
- public HtmlWordDocument(string path)
- {
- this.path = path;
- this.editing = false;
- if (File.Exists(path)) File.Delete(path);
- application = new Application();
- if (editing)
- {
- document = application.Documents.Open(path, ReadOnly: false, Visible: false);
- }
- else
- {
- document = application.Documents.Add(Visible: false);
- }
- document.Activate();
- }
- public void Write(DocumentSection sectionType, string file)
- {
- try
- {
- if (sectionType == DocumentSection.Content)
- {
- application.Selection.InsertFile(file);
- }
- else
- {
- foreach (Section wordSection in document.Sections)
- {
- Range range;
- if (sectionType == DocumentSection.Header)
- range = wordSection.Headers[WdHeaderFooterIndex.wdHeaderFooterPrimary].Range;
- else
- range = wordSection.Footers[WdHeaderFooterIndex.wdHeaderFooterPrimary].Range;
- range.InsertFile(file);
- }
- }
- }
- catch (Exception ex)
- {
- ((_Document)document).Close(SaveChanges: false);
- ((_Application)application).Quit(SaveChanges: false);
- }
- }
- private void WriteSection(DocumentSection sectionType, string file)
- {
- Write(sectionType, file);
- }
- public void WriteContent(string file)
- {
- WriteSection(DocumentSection.Content, file);
- }
- public void WriteHeader(string file)
- {
- WriteSection(DocumentSection.Header, file);
- }
- public void WriteFooter(string file)
- {
- WriteSection(DocumentSection.Footer, file);
- }
- public void Save()
- {
- if (editing)
- {
- application.Documents.Save(true);
- }
- else
- {
- document.SaveAs(path);
- }
- }
- #region IDisposable Members
- public void Dispose()
- {
- ((_Document)document).Close(SaveChanges: true);
- ((_Application)application).Quit(SaveChanges: true);
- }
- #endregion
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement