Search code examples
c#printingsizereadonlypage-size

Setting a Paper Size into C# print


I have a project which requires me to print big data on paper , width f the paper in 3.3inch but the height can be as small aS 0.8 inch up to 100 inches base on the data(label printer)

I have been told that printDialog must NOT be accessible to the user so I decided to set the setting by hardcoding it and calculating the height of the paper by the app .

after putting PrintDocument into watch I have found that page size can be set by these options(probably if I am not wrong)

        doc.DefaultPageSettings.PaperSize.kind = System.Drawing.Printing.PaperKind.Custom;
        doc.DefaultPageSettings.PaperSize.Height = 500;

now the problem is if the paper kind is not custom I will get an exception which I need to change doc.DefaultPageSettings.PaperSize.kind to custom , however, I get that paper kind is read-only

how can I change the paper type to custom in PrintDoc?


Solution

  • So I have come across a post and with some modification, I got the below code which works perfectly for my purpose

    PrintDocument doc = new PrintDocument();
    PrintDialog print = new PrintDialog();
    if (print.ShowDialog(this) == DialogResult.OK)
    {
       print.Document = doc;
    }
    float height = (((float)0.763 * printNumbers) + ((float)0.098 * (printNumbers - (float)1))) * 100;
    PaperSize paperSize = new PaperSize("MY_PAGE_SIZE_NME", 333, (int)height);
    paperSize.RawKind = 256;
    doc.DefaultPageSettings.PaperSize = paperSize;
    doc.Print();
    

    the numbers in Height are customized to my own need, you may wanna change and calculate your if needed