Question

I am trying to produce a document in C# mainly to print. Basically it is a form, where I will fill in the values from objects from a database.

The code I been using in the past is ugly, long, a pain to write and worse to maintain.

public class MyDoc : PrintDocument
{
    private MyContainer _myObject; //Inherits from list.

    private int PageCount()
    {
        return (int)Math.Ceiling(_myObject.Count / 5f);
    }

    protected override void OnPrintPage(PrintPageEventArgs e)
    {
        Graphics g = e.Graphics;
        g.PageUnit = GraphicsUnit.Millimeter;

        Font bigFont = new Font("Arial", 16, FontStyle.Regular, GraphicsUnit.Point);
        Font mediumFont = new Font("Arial", 10, FontStyle.Regular, GraphicsUnit.Point);
        Font smallFont = new Font("Arial", 10, FontStyle.Regular, GraphicsUnit.Point);
        Font smallNumberFont = new Font("Courier New", 7, FontStyle.Regular, GraphicsUnit.Point);
        Pen linePen = new Pen(Brushes.Black, 0.2F);

        int rowPosition = 5;
        int rowIncrement = 9;

        g.DrawString(string.Format("Page {0} of {1}", _pageNumber, PageCount()), smallFont, Brushes.Black, 175, rowPosition);
        rowPosition = 15;

        g.DrawImage(Image.FromFile("myfile.jpg"), 127, rowPosition);

        g.DrawString("Name:", smallFont, Brushes.Black, 3, rowPosition);
        g.DrawString(_myObject.Name, smallBoldFont, Brushes.Black, 50, rowPosition);
        rowPosition += rowIncrement;

        //Sub-Items Table Header
        g.DrawRectangle(linePen, 3, rowPosition, 35, 10);
        g.DrawRectangle(linePen, 38, rowPosition, 85, 10);
        g.DrawRectangle(linePen, 123, rowPosition, 25, 10);
        g.DrawRectangle(linePen, 148, rowPosition, 20, 10);
        g.DrawRectangle(linePen, 168, rowPosition, 25, 10);

        foreach (var i in _myObject)
        {
            //Draw a grid and write out all details of everything in the collection.
            //If there are 2 many, stop and we will create a page 2.
        }

        //Write Standard page footer
        //etc etc.
    }
}

Also a new requirement, I need to Save this to either a pdf or an image.

Basically I've got 300-500 lines of code to write a document which looks somewhat decent.

I've got some more to do which will be very similar and I need a better way!


I've thought of:

XAML - then databind the properties I need to fill in. Not sure how to handle it spreading onto 2 or more pages though.

Word Interop - I don't know if I can. It runs on a webserver where office is NOT installed. (I can package a few dll's up if thats all I need, but I'm not sure.)

So I'm looking for ideas from all you good folks.

I'd prefer not to use external libraries, but if thats the best way, it needs to be free and have good licensing :)

Was it helpful?

Solution

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top