How to print with custom paper size in winforms

前端 未结 2 755
陌清茗
陌清茗 2020-12-25 14:11

I\'m trying to print a document in my application. But on different printers i get different results. This is my code:

PaperSize paperSize = new PaperSize(\"         


        
2条回答
  •  [愿得一人]
    2020-12-25 15:13

    setting

    pd.DefaultPageSettings.PaperSize = paperSize;
    

    and

    pd.PrinterSettings.DefaultPageSettings.PaperSize = paperSize;
    

    might not work sometimes.

    The most appropriate thing is to select a custom papersize that is installed in the Printers driver or Computer then setting the properties of the following

    pd.DefaultPageSettings.PaperSize = ExistingPaperSize;
    pd.PrinterSettings.PaperSize = ExistingPaperSize;
    

    Like this code

        PrintDocument pd = new PrintDocument();
        pd.PrinterSettings = printdg.PrinterSettings;
        PaperSize RequiredPaperSize = CalculatePaperSize(WIDTH,HEIGHT);
        bool FoundMatchingPaperSize = false;
        for (int index = 0; index < pd.PrinterSettings.PaperSizes.Count; index++)
        {
             if (pd.PrinterSettings.PaperSizes[index].Height == RequiredPaperSize.Height && pd.PrinterSettings.PaperSizes[index].Width == RequiredPaperSize.Width)
              {
                  pd.PrinterSettings.DefaultPageSettings.PaperSize = pd.PrinterSettings.PaperSizes[index];
                  pd.DefaultPageSettings.PaperSize = pd.PrinterSettings.PaperSizes[index];
                  FoundMatchingPaperSize = true;
                  break;
               }
        }
    
    
        //Method to calculate PaperSize from Centimeter to 1/100 of an inch
     /// Caclulates the paper size
        /// 
        /// 
        /// 
        /// 
        public static System.Drawing.Printing.PaperSize CalculatePaperSize(double WidthInCentimeters, 
            double HeightInCentimetres)
        {
            int Width = int.Parse( ( Math.Round ((WidthInCentimeters*0.393701) * 100, 0, MidpointRounding.AwayFromZero) ).ToString() );
            int Height = int.Parse( ( Math.Round ((HeightInCentimetres*0.393701) * 100, 0, MidpointRounding.AwayFromZero) ).ToString() );
    
            PaperSize NewSize = new PaperSize();
            NewSize.RawKind = (int)PaperKind.Custom;
            NewSize.Width = Width;
            NewSize.Height = Height;
            NewSize.PaperName = "Letter";
    
            return NewSize;
    
        }
    

提交回复
热议问题