Solved

C++ code to convert .gif to .doc

Posted on 2009-04-01
10
500 Views
Last Modified: 2013-11-20
C++ code to convert .gif to .doc
0
Comment
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 3
  • 2
  • +1
10 Comments
 
LVL 49

Expert Comment

by:DanRollins
ID: 24046043
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 29

Expert Comment

by:pepr
ID: 24046740
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
ID: 24047973
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
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 9

Author Comment

by:Subrat (C++ windows/Linux)
ID: 24066329
If rtf/HTML it is ok
0
 
LVL 9

Author Comment

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

0
 
LVL 9

Author Comment

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

Expert Comment

by:AndyAinscow
ID: 24067044
Something like this should be OK for html


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


0
 
LVL 29

Expert Comment

by:pepr
ID: 24077326
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 9

Author Comment

by:Subrat (C++ windows/Linux)
ID: 24077353
Can u please show me a sample code!
0
 
LVL 29

Accepted Solution

by:
pepr earned 500 total points
ID: 24085644
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

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Windows programmers of the C/C++ variety, how many of you realise that since Window 9x Microsoft has been lying to you about what constitutes Unicode (http://en.wikipedia.org/wiki/Unicode)? They will have you believe that Unicode requires you to useā€¦
Exception Handling is in the core of any application that is able to dignify its name. In this article, I'll guide you through the process of writing a DRY (Don't Repeat Yourself) Exception Handling mechanism, using Aspect Oriented Programming.
The goal of this video is to provide viewers with basic examples to understand how to use strings and some functions related to them in the C programming language.
The viewer will learn how to pass data into a function in C++. This is one step further in using functions. Instead of only printing text onto the console, the function will be able to perform calculations with argumentents given by the user.

728 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