如何设置打印纸张尺寸?自定义尺寸打印仍用默认尺寸问题求助
自定义纸张尺寸打印不生效的解决方案
我来帮你排查这个问题!你的代码里有几个关键细节没处理好,导致自定义纸张尺寸没生效,下面一步步说清楚:
问题根源
- 你设置的自定义尺寸
10×10单位是百分之一英寸,也就是实际只有0.1英寸×0.1英寸,绝大多数打印机不会识别这么极端的小尺寸,直接 fallback 到默认尺寸了。 - 部分打印机需要明确指定
PaperKind.Custom,否则不会承认自定义尺寸。 - 没有同步更新
PrinterSettings里的纸张配置,可能导致打印时用默认设置覆盖你的自定义值。
修改后的完整代码
我标注了关键改动点,同时优化了输入合法性检查:
namespace WC_manager { public partial class tagprint : Form { Zen.Barcode.Code39BarcodeDraw objCode = Zen.Barcode.BarcodeDrawFactory.Code39WithChecksum; int tagNo = 0; PrinterSettings ps = new PrinterSettings(); public tagprint() { InitializeComponent(); } private void label1_Click(object sender, EventArgs e) { } private void printBtn_Click(object sender, EventArgs e) { if(tagNo != 0) { pictureBox1.Image = objCode.Draw(Convert.ToString(tagNo), 100); var doc = new PrintDocument(); doc.PrintPage += new PrintPageEventHandler(ProvideContent); doc.PrinterSettings.PrinterName = "Adobe PDF"; // --- 核心改动开始 --- // 1. 设置合理的自定义尺寸,单位是百分之一英寸(例:2英寸×3英寸 = 200×300) var customPaper = new PaperSize("CustomTag", 200, 300); // 明确标记为自定义纸张类型 customPaper.PaperKind = PaperKind.Custom; // 2. 先检查打印机是否支持自定义尺寸 if (doc.PrinterSettings.IsValid && doc.PrinterSettings.SupportsCustomPaperSize) { // 同步更新DefaultPageSettings和PrinterSettings的纸张配置 doc.DefaultPageSettings.PaperSize = customPaper; doc.PrinterSettings.DefaultPageSettings.PaperSize = customPaper; } else { MessageBox.Show("当前打印机不支持自定义纸张尺寸,请检查打印机设置"); return; } // --- 核心改动结束 --- doc.Print(); } else { MessageBox.Show("Enter Valid Tag no"); } } private void tagTxtFld_TextChanged(object sender, EventArgs e) { // 替换Convert.ToInt32,避免输入非数字时崩溃 if(int.TryParse(tagTxtFld.Text, out int validNumber)) { tagNo = validNumber; } else { tagNo = 0; } } public void ProvideContent(object sender, PrintPageEventArgs e) { Graphics graphics = e.Graphics; Font font = new Font("Courier New", 10); float fontHeight = font.GetHeight(); // 调整绘制位置,避免超出自定义纸张边界 graphics.DrawImage(objCode.Draw(Convert.ToString(tagNo), 20), 10, 10, 50, 50); // 新增测试文本,方便验证纸张尺寸是否生效 graphics.DrawString($"Tag: {tagNo}", font, Brushes.Black, 10, 70); } } }
额外注意事项
- 自定义尺寸要符合打印机物理支持范围:先在打印机控制面板里确认允许的最小/最大自定义尺寸,再转换为百分之一英寸(比如3英寸=300,5英寸=500)。
- 绘制内容时要控制在纸张边界内,否则会被打印机裁剪。
内容的提问来源于stack exchange,提问作者M. Mubeen Asif
相关产品推荐
相关产品推荐

