• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 514
  • Last Modified:

C++ code to convert .gif to .doc

C++ code to convert .gif to .doc
0
Subrat (C++ windows/Linux)
Asked:
Subrat (C++ windows/Linux)
  • 4
  • 3
  • 2
  • +1
1 Solution
 
DanRollinsCommented:
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
 
peprCommented:
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
 
AndyAinscowCommented:
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!

 
Subrat (C++ windows/Linux)Software EngineerAuthor Commented:
If rtf/HTML it is ok
0
 
Subrat (C++ windows/Linux)Software EngineerAuthor Commented:
Plz send me the code.

0
 
Subrat (C++ windows/Linux)Software EngineerAuthor Commented:
Pepr,
I have already instlled WORD. Now proceed eith the code
0
 
AndyAinscowCommented:
Something like this should be OK for html


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


0
 
peprCommented:
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
 
Subrat (C++ windows/Linux)Software EngineerAuthor Commented:
Can u please show me a sample code!
0
 
peprCommented:
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

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 4
  • 3
  • 2
  • +1
Tackle projects and never again get stuck behind a technical roadblock.
Join Now