locked
Dynamic paper height with .NET PrintDocument RRS feed

  • Question

  • Hello,

    I ran into a problem with sizing pages on a thermal printer. I have started from this answer: http://stackoverflow.com/a/27165167/1030464 and now I have the code I pasted below.

    This works nicely, however altough I calculate and set the size of the page, it seems to print a full A4 sized page each time. (I am testing on a Sam4s Ellix II and Microsoft PDF Printer) - It is a big problem, as it's needed to often print 5-6 line long text snippets.

    I need to support multiple thermal printers and I only need the basic functions (so no need to receive signals such as paper jam, etc.) so I decided to go with the Windows printer driver, instead of the POS for .NET one.

    I calculate the height of the text and size the paper accordingly, however it has no effect on the output paper size. Does anyone have a solution for this issue?

    Thank you very much

    public int Print(DatabaseConnector dc)
    {
        try {
    
            // Set up PrintDocument
            PrintDocument recordDoc = new PrintDocument();
            recordDoc.DocumentName = "PrintTask ID "+id.ToString();
            recordDoc.PrintPage += new PrintPageEventHandler(PrintTask.PrintReceiptPage); // Filling in the stuff
    
            // Print Controller
            StandardPrintController spc = new StandardPrintController();
            recordDoc.PrintController = spc; // This hides popup
    
            // Printer Settings
            PrinterSettings ps = new PrinterSettings();
            ps.PrinterName = dc.ReadSetting("PrinterName"); 
            recordDoc.PrinterSettings = ps;
            recordDoc.Print();
    
            // Clean up
            recordDoc.Dispose();
        }
        catch (Exception exc)
        {
            ((MainForm)Application.OpenForms[0]).msg(exc.Message);
        }
        return 1; // ignore this 
    }
    
    private static void PrintReceiptPage(object sender, PrintPageEventArgs e)
    {
        try {
            // Read settings
            DatabaseConnector db = new DatabaseConnector();
            PrintTask pt = db.ReadTask();
            float x = float.Parse(db.ReadSetting("PaperMarginFromLeft"));
            float y = float.Parse(db.ReadSetting("PaperMarginFromTop"));
            float width = float.Parse(db.ReadSetting("PaperWidth"));
            float height = 0F;
            string text;
    
            // Set up font
            Font drawFont1 = new Font(db.ReadSetting("PrintFont"), Int32.Parse(db.ReadSetting("PrintFontSize")), FontStyle.Regular);
            SolidBrush drawBrush = new SolidBrush(Color.Black);
    
            // Set format of string.
            StringFormat drawFormatLeft = new StringFormat();
            drawFormatLeft.Alignment = StringAlignment.Near;
    
            // Draw string to screen.
            text = pt.getData();
            e.Graphics.DrawString(text, drawFont1, drawBrush, new RectangleF(x, y, width, height), drawFormatLeft);
    
            // calculate text size
            SizeF textSize = e.Graphics.MeasureString(text, drawFont1);
            y += textSize.Height;
    
            // Set page size - has no effect
            e.HasMorePages = false;
            float inchHeight = PrintTask.PixelsToInchY(y, e.Graphics);
            PaperSize originalPaperSize  = e.PageSettings.PaperSize;
            PaperSize scaledSize = new PaperSize("Custom", originalPaperSize.Width, (int)Math.Ceiling(inchHeight * 100));
            e.PageSettings.PaperSize = scaledSize;
            e.PageSettings.PrinterSettings.DefaultPageSettings.PaperSize = scaledSize;
    
        }
        catch (Exception exc)
        {
            ((MainForm)Application.OpenForms[0]).msg(exc.Message);
        }
    }
    
    public static float PixelsToInchX(float n, Graphics graphics)
    {
        return n * graphics.DpiX / 300;
    }
    public static float PixelsToInchY(float n, Graphics graphics)
    {
        return n * graphics.DpiY / 300;
    }


    Monday, February 15, 2016 10:10 AM

Answers

  • Hi molbal,

    Welcome to MSDN forum.

    After the PrintDialog closes, based on Linki's code, not only use the following code

    pd.DefaultPageSettings.PaperSize = paperSize;

    Try also setting

    pd.PrinterSettings.DefaultPageSettings.PaperSize = paperSize;

    You also can try

    public void SetPaperSize(string paperSizeName)
    {
     paperSize = doc.PrinterSettings.PaperSizes.Cast<PaperSize>().FirstOrDefault
              (a => a.PaperName.Equals(paperSizeName, 
      StringComparison.InvariantCultureIgnoreCase));
     if(paperSize==null)
     throw new ArgumentException(string.Format
      ("Papersize {0} not found.",paperSizeName));
     doc.DefaultPageSettings.PaperSize = paperSize;
     doc.PrinterSettings.DefaultPageSettings.PaperSize = paperSize;
    }

    Best regards,

    Kristin


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.

    Friday, February 19, 2016 9:49 AM

All replies

  • Hi molbal,

    >>This works nicely, however altough I calculate and set the size of the page, it seems to print a full A4 sized page each time. (I am testing on a Sam4s Ellix II and Microsoft PDF Printer)

    Could you please try the following code ?

                     if (myPrinDialog.ShowDialog() == DialogResult.OK)
                     {
                         prntdoc.DefaultPageSettings.PaperSize = new PaperSize("A4", 827, 1169);
                         prntdoc.DefaultPageSettings.Margins = new Margins(0, 0, 0, 0);
                         prntdoc.Print();
                     }

    By the way, it could be better to show a screen capture of your print page here. thanks.

    Tuesday, February 16, 2016 8:08 AM
  • Hi Linki,

    Thank you very much for answering.

    I am showing a dialog now, but it does not affect the output document.

    Original

    With dialog

    The code looks like this now:

                    // Print Controller
                    // StandardPrintController spc = new StandardPrintController();
                    // recordDoc.PrintController = spc; // This hides popup
    
                    // Printer Settings
                    PrinterSettings ps = new PrinterSettings();
                    ps.PrinterName = dc.ReadSetting("PrinterName"); 
                    recordDoc.PrinterSettings = ps;
                    recordDoc.Print();
    
                    // Create the print dialog object and set options
                    PrintDialog pDialog = new PrintDialog();
                    pDialog.UseEXDialog = true;
    
                    // Display the dialog. This returns true if the user presses the Print button.
                    DialogResult print = pDialog.ShowDialog();
                    if (print == DialogResult.OK)
                    {
                        
                        recordDoc.DefaultPageSettings.PaperSize = new PaperSize("A4", 827, 1169);
                        recordDoc.DefaultPageSettings.Margins = new Margins(0, 0, 0, 0);
                        recordDoc.Print();
                    }

    Do you have another idea? I will check this on the thermal printer as well and post the results (I have to wait until the café closes so I have proper access to the equipment there)

    If not, I will have to fall back to OPOS.

    Thank you again

    Tuesday, February 16, 2016 3:34 PM
  • Hi molbal,

    Welcome to MSDN forum.

    After the PrintDialog closes, based on Linki's code, not only use the following code

    pd.DefaultPageSettings.PaperSize = paperSize;

    Try also setting

    pd.PrinterSettings.DefaultPageSettings.PaperSize = paperSize;

    You also can try

    public void SetPaperSize(string paperSizeName)
    {
     paperSize = doc.PrinterSettings.PaperSizes.Cast<PaperSize>().FirstOrDefault
              (a => a.PaperName.Equals(paperSizeName, 
      StringComparison.InvariantCultureIgnoreCase));
     if(paperSize==null)
     throw new ArgumentException(string.Format
      ("Papersize {0} not found.",paperSizeName));
     doc.DefaultPageSettings.PaperSize = paperSize;
     doc.PrinterSettings.DefaultPageSettings.PaperSize = paperSize;
    }

    Best regards,

    Kristin


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.

    Friday, February 19, 2016 9:49 AM
  • Hi,

    Thanks for your answer I am going to try out this, too. (Apologies for the late answer, I've been on holiday)

    Tuesday, February 23, 2016 9:02 AM
  • your solution was perfect it was worked for me as i used it for controlling the print document size .

    Note : I have very less items to be printed in a invoice .

    // code for the print document length and width control as they are directly coming form the data grid view .

    if (dgv3.Rows.Count <=2)
                    {
                        DVPrintDocument.DefaultPageSettings.PaperSize = new PaperSize("", 400, 500);
                        DVPrintDocument.DefaultPageSettings.Margins = new Margins(0, 0, 0, 0);
                    }
                    else if (dgv3.Rows.Count <= 4)
                    {
                        DVPrintDocument.DefaultPageSettings.PaperSize = new PaperSize("", 400, 550);
                        DVPrintDocument.DefaultPageSettings.Margins = new Margins(0, 0, 0, 0);
                    }
                    else if (dgv3.Rows.Count <= 6)
                    {
                        DVPrintDocument.DefaultPageSettings.PaperSize = new PaperSize("", 400, 600);
                        DVPrintDocument.DefaultPageSettings.Margins = new Margins(0, 0, 0, 0);
                    }
                    else if (dgv3.Rows.Count <= 8)
                    {
                        DVPrintDocument.DefaultPageSettings.PaperSize = new PaperSize("", 400, 650);
                        DVPrintDocument.DefaultPageSettings.Margins = new Margins(0, 0, 0, 0);
                    }
                    else if (dgv3.Rows.Count <= 10)
                    {
                        DVPrintDocument.DefaultPageSettings.PaperSize = new PaperSize("", 400, 700);
                        DVPrintDocument.DefaultPageSettings.Margins = new Margins(0, 0, 0, 0);
                    }
                    else if (dgv3.Rows.Count <= 12)
                    {
                        DVPrintDocument.DefaultPageSettings.PaperSize = new PaperSize("", 400, 750);
                        DVPrintDocument.DefaultPageSettings.Margins = new Margins(0, 0, 0, 0);
                    }
                    else if (dgv3.Rows.Count <= 14)
                    {
                        DVPrintDocument.DefaultPageSettings.PaperSize = new PaperSize("", 400, 800);
                        DVPrintDocument.DefaultPageSettings.Margins = new Margins(0, 0, 0, 0);
                    }
                    else if (dgv3.Rows.Count <= 16)
                    {
                        DVPrintDocument.DefaultPageSettings.PaperSize = new PaperSize("", 400, 850);
                        DVPrintDocument.DefaultPageSettings.Margins = new Margins(0, 0, 0, 0);
                    }
                    else if (dgv3.Rows.Count <= 18)
                    {
                        DVPrintDocument.DefaultPageSettings.PaperSize = new PaperSize("", 400, 900);
                        DVPrintDocument.DefaultPageSettings.Margins = new Margins(0, 0, 0, 0);
                    }
                    else if (dgv3.Rows.Count <= 20)
                    {
                        DVPrintDocument.DefaultPageSettings.PaperSize = new PaperSize("", 400, 950);
                        DVPrintDocument.DefaultPageSettings.Margins = new Margins(0, 0, 0, 0);
                    }

    // Code for the invoice .

    private void DVPrintDocument_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
            {
                SqlConnection con = new SqlConnection(@"ConnectionString");
                con.Open();
                SqlTransaction tran = con.BeginTransaction();

                SqlCommand cmd10 = new SqlCommand("select top 1 InvioceID,Totalqty," +
                    "TotalAmount,TotalAmountWithGST,ActualAmount," +
                    "DiscountInPercent from Bill order by InvioceID DESC", con, tran);
                cmd10.ExecuteNonQuery();

                using (SqlDataReader dr = cmd10.ExecuteReader())
                {
                    while (dr.Read())
                    {
                        INVOICEID = Convert.ToInt32(dr["InvioceID"]);
                        Total_Qty = Convert.ToString(dr["Totalqty"]);
                        Total_Amount = Convert.ToString(dr["TotalAmount"]);
                        _TotalWithGST = Convert.ToString(dr["TotalAmountWithGST"]);
                        Actual_Amount = Convert.ToString(dr["ActualAmount"]);
                        _Discount = Convert.ToString(dr["DiscountInPercent"]);
                    }
                }

                tran.Commit();
                con.Close();

                e.Graphics.DrawString("FOODIES FASTFOOD", new Font("Arial",15,FontStyle.Bold), Brushes.Blue, new Point(100,30));
                e.Graphics.DrawString("GST# 222-333-123456", new Font("Arial", 10, FontStyle.Regular), Brushes.Blue, new Point(130, 70));
                e.Graphics.DrawString("Invoice ID :", new Font("Arial", 10, FontStyle.Regular), Brushes.Blue, new Point(10, 100));
                e.Graphics.DrawString(INVOICEID.ToString(), new Font("Arial", 10, FontStyle.Regular), Brushes.Blue, new Point(90, 100));
                e.Graphics.DrawString("Transaction Date :", new Font("Arial", 10, FontStyle.Regular), Brushes.Blue, new Point(10, 120));
                e.Graphics.DrawString(DateTime.Now.Date.ToShortDateString(), new Font("Arial", 10, FontStyle.Regular), Brushes.Blue, new Point(130, 120));
                e.Graphics.DrawString("Transaction Time :", new Font("Arial", 10, FontStyle.Regular), Brushes.Blue, new Point(10, 140));
                e.Graphics.DrawString(DateTime.Now.ToShortTimeString(), new Font("Arial", 10, FontStyle.Regular), Brushes.Blue, new Point(130, 140));
                //
                e.Graphics.DrawString("------------------------------------------------------------------------------",
                   new Font("Arial", 10, FontStyle.Regular), Brushes.Blue, new Point(10, 160));
                e.Graphics.DrawString("SALES ITEMS", new Font("Arial", 10, FontStyle.Regular), Brushes.Blue, new Point(150, 180));
                e.Graphics.DrawString("------------------------------------------------------------------------------",
                new Font("Arial", 10, FontStyle.Regular), Brushes.Blue, new Point(10, 200));
                //
                e.Graphics.DrawString("PRODUCT NAME", new Font("Arial", 9, FontStyle.Regular), Brushes.Blue, new Point(10, 240));
                e.Graphics.DrawString("QUANTITY", new Font("Arial", 9, FontStyle.Regular), Brushes.Blue, new Point(160, 240));
                e.Graphics.DrawString("RATE", new Font("Arial", 9, FontStyle.Regular), Brushes.Blue, new Point(240, 240));
                e.Graphics.DrawString("AMOUNT", new Font("Arial", 9, FontStyle.Regular), Brushes.Blue, new Point(310, 240));

                int position = 260;

                for (int i = 0;i < dgv3.Rows.Count; i ++)
                {
                    position = position + 20;
                    e.Graphics.DrawString(Convert.ToString(dgv3.Rows[i].Cells[0].Value), new Font("Arial", 10, FontStyle.Regular), Brushes.Blue, new Point(10,position));
                    e.Graphics.DrawString(Convert.ToString(dgv3.Rows[i].Cells[1].Value)+".00", new Font("Arial", 10, FontStyle.Regular), Brushes.Blue, new Point(170, position));
                    e.Graphics.DrawString(Convert.ToString(dgv3.Rows[i].Cells[2].Value)+".00", new Font("Arial", 10, FontStyle.Regular), Brushes.Blue, new Point(240, position));
                    e.Graphics.DrawString(Convert.ToString(dgv3.Rows[i].Cells[3].Value)+".00", new Font("Arial", 10, FontStyle.Regular), Brushes.Blue, new Point(310, position));
                }
                //
                e.Graphics.DrawString("------------------------------------------------------------------------------",
               new Font("Arial", 10, FontStyle.Regular), Brushes.Blue, new Point(10, position + 20));
                //
                e.Graphics.DrawString("Actual Amount", new Font("Arial", 10, FontStyle.Regular), Brushes.Blue, new Point(10, position + 40));
                e.Graphics.DrawString(Actual_Amount.ToString() + ".00", new Font("Arial", 10, FontStyle.Regular), Brushes.Blue, new Point(310, position + 40));
                e.Graphics.DrawString("Total Quantity", new Font("Arial", 10, FontStyle.Regular), Brushes.Blue, new Point(10, position + 60));
                e.Graphics.DrawString(Total_Qty.ToString() + ".00", new Font("Arial", 10, FontStyle.Regular), Brushes.Blue, new Point(310, position + 60));
                e.Graphics.DrawString("Total Amount", new Font("Arial", 10, FontStyle.Regular), Brushes.Blue, new Point(10, position + 80));
                e.Graphics.DrawString(Total_Amount.ToString() + ".00", new Font("Arial", 10, FontStyle.Regular), Brushes.Blue, new Point(310, position + 80));
                e.Graphics.DrawString("Total Amount(GST Included)", new Font("Arial", 10, FontStyle.Regular), Brushes.Blue, new Point(10, position + 100));
                e.Graphics.DrawString(_TotalWithGST.ToString(), new Font("Arial", 10, FontStyle.Regular), Brushes.Blue, new Point(310, position + 100));
                e.Graphics.DrawString("Discount", new Font("Arial", 10, FontStyle.Regular), Brushes.Blue, new Point(10, position + 120));
                e.Graphics.DrawString(_Discount.ToString(), new Font("Arial", 10, FontStyle.Regular), Brushes.Blue, new Point(310, position + 120));
                //
                e.Graphics.DrawString("------------------------------------------------------------------------------",
               new Font("Arial", 10, FontStyle.Regular), Brushes.Blue, new Point(10, position + 140));
                //
                e.Graphics.DrawString("FOR ANY QUERIES AND COMPLAINS", new Font("Arial", 10, FontStyle.Regular), Brushes.Blue, new Point(80, position + 160));
                e.Graphics.DrawString(" SMS / WHATSAPP : 03423351437", new Font("Arial", 10, FontStyle.Regular), Brushes.Blue, new Point(90, position + 180));

            }


    Tuesday, September 10, 2019 10:36 PM
  • I'm glad it worked for you.

    The final solution for me was to set the printer driver to dynamic height.

    Thursday, September 12, 2019 8:55 AM