在C#中添加水印图像 [英] Add watermark image in c#

查看:105
本文介绍了在C#中添加水印图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个小代码在doc文件中添加水印图像,只有一个小问题,如果我将它一次转换就可以了,但是如果我尝试转换另一个文件会给我这个错误:

I have this little code to add a watermark image in a doc file, only have a little issue, if i convert it one time it works ok, but if i try to convert another file gives me this error:

RPC服务器不可用. (来自HRESULT的异常:0x800706BA)

The RPC server is unavailable. (Exception from HRESULT: 0x800706BA)

在此行:

wordFile = oWord.Documents.Open(row.filename);

wordFile = oWord.Documents.Open(row.filename);

这是我的代码:

Microsoft.Office.Interop.Word.Application oWord = new Microsoft.Office.Interop.Word.Application();
        Document wordFile = new Document();

        //OTHER VARIABLES
        Object oClassType = "Word.Document.8";
        Object oTrue = true;
        Object oFalse = false;
        Object oMissing = System.Reflection.Missing.Value;

private void BtnInserirImagem_Click(object sender, RoutedEventArgs e)
        {
            foreach(MyDocsList row in dataGridList.Items)
            {
                wordFile = oWord.Documents.Open(row.filename);
                addWatermark(wordFile, row.filename);

                //QUITTING THE APPLICATION
                oWord.Quit(ref oMissing, ref oMissing, ref oMissing);
            }
        }

        private void addWatermark(Document doc, string filename)
        {
            object refmissing = System.Reflection.Missing.Value;
            string watermarkPath = Directory.GetCurrentDirectory() + "\\fundo.jpg";

            if (File.Exists(watermarkPath))
            {

                object linkToFile = false;
                object saveWithDocument = true;

                WdHeaderFooterIndex hfIndex = WdHeaderFooterIndex.wdHeaderFooterPrimary;

                HeaderFooter headerFooter;

                for (int i = 1; i < doc.Sections.Count + 1; i++)
                {

                    if (doc.Sections[i].Headers != null)
                    {
                        headerFooter = doc.Sections[i].Headers[hfIndex];
                    }
                    else if (doc.Sections[i].Footers != null)
                    {
                        headerFooter = doc.Sections[i].Footers[hfIndex];
                    }
                    else
                    {
                        headerFooter = null;
                    }

                    if (headerFooter != null)
                    {

                        try
                        {
                            Microsoft.Office.Interop.Word.Shape watermarkShape;
                            watermarkShape = headerFooter.Shapes.AddPicture(watermarkPath, ref linkToFile, ref saveWithDocument, ref refmissing,
                                                                            ref refmissing, ref refmissing, ref refmissing, ref refmissing);

                            watermarkShape.Left = Convert.ToSingle(WdShapePosition.wdShapeLeft);
                            watermarkShape.Top = Convert.ToSingle(WdShapePosition.wdShapeCenter);
                        }
                        catch (System.Runtime.InteropServices.COMException e)
                        {
                            MessageBoxResult result = MessageBox.Show(String.Format("{0} - Error Code = {1}", e.Message, e.ErrorCode));
                            throw e;
                        }
                    }
                }

                oWord.ActiveWindow.View.SeekView = WdSeekView.wdSeekMainDocument;
                oWord.ActiveWindow.ActivePane.View.Type = Microsoft.Office.Interop.Word.WdViewType.wdPrintView;
            }
            else
            {
                MessageBoxResult result = MessageBox.Show("Could not find watermark image");
            }

            //THE LOCATION WHERE THE FILE NEEDS TO BE SAVED
            string outstringFile="";
            string pathfile = System.IO.Path.GetDirectoryName(filename);
            string filenameFile = System.IO.Path.GetFileName(filename);
            outstringFile = pathfile + "\\OG" + filenameFile;

            Object oSaveAsFile = (Object)(outstringFile);

            wordFile.SaveAs(ref oSaveAsFile, 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);


            //CLOSING THE FILE
            wordFile.Close(ref oFalse, ref oMissing, ref oMissing);


        }

推荐答案

来自

首次以编程方式启动Word时,它会通过RPC服务器连接到Word.当您关闭文档时,该服务器将在您的应用程序不知道的情况下关闭.解决方案是捕获错误并重新初始化Word对象.您将可以继续.

When you first launch Word programmatically, it connects to Word via an RPC server. When you close the document, this server gets closed without your application knowing about it. The solution is to trap an error and re-initialise your Word object. you will then be able to continue.

您只能在外部初始化oWord对象.然后,您将在第一次运行时在foreach循环中对其调用.Quit()方法,此后不再可用.您将必须删除BtnInserirImagem_Click中的oWord.Quit();并使用一个不断初始化的单词对象,或者可以在需要时对其进行初始化,然后在其上调用quit.

You initialize your oWord object outside and only once. Then you are calling the .Quit() method on it in your foreach loop in the first run after which it is not available anymore. You will either have to remove the oWord.Quit(); in BtnInserirImagem_Click and live with a constantly initialized word object or you could initialize it when needed and call quit on it afterwards.

    Document wordFile = new Document();

    //OTHER VARIABLES
    Object oClassType = "Word.Document.8";
    Object oTrue = true;
    Object oFalse = false;
    Object oMissing = System.Reflection.Missing.Value;

    private void BtnInserirImagem_Click(object sender, RoutedEventArgs e)
    {
        //Init Word App Object here
        Microsoft.Office.Interop.Word.Application oWord = new Microsoft.Office.Interop.Word.Application();

        foreach (MyDocsList row in dataGridList.Items)
        {
            wordFile = oWord.Documents.Open(row.filename);
            //pass the Word App instance
            addWatermark(wordFile, row.filename, oWord);
        }
        // Quitting oWord outside of the loop
        oWord.Quit(ref oMissing, ref oMissing, ref oMissing);
    }

    //added the Word App instance to the signature
    private void addWatermark(Document doc, object filename, Microsoft.Office.Interop.Word.Application oWord)
    {
        object refmissing = System.Reflection.Missing.Value;
        string watermarkPath = Directory.GetCurrentDirectory() + "\\fundo.jpg";

        if (File.Exists(watermarkPath))
        {

            object linkToFile = false;
            object saveWithDocument = true;

            WdHeaderFooterIndex hfIndex = WdHeaderFooterIndex.wdHeaderFooterPrimary;

            HeaderFooter headerFooter;

            for (int i = 1; i < doc.Sections.Count + 1; i++)
            {

                if (doc.Sections[i].Headers != null)
                {
                    headerFooter = doc.Sections[i].Headers[hfIndex];
                }
                else if (doc.Sections[i].Footers != null)
                {
                    headerFooter = doc.Sections[i].Footers[hfIndex];
                }
                else
                {
                    headerFooter = null;
                }

                if (headerFooter != null)
                {

                    try
                    {
                        Microsoft.Office.Interop.Word.Shape watermarkShape;
                        watermarkShape = headerFooter.Shapes.AddPicture(watermarkPath, ref linkToFile, ref saveWithDocument, ref refmissing,
                                                                        ref refmissing, ref refmissing, ref refmissing, ref refmissing);

                        watermarkShape.Left = Convert.ToSingle(WdShapePosition.wdShapeLeft);
                        watermarkShape.Top = Convert.ToSingle(WdShapePosition.wdShapeCenter);
                    }
                    catch (System.Runtime.InteropServices.COMException e)
                    {
                        MessageBoxResult result = MessageBox.Show(String.Format("{0} - Error Code = {1}", e.Message, e.ErrorCode));
                        throw e;
                    }
                }
            }

            oWord.ActiveWindow.View.SeekView = WdSeekView.wdSeekMainDocument;
            oWord.ActiveWindow.ActivePane.View.Type = Microsoft.Office.Interop.Word.WdViewType.wdPrintView;
        }
        else
        {
            MessageBoxResult result = MessageBox.Show("Could not find watermark image");
        }

        //THE LOCATION WHERE THE FILE NEEDS TO BE SAVED
        string outstringFile = "";
        string pathfile = System.IO.Path.GetDirectoryName(filename);
        string filenameFile = System.IO.Path.GetFileName(filename);
        outstringFile = pathfile + "\\OG" + filenameFile;

        Object oSaveAsFile = (Object)(outstringFile);

        wordFile.SaveAs(ref oSaveAsFile, 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);

        //CLOSING THE FILE
        wordFile.Close(ref oFalse, ref oMissing, ref oMissing);
    }

这篇关于在C#中添加水印图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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