Make a Word document with one picture on each page in C#


[Word document]

This example shows how you can make a program create a Word document that contains a picture on each page.

Before you start writing code, open the Add References dialog, click on the COM tab, and add a reference to “Microsoft Word 12.0 Object Library” (or whatever version you have installed on your system).

When you click the Select Pictures button, the program executes the following code.

// Let the user select the pictures.
private void btnSelectPictures_Click(object sender, EventArgs e)
{
    if (ofdPictures.ShowDialog() == DialogResult.OK)
        lstFiles.DataSource = ofdPictures.FileNames;
}

This code displays the OpenFileDialog named ofdPictures. If you select one or more files and click Open, the program sets the DataSource property for the lstFiles ListBox equal to the dialog’s FileNames array. That makes the ListBox display the names of the selected files.

You can then review the list of files and click the Create Document button to execute the following code.

// Create the Word document.
private void btnCreateDocument_Click(object sender, EventArgs e)
{
    // Get the Word application object.
    Word._Application word_app = new Word.ApplicationClass();

    // Make Word visible (optional).
    word_app.Visible = true;

    // Create the Word document.
    object missing = Type.Missing;
    Word._Document word_doc = word_app.Documents.Add(
        ref missing, ref missing,
        ref missing, ref missing);

    // Make one page per picture.
    object collapse_end = Word.WdCollapseDirection.wdCollapseEnd;
    object page_break = Word.WdBreakType.wdPageBreak;
    for (int i = 0; i < lstFiles.Items.Count; i++)
    {
        // Get the file's name.
        string filename = (string)lstFiles.Items[i];

        // Go to the end of the document.
        range = word_doc.Paragraphs.Last.Range;

        // Add the picture to the range.
        Word.InlineShape inline_shape =
            range.InlineShapes.AddPicture(
                filename, ref missing, ref missing,
                ref missing);

        // Add a paragraph.
        Word.Range range.InsertParagraphAfter();

        // Add a caption.
        FileInfo file_info = new FileInfo(filename);
        range.InsertAfter("Picture " +
            i.ToString() + ": " + file_info.Name);

        // If this isn't the last page, insert a page break.
        if (i < lstFiles.Items.Count - 1)
        {
            range.Collapse(ref collapse_end);
            range.InsertBreak(ref page_break);
        }
    }

    // Save the document.
    object doc_filename = Path.GetFullPath(
        Path.Combine(Application.StartupPath, "..\\..")) +
        "\\pictures.docx";
    word_doc.SaveAs(ref doc_filename, ref missing, ref missing,
        ref missing, ref missing, ref missing, ref missing,
        ref missing, ref missing, ref missing, ref missing,
        ref missing, ref missing, ref missing, ref missing,
        ref missing);

    // Close.
    object save_changes = false;
    word_doc.Close(ref save_changes, ref missing, ref missing);
    word_app.Quit(ref save_changes, ref missing, ref missing);

    MessageBox.Show("Done");
}

This code creates a Word application object (the Word server) and makes it visible. It then uses the server to create a new Word document.

Next the program loops through the file names in the program’s ListBox. Inside the loop, the program uses the document’s Paragraphs.Last.Range value to get a Range object that represents the end of the document.

The code then creates a new InlineShapes object holding the picture in the range. It adds a paragraph after the picture and then adds a text caption after that.

Next, if this is not the last picture, the program collapses the range so it represents the spot after the range and adds a page break.

After it has finished creating all of the pages, the program saves the Word document.

As is usually the case with Word automation, the hardest part is figuring out what Word objects and methods to use. Download the example to experiment with the program and to see additional details.


Download Example   Follow me on Twitter   RSS feed   Donate




About RodStephens

Rod Stephens is a software consultant and author who has written more than 30 books and 250 magazine articles covering C#, Visual Basic, Visual Basic for Applications, Delphi, and Java.
This entry was posted in Office, Word and tagged , , , , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.