using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Printing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace pdPrint
{
public partial class Form1 : Form
{
private int lineSize;
private List<string> textList;
private int lineHeight;
private int fontSize;
public Form1()
{
lineSize = 20;
lineHeight = 22;
fontSize = 12;
InitializeComponent();
}
private void btn_Print_Click(object sender, EventArgs e)
{
if (string.IsNullOrWhiteSpace(this.txt_PrintText.Text))
{
return;
}
var sourceTexts = this.txt_PrintText.Text.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
textList = new List<string>();
foreach (var item in sourceTexts)
{
if (!string.IsNullOrWhiteSpace(item))
{
if (item.Length > lineSize)
{
textList.AddRange(GetArr(lineSize, item));
}
else
{
textList.Add(item);
}
}
}
PrintDocument pd = new PrintDocument();
pd.PrintPage += new PrintPageEventHandler(Print_Content);
PaperSize pageSize = new PaperSize("自定义纸张", fontSize * lineSize, (textList.Count * lineHeight));
pd.DefaultPageSettings.PaperSize = pageSize;
try
{
pd.Print();
}
catch (Exception ex)
{
MessageBox.Show("打印失败." + ex.Message);
}
}
/// <summary>
/// 打印内容事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Print_Content(object sender, PrintPageEventArgs e)
{
var mark = 0;
foreach (var item in textList)
{
e.Graphics.DrawString(item, new Font(new FontFamily("宋体"), fontSize), System.Drawing.Brushes.Black, 0, mark * lineSize);
mark++;
}
}
/// <summary>
/// 根据内容进行分行
/// </summary>
/// <param name="linelen">每行字数</param>
/// <param name="text">原文字行(段落)文字</param>
/// <returns></returns>
private List<string> GetArr(int linelen, string text)
{
var list = new List<string>();
int listcount = text.Length % linelen == 0 ? text.Length / linelen : (text.Length / linelen) + 1;
for (int j = 0; j < listcount; j++)
{
try
{
list.Add(text.Substring(j * linelen, linelen));
}
catch (Exception)
{
list.Add(text.Substring(j * linelen));
}
}
return list;
}
}
}