none
I failed to remove a blank page from a Word document by using C# Microsoft.Office.Interop.Word package RRS feed

  • Question

  • Dear friends,

    I was trying to delete a blank page from a Word document by using C# Microsoft.Office.Interop.Word package. But somehow I always failed, even after trying various methods:

    1) Delete all corresponding paragraphs within the blank page by using the Word.Range.Delete(Word.Paragraph) method;

    2) Delete the full blank page by using the Word.Paragraph.Range.Delete() method;

    3) Delete the blank page by continuously inputting the Backspace key, using the method Word.Application.Selection.TypeBackspace();

    4) Delete all content between two bookmarks (in the start and end of the blank page respectively) by using the method Word.Range.Delete();

    The full set of the C# source codes is listed below.

    Note: I also need to raise a question: how can I upload and share the sample Word document into this MSDN forum? 

    Thank you for any help.

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Text.RegularExpressions;
    using System.IO;
    using System.Data;
    using System.Reflection;
    using Word = Microsoft.Office.Interop.Word;
    using System.Runtime.InteropServices;
    using Microsoft.Office.Core;
    using System.Drawing;
    using System.Diagnostics;
    
    using System.Timers;
    using System.Windows.Forms;
    
    using Process = System.Diagnostics.Process;
    using System.Collections;
    
    namespace getWordPages
    {
        public partial class Form1 : Form
        {
            Word.Application WordApplication;
            Word._Document Doc;
    
            public Form1()
            {
                InitializeComponent();
            }
    
            ~Form1()
            {
                if (Doc != null)
                    Doc.Close(0);
    
                if (WordApplication != null)
                    WordApplication.Quit();
    
                Doc = null;
                WordApplication = null;
            }
    
            private void label1_Click(object sender, EventArgs e)
            {
    
            }
    
            private void button1_Click(object sender, EventArgs e)
            {
                string filename = tbWordDoc.Text;
                string[] Pages = GetPagesDoc(filename);
                tbPageNo.Text = tbPageNo.Text.Trim();
                int iPageNum = Convert.ToInt32(tbPageNo.Text);
                tbPageContent.Text = Pages[iPageNum-1];
            }
    
            private bool emptyText(string text, ref int nLines)
            {
                bool res = true;
                nLines = 0;
                foreach( char ch in text)
                {
                    if ((ch >= ' ') && (ch <= 127))
                        res = true;
                    else
                        nLines++;
                }
                return (res);
            }
    
            private bool isBlankPage(Word.Range range, ref int nLines)
            {
                if (range.Bookmarks.Count > 0)
                    return false;
                if( range.FormFields.Count > 0 )
                    return false;
                if (range.Frames.Count > 0)
                    return false;
                if (range.Hyperlinks.Count>0)
                    return false;
                if (range.InlineShapes.Count > 0)
                    return false;
                if (range.ShapeRange.Count > 0)
                    return false;
                if (range.Tables.Count > 0)
                    return false;
                if (!emptyText(range.Text, ref nLines))
                    return false;
                return (true);
            }
    
            public string[] GetPagesDoc(object Path)
            {
                List<string> Pages = new List<string>();
    
                // Get application object
                WordApplication = new Word.Application();
                WordApplication.Visible = true;
                // WordApplication.Visible = false;
    
                // Get document object
                object Miss = System.Reflection.Missing.Value;
                object ReadOnly = false;
                object Visible = true;
                Doc = WordApplication.Documents.Open(ref Path, ref Miss, ref ReadOnly, ref Miss, ref Miss, ref Miss, ref Miss, ref Miss, ref Miss, ref Miss, ref Miss, ref Visible, ref Miss, ref Miss, ref Miss, ref Miss);
    
                // Get pages count
                Word.WdStatistic PagesCountStat = Word.WdStatistic.wdStatisticPages;
                int PagesCount = Doc.ComputeStatistics(PagesCountStat, ref Miss);
    
                Doc.Activate();
    
                //Get pages
                object What = Word.WdGoToItem.wdGoToPage;
                object Which = Word.WdGoToDirection.wdGoToAbsolute;
                object Start;
                object End;
                object CurrentPageNumber;
                object NextPageNumber;
    
                Word.Range wordRange;
                int nLines = 0;
    
                for (int Index = 1; Index <= PagesCount; Index++)
                {
                    CurrentPageNumber = (Convert.ToInt32(Index.ToString()));
                    NextPageNumber = (Convert.ToInt32((Index + 1).ToString()));
    
                    // Get start position of current page
                    Start = WordApplication.Selection.GoTo(ref What, ref Which, ref CurrentPageNumber, ref Miss).Start;
    
                    // Get end position of current page                                
                    End = WordApplication.Selection.GoTo(ref What, ref Which, ref NextPageNumber, ref Miss).End;
    
                    // Get text
                    if (Convert.ToInt32(Start.ToString()) != Convert.ToInt32(End.ToString()))
                    {
                        wordRange = Doc.Range(ref Start, ref End);
                        Pages.Add(wordRange.Text);
                    }
                    else
                    {
                        wordRange = Doc.Range(ref Start);
                        Pages.Add(wordRange.Text);
                    }
                    if( Index == 2 )
                    {
                        int bookmark_cnt = wordRange.Bookmarks.Count;
                        int formfield_cnt = wordRange.FormFields.Count;
                        int frame_cnt = wordRange.Frames.Count;
                        int hyperlink_cnt = wordRange.Hyperlinks.Count;
                        int table_cnt = wordRange.Tables.Count;
                        int inlineshape_cnt = wordRange.InlineShapes.Count;
                        int shaperange_cnt = wordRange.ShapeRange.Count;
                        int paragraph_cnt = wordRange.Paragraphs.Count;
                        int section_cnt = wordRange.Sections.Count;
                        int sentence_cnt = wordRange.Sentences.Count;
                    }
                    if (isBlankPage(wordRange, ref nLines))
                        deletePageByBackspace(wordRange, 2*nLines);
                }
                // deleteBetweenBookmarks("Start_Bookmark", "End_Bookmark");
                return Pages.ToArray<string>();
            }
    
            private void deleteBetweenBookmarks(string startBookmark, string endBookmark)
            {
                Word.Range range = Doc.Range();
                range.Start = Doc.Bookmarks.get_Item(startBookmark).Range.Start;
                range.End = Doc.Bookmarks.get_Item(endBookmark).Range.End;
                range.Delete();
            }
    
            private void deletePage(Word.Range range, int nLines)
            {
                string newline = "\r";
                foreach (Word.Paragraph para in range.Paragraphs)
                {
                    if (para.ToString().Contains(newline))
                    {
                        para.Range.Select();
                        range.Delete(para);
                    }
                }
            }
    
            private void deleteFullPage(Word.Range range)
            {
                foreach (Word.Paragraph para in range.Paragraphs)
                {
                    para.Range.Select();
                    para.Range.Delete();
                }
            }
    
            private void deletePageByBackspace(Word.Range range, int nLines)
            {
                object oMissing = System.Reflection.Missing.Value;
                object what = Word.WdGoToItem.wdGoToPercent;
                object which = Word.WdGoToDirection.wdGoToLast;
    
                range.Select();
                // range.Delete(Type.Missing);
                for (int i = 0; i < nLines; i++)
                    WordApplication.Selection.TypeBackspace();
            }
    
    
            public static void KillProcesses(string processName)
            {
                Process[] _allProcesses = Process.GetProcessesByName(processName);
    
                // check to kill the right process
                foreach (Process currentProcess in _allProcesses)
                {
                    currentProcess.Kill();
                }
            }
            private void label1_Click_1(object sender, EventArgs e)
            {
    
            }
            private void textBox1_TextChanged(object sender, EventArgs e)
            {
    
            }
    
            private void button2_Click(object sender, EventArgs e)
            {
                Environment.Exit(0);
            }
        }
    }
    


    Sunday, April 21, 2019 12:40 PM

All replies

  • Hello,

    First off when posting source code use a code block

    Second, you can't upload source code to these forums. Instead create a zip file (not rar or other formats) and place it on your Microsoft OneDrive, same login as here.

    Third, this forum is for C#, your post is better off in the Word for developer form where it's not a language based forum e.g. C# or VB.NET. This forum may have better recommendations for you so I'm moving your question there.

    Last thing, when posting code remove event events such as Label1_Click_1 etc,


    Please remember to mark the replies as answers if they help and unmarked them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.

    NuGet BaseConnectionLibrary for database connections.

    StackOverFlow
    profile for Karen Payne on Stack Exchange

    Sunday, April 21, 2019 12:54 PM
  • Dear Friends,

    Just now I uploaded my sample Word Document with a blank page here:

    https://onedrive.live.com/edit.aspx?cid=8ffa4a1c66cfced9&page=view&resid=8FFA4A1C66CFCED9!281&parId=8FFA4A1C66CFCED9!280&app=Word

    Also I have uploaded the screenshot showing the blank page at the URL below:

    https://onedrive.live.com/?cid=8FFA4A1C66CFCED9&id=8FFA4A1C66CFCED9%21288&parId=8FFA4A1C66CFCED9%21282&o=OneUp

    Please try to help me to remove the blank page by using C# Microsoft.Office.Interop.Word package. If anybody can remove the blank page using C# program, please kindly show me the piece of source codes. 

    Thanks!

    moonriver

    Monday, April 22, 2019 12:46 AM