Solved

C++ code to convert .gif to .doc

Posted on 2009-04-01
10
490 Views
Last Modified: 2013-11-20
C++ code to convert .gif to .doc
0
Comment
  • 4
  • 3
  • 2
  • +1
10 Comments
 
LVL 49

Expert Comment

by:DanRollins
Comment Utility
The only way I can think of to do this would be to create a Word document and embed the .gif image into it. That can be done programmatically, but it's kind of complicated in C++ (probably easier in, say, JavaScript or VBS).
Please provide some more details.
0
 
LVL 28

Expert Comment

by:pepr
Comment Utility
To add to DanRollins, you have to have MS Word installed on the computer where this is to be done (programmatically). There is no other reliable way to do it without having MS Word installed. The reason is that the program will use the Word components to do the action.
0
 
LVL 44

Expert Comment

by:AndyAinscow
Comment Utility
Any particular reason it must be a word doc file?  
There are a number of 'document' formats (eg. rtf, HTML) where your task would be a lot easier.
0
 
LVL 8

Author Comment

by:Subrat (C++ windows/Linux)
Comment Utility
If rtf/HTML it is ok
0
 
LVL 8

Author Comment

by:Subrat (C++ windows/Linux)
Comment Utility
Plz send me the code.

0
What Is Threat Intelligence?

Threat intelligence is often discussed, but rarely understood. Starting with a precise definition, along with clear business goals, is essential.

 
LVL 8

Author Comment

by:Subrat (C++ windows/Linux)
Comment Utility
Pepr,
I have already instlled WORD. Now proceed eith the code
0
 
LVL 44

Expert Comment

by:AndyAinscow
Comment Utility
Something like this should be OK for html


<html>
    <head>
    </head>
    <body>
        <IMG height="122" width="462" src="abc.gif">
    </body>
</html>


0
 
LVL 28

Expert Comment

by:pepr
Comment Utility
I can only show you fragments of code (not a fully working example) that uses Word97 (i.e. the interface version 8). The interface is also supported by the newer versions; however, the #import commands require the presence of the old dll's. You should be able to do the same with newer dll's but I have no experience with the newer interfaces. I also use WTL instead of MFC, but that should not make a big difference.




0
 
LVL 8

Author Comment

by:Subrat (C++ windows/Linux)
Comment Utility
Can u please show me a sample code!
0
 
LVL 28

Accepted Solution

by:
pepr earned 500 total points
Comment Utility
This is my really old code that was simplified (the image was originally generated) that was used for learning the export to Word. I did not compile it now. But you should get the idea. The

#include "mso97.tlh"
#include "vbeext1.tlh"
#include "msword8.tlh"

included header files (and the not-shown *.tli) are the result of #import of the related files.


#include <atlbase.h>
 

#include "mso97.tlh"

#include "vbeext1.tlh"

#include "msword8.tlh"
 

#include <cassert>

#include <iomanip>

#include <iostream>

#include <sstream>

#include <string>
 

using namespace std;
 

CComModule _Module;
 

float mm100ToPt(int mm)

{

    // Convert hundreds of mm (integer) to pt (float), because that 

    // unit and type is required for document properties.

    //

    return static_cast<float>(mm * 720.0 / 25400.0); 

}
 
 

/*! \brief Predicate of the file existence.

*/

bool isfile(const std::string & filename)

{

    WIN32_FIND_DATA FindFileData;

    HANDLE Handle;
 

    // Search for the file.

    //

    Handle = FindFirstFile(filename.c_str(), &FindFileData);
 

    // Not found => false.

    //

    if (Handle == INVALID_HANDLE_VALUE)

        return false;

    

    // Found => close the searching for the file...

    //

    FindClose(Handle);

    return true;

}
 
 

void WordExample()

{

    // Create the instance of the MS Word.

    //

    Word::_ApplicationPtr spWord;
 

    _variant_t vtTrue(true);

    _variant_t vtFalse(false);
 

    try

    {

        spWord.CreateInstance(OLESTR("Word.Application"));

    }

    

    // If the instance was not created, stop here.

    //

    catch (_com_error & e)

    {

        ostringstream ostr;

        ostr << "Failed to create the MS Word instance: " 

             << setbase(16) << e.Error() << " ("

             << setbase(10) << e.Error() << "):\n"

             << " meaning:    " << string(e.ErrorMessage()) << "\n"

             << " source:     " << string(e.Source()) << "\n"

             << " description:" << string(e.Description()) << "\n"

             << endl;

        exit(1);

    }
 

    // Pointers to Word document.

    //

    Word::_DocumentPtr spDocument;

    try

    {

        // Create new Word document based on Normal.dot template.

        //

        spDocument = spWord->Documents->Add();
 

        // Create and fill the demo chart instance 

        // with invisible window 15x10 cm.

        //

        HDC hDC = GetDC(NULL);

        assert(hDC != NULL);
 

        // removed from here for simplicity -- see the "some.gif" below.
 

        int LX = GetDeviceCaps(hDC, LOGPIXELSX);

        int LY = GetDeviceCaps(hDC, LOGPIXELSY);
 

        long x = MulDiv(1500, LX, 254);   // 15 cm to pixels LX PPI

        long y = MulDiv(1000, LY, 254);
 

        // Some constants used for working with the Word instance.

        //

        _variant_t LineBreak(static_cast<short>(Word::wdLineBreak));

        _variant_t PageBreak(static_cast<short>(Word::wdPageBreak));

        _variant_t CollapseEnd(Word::wdCollapseEnd);

        _variant_t StyleTypeParagraph(Word::wdStyleTypeParagraph);

        _variant_t AlignTabDecimal(Word::wdAlignTabDecimal);

        _variant_t AlignTabLeft(Word::wdAlignTabLeft);

        _variant_t AlignTabRight(Word::wdAlignTabRight);
 

        // Some experiment with margins.

        //

        spDocument->PageSetup->LeftMargin = 0;

        spDocument->PageSetup->TopMargin = mm100ToPt(2000); // 2 cm

        spDocument->PageSetup->RightMargin = 0;

        spDocument->PageSetup->BottomMargin = 0;
 

        // Get the pointer to collection for inserting pictures.

        //

        Word::InlineShapesPtr spInlineShapes(spDocument->InlineShapes);
 
 

        // Define the style for the report title.

        //

        Word::StylesPtr spStyles(spDocument->Styles);

        Word::StylePtr spReportTitleStyle(spStyles->Add("ReportTitle", 

                                                        &StyleTypeParagraph));

        

        spReportTitleStyle->ParagraphFormat->Alignment = Word::wdAlignParagraphCenter;

        

        spReportTitleStyle->Font->Bold = true;

        spReportTitleStyle->Font->Name = "Arial";

        spReportTitleStyle->Font->Size = 14;
 

        // Define the style for the report in-line image (centered).

        //

        Word::StylePtr spReportImgStyle(spStyles->Add("ReportImg", 

                                                      &StyleTypeParagraph));

        

        spReportImgStyle->ParagraphFormat->Alignment = Word::wdAlignParagraphCenter;
 

        // Style for the report table body.

        //

        Word::StylePtr spReportTableBodyStyle(spStyles->Add("ReportTableBody", 

                                                        &StyleTypeParagraph));

        

        Word::RangePtr spRange(spDocument->Range());

        ostringstream ostr;
 

        int reccount = 0;

        const int maxpageno = 5;  // demo -- 5 pages

        for (int pageno = 1;  pageno <= maxpageno; ++pageno)

        {

            // Get the name of the gif file (simplistic). Originally,

            // it was .wmf. I guess it should not make a difference.

            //

            string imgFileName("some.gif");
 

            // Write the report title.

            //

            ostr.str("");

            ostr << "Title of the page no. " << pageno << ".\n";

            spRange->PutText(ostr.str().c_str());

            spRange->PutStyle(&_variant_t("ReportTitle"));

            spRange->Collapse(&CollapseEnd);
 

            spRange->PutText("\n");

            spRange->PutStyle(&_variant_t("ReportImg"));
 

            _variant_t vtRange(static_cast<IUnknown*>(spRange));

            spInlineShapes->AddPicture(imgFileName.c_str(), &vtFalse, &vtTrue, 

                                       &vtRange);

            

            //Word::InlineShapePtr spShape = spShapes->AddOLEObject(&picture);
 

            // Insert the next paragraph with hard line breaks.

            //

            const int numlines = 40;

            for (int i = 1; i <= numlines; ++i)

            {

                // One line...

                //

                ostr.str("");

                ostr << "\t" << ++reccount 

                     << ".\tName\t100\t333.333\t222,22\tText text.";
 

                spRange->InsertAfter(ostr.str().c_str());
 

                // Next line or the last line of the paragraph.

                //

                if (i < numlines)

                {

                    spRange->Collapse(&CollapseEnd);

                    spRange->InsertBreak(&LineBreak);

                }

                else

                {

                    spRange->PutStyle(&_variant_t("ReportTableBody"));

                    spRange->Collapse(&CollapseEnd);

                }

            }
 

            // Page break if there will be another page.

            //

            if (pageno < maxpageno)

            {

                spRange->Collapse(&CollapseEnd);

                spRange->InsertBreak(&PageBreak);

            }

        }
 

        // Experiment: Tab positions of the table body style set

        // _after_ generating the content (related to the logic 

        // of the application).

        //

        Word::TabStopsPtr spTabStops(

            spReportTableBodyStyle->ParagraphFormat->GetTabStops());

        spTabStops->Add(mm100ToPt(2000), &AlignTabRight);     

        spTabStops->Add(mm100ToPt(2500), &AlignTabLeft);

        spTabStops->Add(mm100ToPt(5500), &AlignTabRight);

        spTabStops->Add(mm100ToPt(6500), &AlignTabDecimal);

        spTabStops->Add(mm100ToPt(10000), &AlignTabDecimal);

        spTabStops->Add(mm100ToPt(15000), &AlignTabLeft);
 

        spReportTableBodyStyle->Font->Bold = false;

        spReportTableBodyStyle->Font->Name = "Arial";

        spReportTableBodyStyle->Font->Size = 10;
 

        // Set name of the generated Word document. Erase the file

        // if it already exists.

        //

        string filename("c:/tmp/test.rtf");
 

        if (isfile(filename))

            unlink(filename.c_str());
 

        // Store the document.

        //

        _variant_t FileName(filename.c_str());

        _variant_t FormatRTF(static_cast<short>(Word::wdFormatRTF));
 

        spDocument->SaveAs(&FileName,             // Filename

                           &FormatRTF,            // or &vtMissing, ... FileFormat !!!

                           &vtMissing,            // LockComment

                           &vtMissing,            // Password

                           &vtMissing,            // AddToRecentFiles

                           &vtMissing,            // WritePassword

                           &vtMissing,            // ReadOnlyRecommended

                           &vtTrue,               // EmbedTrueTypeFonts

                           &vtMissing,            // SaveNativePictureFormat

                           &vtMissing,            // SaveFormsData

                           &vtMissing             // SaveAsAOCELetter

                      );
 

 

        // Close the document and the Word instance.

        //

        spDocument->Close();

        spWord->Quit();

        

        // Release the components.

        //

        spDocument = NULL;

        spWord = NULL;

    }

    

    catch (_com_error & e)

    {

        cerr << "COM error " 

             << setbase(16) << e.Error() << " ("

             << setbase(10) << e.Error() << "):\n"

             << " meaning:     " << string(e.ErrorMessage()) << "\n"

             << " source:      " << string(e.Source()) << "\n"

             << " description: " << string(e.Description()) << "\n"

             << endl;

        exit(1);

    }
 

    catch (...)

    {

        cerr << "Some non COM error!\a\n";

        exit(1);

    }

}
 

int WINAPI WinMain(HINSTANCE hInstance, 

                   HINSTANCE hPrevInstance, 

                   LPTSTR lpCmdLine, 

                   int nShowCmd)

{

    HRESULT hRes = CoInitialize(0);

    ATLASSERT(SUCCEEDED(hRes));

    

    _Module.Init(NULL, hInstance);
 

    WordExample();

    MessageBox(NULL, "End", "Export to Word", 

               MB_ICONINFORMATION | MB_TOPMOST | MB_OK);
 

    _Module.Term();

    CoUninitialize();
 

    return 0;

}

Open in new window

0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Introduction: Hints for the grid button.  Nested classes, templated collections.  Squash that darned bug! Continuing from the sixth article about sudoku.   Open the project in visual studio. First we will finish with the SUD_SETVALUE messa…
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
The goal of this video is to provide viewers with basic examples to understand opening and writing to files in the C programming language.
The goal of this video is to provide viewers with basic examples to understand and use conditional statements in the C programming language.

762 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now