使用Microsoft Word.interop删除Word文档中的空白页 [英] Blank page removal in a word document using microsoft word.interop

查看:377
本文介绍了使用Microsoft Word.interop删除Word文档中的空白页的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个Word文档,该文档使用 word.interop 生成动态内容.两者之间使用了分页符.我面临的问题是,此页面中断将创建空白页面,而这些页面我不想显示给用户.

I have created a word document which generates dynamic contents using word.interop. It has some page breaks used in between. what is the problem which I am facing is, this page breaks creates blank pages which I don't want to show to users.

在某些情况下,我需要在那里使用那些分页符以维持页面布局,因此我无法考虑删除那些分页符.但是我想要的是另一种解决方案,例如,如果特定页面中除了分页符之外没有任何内容,请删除该页面.

In some cases I need those page breaks there in order to maintain the page layout, so I can't think about removing those page breaks. but what I want is another solution like, in case if there no contents in a particular page other than a page break, remove that page.

我该如何做到这一点,请帮忙. 在此先感谢.

How can I accomplish this, please help.. Thanks in advance..

推荐答案

    private bool RemoveBlankPage()
    {
        Word.Application wordapp = null;
        Word.Document doc = null;
        Word.Paragraphs paragraphs=null;
        try
        {
            // Start Word APllication and set it be invisible
            wordapp = new Word.Application();
            wordapp.Visible = false;
            doc = wordapp.Documents.Open(wordPath);
            paragraphs = doc.Paragraphs;
            foreach (Word.Paragraph paragraph in paragraphs)
            {
                if (paragraph.Range.Text.Trim() == string.Empty)
                {
                    paragraph.Range.Select();
                    wordapp.Selection.Delete();
                }
            }

            // Save the document and close document
            doc.Save();
            ((Word._Document)doc).Close();

            // Quit the word application
            ((Word._Application)wordapp).Quit();

        }
        catch(Exception ex)
        {
            MessageBox.Show("Exception Occur, error message is: "+ex.Message);
            return false;
        }
        finally
        { 
            // Clean up the unmanaged Word COM resources by explicitly
            // call Marshal.FinalReleaseComObject on all accessor objects
            if (paragraphs != null)
            {
                Marshal.FinalReleaseComObject(paragraphs);
                paragraphs = null;
            }
            if (doc != null)
            {
                Marshal.FinalReleaseComObject(doc);
                doc = null;
            }
            if (wordapp != null)
            {
                Marshal.FinalReleaseComObject(wordapp);
                wordapp = null;
            }
        }

        return true;
    }

此链接帮助我完成了项目

This link helped me complete my project

https://code.msdn.microsoft. com/office/How-to-remove-blank-pages-e200755d

这篇关于使用Microsoft Word.interop删除Word文档中的空白页的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆