views:

647

answers:

1

I'm trying to preview and print multiple page TIFF files from a C# 2005 Windows application. Printing works fine but when I send my PrintDocument to a PrintPreviewDialog I get two images of the first page rather than an ameage of the first and second page. I also have the same problem when I use PrintPreviewControl.

Below is code for a form with 2 buttons, a PrintDocument and a PrintPreviewDialog that demonstrates the problem.

public partial class Form1 : Form
{
    private Image m_Image;
    private Int32 m_CurrentPage;
    private Int32 m_PageCount;

    private void Form1_Load(object sender, EventArgs e)
    {
        m_Image = Image.FromFile(".\\Test-2-Page-Image.tif");
        m_PageCount = m_Image.GetFrameCount(FrameDimension.Page);
    }

    private void printDocument_BeginPrint(object sender, PrintEventArgs e)
    {
        m_CurrentPage = 0;
        m_PageCount = m_Image.GetFrameCount(FrameDimension.Page);
    }

    private void printDocument_PrintPage(object sender, PrintPageEventArgs e)
    {
        m_Image.SelectActiveFrame(FrameDimension.Page, m_CurrentPage);
        e.Graphics.DrawImage(m_Image, 0, 0);
        ++m_CurrentPage;
        e.HasMorePages = (m_CurrentPage < m_PageCount);
    }

    private void btnPreview_Click(object sender, EventArgs e)
    {
        printPreviewDialog.Document = printDocument;
        printPreviewDialog.ShowDialog();
    }

    private void btnPrint_Click(object sender, EventArgs e)
    {
        printDocument.Print();
    }
}

Does anyone know if there is there a problem with the PrintPreviewDialog in the .Net framework or am I doing something wrong.

+1  A: 

It's a bug with the Graphics.DrawImage() function.

The problem is documented here: Graphics.DrawImage Bug

The working code looks like this:

img.SelectActiveFrame(FrameDimension.Page, curPage);
using(MemoryStream stm = new MemoryStream())
{     
    img.Save(stm, imgCodecInfo, encParams); // save to memory stream
    Bitmap bmp = (Bitmap)Image.FromStream(stm);
    e.Graphics.DrawImage((Image)bmp,0,0);
    bmp.Dispose();
}
Steven Richards