C#教程之打印和打印预览
最近研究一了一下關(guān)于PDF打印和打印預(yù)覽的功能,在此小小的總結(jié)記錄一下學(xué)習(xí)過程。
實現(xiàn)打印和打印預(yù)覽的方法,一般要實現(xiàn)如下的菜單項:打印、打印預(yù)覽、頁面設(shè)置、
PrintDocument類
PrintDocument組件是用于完成打印的類,其常用的屬性、方法事件如下:
屬性DocumentName:字符串類型,記錄打印文檔時顯示的文檔名(例如,在打印狀態(tài)對話框或打印機隊列中顯示),即用戶填寫生成pdf文件名時的默認值為DocumentName 方法Print:開始文檔的打印。 事件BeginPrint:在調(diào)用Print方法后,在打印文檔的第一頁之前發(fā)生。 事件PrintPage:需要打印新的一頁時發(fā)生。 事件EndPrint:在文檔的最后一頁打印后發(fā)生。
若要打印,首先創(chuàng)建PrintDocument組建的對象,然后使用頁面上設(shè)置對話框PageSetupDialog設(shè)置頁面打印方式,這些設(shè)置作為打印頁的默認設(shè)置、使用打印對話框PrintDialog設(shè)置對文檔進行打印的打印機的參數(shù)。在打開兩個對話框前,首先設(shè)置對話框的屬性Document為指定的PrintDocument類對象,修改的設(shè)置將保存到PrintDocument組件對象中。
第三步是調(diào)用PrintDocument.Print方法來實際打印文檔,調(diào)用該方法后,引發(fā)下列事件:BeginPrint、PrintPage、EndPrint。其中每打印一頁都引發(fā)PrintPage事件,打印多頁,要多次引發(fā)PrintPage事件。完成一次打印,可以引發(fā)一個或多個PrintPage事件。
/// <summary>
/// 打印紙設(shè)置
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void FileMenuItem_PageSet_Click(object sender, EventArgs e)
{
PageSetupDialog pageSetupDialog = new PageSetupDialog();
pageSetupDialog.Document = printDocument;
pageSetupDialog.ShowDialog();
}
/// <summary>
/// 打印機設(shè)置
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void FileMenuItem_PrintSet_Click(object sender, EventArgs e)
{
PrintDialog printDialog = new PrintDialog();
printDialog.Document = printDocument;
printDialog.ShowDialog();
}
/// <summary>
/// 預(yù)覽功能
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void FileMenuItem_PrintView_Click(object sender, EventArgs e)
{
PrintPreviewDialog printPreviewDialog = new PrintPreviewDialog {Document = printDocument};
lineReader = new StreamReader(@"f:新建文本文檔.txt");
try
{ // 腳本學(xué)堂 www.jbxue.com
printPreviewDialog.ShowDialog();
}
catch (Exception excep)
{
MessageBox.Show(excep.Message, "打印出錯", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
/// <summary>
/// 打印功能
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void FileMenuItem_Print_Click(object sender, EventArgs e)
{
PrintDialog printDialog = new PrintDialog {Document = printDocument};
lineReader = new StreamReader(@"f:新建文本文檔.txt");
if (printDialog.ShowDialog() == DialogResult.OK)
{
try
{
printDocument.Print();
}
catch (Exception excep)
{
MessageBox.Show(excep.Message, "打印出錯", MessageBoxButtons.OK, MessageBoxIcon.Error);
printDocument.PrintController.OnEndPrint(printDocument, new PrintEventArgs());
}
}
}
程序員應(yīng)為這3個事件編寫事件處理函數(shù)。BeginPrint事件處理函數(shù)進行打印初始化,一般設(shè)置在打印時所有頁的相同屬性或共用的資源,例如所有頁共同使用的字體、建立要打印的文件流等。PrintPage事件處理函數(shù)負責(zé)打印一頁數(shù)據(jù)。EndPrint事件處理函數(shù)進行打印善后工作。這些處理函數(shù)的第2個參數(shù)System.Drawing.Printing.PrintEventArgs e提供了一些附加信息,主要有:
l e.Cancel:布爾變量,設(shè)置為true,將取消這次打印作業(yè)。
l e.Graphics:所使用的打印機的設(shè)備環(huán)境,參見第五章。
l e.HasMorePages:布爾變量。PrintPage事件處理函數(shù)打印一頁后,仍有數(shù)據(jù)未打印,退出事件處理函數(shù)前設(shè)置HasMorePages=true,退出PrintPage事件處理函數(shù)后,將再次引發(fā)PrintPage事件,打印下一頁。
l e.MarginBounds:打印區(qū)域的大小,是Rectangle結(jié)構(gòu),元素包括左上角坐標(biāo):Left和Top,寬和高:Width和Height。單位為1/100英寸。
l e.MarginBounds:打印紙的大小,是Rectangle結(jié)構(gòu)。單位為1/100英寸。
l e.PageSettings:PageSettings類對象,包含用對話框PageSetupDialog設(shè)置的頁面打印方式的全部信息??捎脦椭榭碢ageSettings類的屬性。
注意:本例打印或預(yù)覽RichTextBox中的內(nèi)容,增加變量:StringReader streamToPrint=null。如果打印或預(yù)覽文件,改為:StreamReader streamToPrint,
接下來用winform的例子具體實現(xiàn)一個小功能:
首先我們要生成的pdf 文件中的數(shù)據(jù)來源有:從其他文本中獲得,用戶將現(xiàn)有的數(shù)據(jù)按照某只格式輸出為pdf文件
首先介紹一下,讀取txt文件中的內(nèi)容,生成pdf文件的具體代碼:
PrintDocument printDocument;
StreamReader lineReader = null;
public Form1()
{
InitializeComponent();
// 這里的printDocument對象可以通過將PrintDocument控件拖放到窗體上來實現(xiàn),注意要設(shè)置該控件的PrintPage事件。
printDocument=new PrintDocument();
printDocument.DocumentName = "張海倫測試";
printDocument.PrintPage += new PrintPageEventHandler (this.printDocument_PrintPage);
}
/// <summary>
/// 打印內(nèi)容頁面布局
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void printDocument_PrintPage(object sender, PrintPageEventArgs e)
{
var g = e.Graphics; //獲得繪圖對象
float linesPerPage = 0; //頁面的行號
float yPosition = 0; //繪制字符串的縱向位置
var count = 0; //行計數(shù)器
float leftMargin = e.MarginBounds.Left; //左邊距
float topMargin = e.MarginBounds.Top; //上邊距
string line = null;
System.Drawing.Font printFont = this.textBox.Font; //當(dāng)前的打印字體
BaseFont baseFont = BaseFont.CreateFont("f:\STSONG.TTF", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
var myBrush = new SolidBrush(Color.Black); //刷子
linesPerPage = e.MarginBounds.Height / printFont.GetHeight(g); //每頁可打印的行數(shù)
//逐行的循環(huán)打印一頁
while (count < linesPerPage && ((line = lineReader.ReadLine()) != null))
{
yPosition = topMargin + (count * printFont.GetHeight(g));
g.DrawString(line, printFont, myBrush, leftMargin, yPosition, new StringFormat());
count++;
}
}
/// <summary>
/// 打印紙設(shè)置
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void FileMenuItem_PageSet_Click(object sender, EventArgs e)
{
PageSetupDialog pageSetupDialog = new PageSetupDialog();
pageSetupDialog.Document = printDocument;
pageSetupDialog.ShowDialog();
}
/// <summary>
/// 打印機設(shè)置
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void FileMenuItem_PrintSet_Click(object sender, EventArgs e)
{
PrintDialog printDialog = new PrintDialog();
printDialog.Document = printDocument;
printDialog.ShowDialog();
}
/// <summary>
/// 預(yù)覽功能
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void FileMenuItem_PrintView_Click(object sender, EventArgs e)
{
PrintPreviewDialog printPreviewDialog = new PrintPreviewDialog {Document = printDocument};
lineReader = new StreamReader(@"f:新建文本文檔.txt");
try
{ // 腳本學(xué)堂 www.jbxue.com
printPreviewDialog.ShowDialog();
}
catch (Exception excep)
{
MessageBox.Show(excep.Message, "打印出錯", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
/// <summary>
/// 打印功能
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void FileMenuItem_Print_Click(object sender, EventArgs e)
{
PrintDialog printDialog = new PrintDialog {Document = printDocument};
lineReader = new StreamReader(@"f:新建文本文檔.txt");
if (printDialog.ShowDialog() == DialogResult.OK)
{
try
{
printDocument.Print();
}
catch (Exception excep)
{
MessageBox.Show(excep.Message, "打印出錯", MessageBoxButtons.OK, MessageBoxIcon.Error);
printDocument.PrintController.OnEndPrint(printDocument, new PrintEventArgs());
}
}
}
View Code
其次,根據(jù)現(xiàn)有數(shù)據(jù)數(shù)據(jù)某種文本樣式的pdf文件具體代碼如下:
///GetPrintSw方法用來構(gòu)造打印文本,內(nèi)部StringBuilder.AppendLine在Drawstring時單獨占有一行。
public StringBuilder GetPrintSW()
{
StringBuilder sb = new StringBuilder();
string tou = "測試管理公司名稱";
string address = "河南洛陽";
string saleID = "2010930233330"; //單號
string item = "項目";
decimal price = 25.00M;
int count = 5;
decimal total = 0.00M;
decimal fukuan = 500.00M;
sb.AppendLine(" " + tou + "
");
sb.AppendLine("--------------------------------------");
sb.AppendLine("日期:" + DateTime.Now.ToShortDateString() + " " + "單號:" + saleID);
sb.AppendLine("-----------------------------------------");
sb.AppendLine("項目" + " " + "數(shù)量" + " " + "單價" + " " + "小計");
for (int i = 0; i < count; i++)
{
decimal xiaoji = (i + 1) * price;
sb.AppendLine(item + (i + 1) + " " + (i + 1) + " " + price + " " + xiaoji);
total += xiaoji;
}
sb.AppendLine("-----------------------------------------");
sb.AppendLine("數(shù)量:" + count + " 合計: " + total);
sb.AppendLine("付款:" + fukuan);
sb.AppendLine("現(xiàn)金找零:" + (fukuan - total));
sb.AppendLine("-----------------------------------------");
sb.AppendLine("地址:" + address + "");
sb.AppendLine("電話:123456789 123456789");
sb.AppendLine("謝謝惠顧歡迎下次光臨 ");
sb.AppendLine("-----------------------------------------");
return sb;
}
View Code
最后我們在軟件中,經(jīng)常使用的是將現(xiàn)有的某條記錄生成一個pdf文件表格,里面有用戶從數(shù)據(jù)庫中獲取的值。具體代碼如下:
private void printDocument_PrintPage(object sender, PrintPageEventArgs e)
{
Font titleFont = new Font("宋體", 9, FontStyle.Bold);//標(biāo)題字體
Font font = new Font("宋體", 9, FontStyle.Regular);//正文文字
Brush brush = new SolidBrush(Color.Black);//畫刷
Pen pen = new Pen(Color.Black); //線條顏色
Point po = new Point(10, 10);
try
{
e.Graphics.DrawString(GetPrintSW().ToString(), titleFont, brush, po); //DrawString方式進行打印。
int length = 500;
int height = 500;
Graphics g = e.Graphics;//利用該圖片對象生成“畫板”
Pen p = new Pen(Color.Red, 1);//定義了一個紅色,寬度為的畫筆
g.Clear(Color.White); //設(shè)置黑色背景
//一排數(shù)據(jù)
g.DrawRectangle(p, 100, 100, 80, 20);//在畫板上畫矩形,起始坐標(biāo)為(10,10),寬為80,高為20
g.DrawRectangle(p, 180, 100, 80, 20);//在畫板上畫矩形,起始坐標(biāo)為(90,10),寬為80,高為20
g.DrawRectangle(p, 260, 100, 80, 20);//
g.DrawRectangle(p, 340, 100, 80, 20);//
g.DrawString("目標(biāo)", font, brush, 12, 12);//
g.DrawString("完成數(shù)", font, brush, 92, 12);
g.DrawString("完成率", font, brush, 172, 12);//進行繪制文字。起始坐標(biāo)為(172, 12)
g.DrawString("效率", font, brush, 252, 12);//關(guān)鍵的一步,進行繪制文字。
g.DrawRectangle(p, 10, 30, 80, 20);
g.DrawRectangle(p, 90, 30, 80, 20);
g.DrawRectangle(p, 170, 30, 80, 20);
g.DrawRectangle(p, 250, 30, 80, 20);
g.DrawString("800", font, brush, 12, 32);
g.DrawString("500", font, brush, 92, 32);//關(guān)鍵的一步,進行繪制文字。
g.DrawString("60%", font, brush, 172, 32);//關(guān)鍵的一步,進行繪制文字。
g.DrawString("50%", font, brush, 252, 32);//關(guān)鍵的一步,進行繪制文字。
g.DrawRectangle(p, 10, 50, 80, 20);
g.DrawRectangle(p, 90, 50, 80, 20);
g.DrawRectangle(p, 170, 50, 160, 20);//在畫板上畫矩形,起始坐標(biāo)為(170,10),寬為160,高為20
g.DrawString("總查數(shù)", font, brush, 12, 52);
g.DrawString("不良數(shù)", font, brush, 92, 52);
g.DrawString("合格率", font, brush, 222, 52);
g.Dispose();//釋放掉該資源
}
catch (Exception ex)
{
MessageBox.Show(this, "打印出錯!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
View Code
效果圖如:
上面這3個例子,均是在winform中實現(xiàn)的,最后一個功能的實現(xiàn)比較復(fù)雜,不是很好,
下面是倆個wpf實現(xiàn)打印的例子,
簡單的一個具體代碼有:
1 public MainWindow()
2 {
3 InitializeComponent();
4 }
5 /// <summary>
6 /// 我得第一個Pdf程序
7 /// </summary>
8 private void CreatePdf()
9 {
10 string fileName = string.Empty;
11 Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
12 dlg.FileName = "我的第一個PDF";
13 dlg.DefaultExt = ".pdf";
14 dlg.Filter = "Text documents (.pdf)|*.pdf";
15 Nullable<bool> result = dlg.ShowDialog();
16 if (result == true)
17 {
18 fileName = dlg.FileName;
19 Document document = new Document();
20 PdfWriter.GetInstance(document, new FileStream(fileName, FileMode.Create));
21 document.Open();
22 iTextSharp.text.Paragraph paragraph = new iTextSharp.text.Paragraph("Hello World");
23 document.Add(paragraph);
24 document.Close();
25 }//end if
26 }
27 /// <summary>
28 /// 設(shè)置頁面大小、作者、標(biāo)題等相關(guān)信息設(shè)置
29 /// </summary>
30 private void CreatePdfSetInfo()
31 {
32 string fileName = string.Empty;
33 Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
34 dlg.FileName = "我的第一個PDF";
35 dlg.DefaultExt = ".pdf";
36 dlg.Filter = "Text documents (.pdf)|*.pdf";
37 Nullable<bool> result = dlg.ShowDialog();
38 if (result == true)
39 {
40 fileName = dlg.FileName;
41 //設(shè)置頁面大小
42 iTextSharp.text.Rectangle pageSize = new iTextSharp.text.Rectangle(216f, 716f);
43 pageSize.BackgroundColor = new iTextSharp.text.BaseColor(0xFF, 0xFF, 0xDE);
44 //設(shè)置邊界
45 Document document = new Document(pageSize, 36f, 72f, 108f, 180f);
46 PdfWriter.GetInstance(document, new FileStream(fileName, FileMode.Create));
47 // 添加文檔信息
48 document.AddTitle("PDFInfo");
49 document.AddSubject("Demo of PDFInfo");
50 document.AddKeywords("Info, PDF, Demo");
51 document.AddCreator("SetPdfInfoDemo");
52 document.AddAuthor("焦?jié)?);
53 document.Open();
54 // 添加文檔內(nèi)容
55 for (int i = 0; i < 5; i++)
56 {
57 document.Add(new iTextSharp.text.Paragraph("Hello World! Hello People! " +"Hello Sky! Hello Sun! Hello Moon! Hello Stars!"));
58 }
59 document.Close();
60 }//end if
61 }
62 /// <summary>
63 /// 創(chuàng)建多個Pdf新頁
64 /// </summary>
65 private void CreateNewPdfPage()
66 {
67 string fileName = string.Empty;
68 Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
69 dlg.FileName = "創(chuàng)建多個Pdf新頁";//生成的pdf文件名
70 dlg.DefaultExt = ".pdf";//pdf的默認后綴名
71 dlg.Filter = "Text documents (.pdf)|*.pdf";
72 Nullable<bool> result = dlg.ShowDialog();
73 if (result == true)
74 {
75 fileName = dlg.FileName;
76 Document document = new Document(PageSize.NOTE);
77 PdfWriter writer= PdfWriter.GetInstance(document, new FileStream(fileName, FileMode.Create));
78 document.Open();
79 // 第一頁
80 document.Add(new iTextSharp.text.Paragraph("PDF1, PDF1, PDF1, PDF1, PDF1"));
81 document.Add(new iTextSharp.text.Paragraph("PDF1, PDF1, PDF1, PDF1, PDF1"));
82 document.Add(new iTextSharp.text.Paragraph("PDF1, PDF1, PDF1, PDF1, PDF1"));
83 document.Add(new iTextSharp.text.Paragraph("PDF1, PDF1, PDF1, PDF1, PDF1"));
84 // 添加新頁面
85 document.NewPage();
86 // 第二頁
87 // 添加第二頁內(nèi)容
88 document.Add(new iTextSharp.text.Paragraph("PDF2, PDF2, PDF2, PDF2, PDF2"));
89 document.Add(new iTextSharp.text.Paragraph("PDF2, PDF2, PDF2, PDF2, PDF2"));
90 document.Add(new iTextSharp.text.Paragraph("PDF2, PDF2, PDF2, PDF2, PDF2"));
91 document.Add(new iTextSharp.text.Paragraph("PDF2, PDF2, PDF2, PDF2, PDF2"));
92 document.Add(new iTextSharp.text.Paragraph("PDF2, PDF2, PDF2, PDF2, PDF2"));
93 document.Add(new iTextSharp.text.Paragraph("PDF2, PDF2, PDF2, PDF2, PDF2"));
94 // 添加新頁面
95 document.NewPage();
96 // 第三頁
97 // 添加新內(nèi)容
98 document.Add(new iTextSharp.text.Paragraph("PDF3, PDF3, PDF3, PDF3, PDF3"));
99 document.Add(new iTextSharp.text.Paragraph("PDF3, PDF3, PDF3, PDF3, PDF3"));
100 document.Add(new iTextSharp.text.Paragraph("PDF3, PDF3, PDF3, PDF3, PDF3"));
101 document.Add(new iTextSharp.text.Paragraph("PDF3, PDF3, PDF3, PDF3, PDF3"));
102 // 重新開始頁面計數(shù)
103 document.ResetPageCount();
104 // 新建一頁
105 document.NewPage();
106 // 第四頁
107 // 添加第四頁內(nèi)容
108 document.Add(new iTextSharp.text.Paragraph("PDF4, PDF4, PDF4, PDF4, PDF4"));
109 document.Add(new iTextSharp.text.Paragraph("PDF4, PDF4, PDF4, PDF4, PDF4"));
110 document.Add(new iTextSharp.text.Paragraph("PDF4, PDF4, PDF4, PDF4, PDF4"));
111 document.Add(new iTextSharp.text.Paragraph("PDF4, PDF4, PDF4, PDF4, PDF4"));
112 document.Close();
113 }//end if
114 }
115 /// <summary>
116 /// 生成圖片pdf頁(pdf中插入圖片)
117 /// </summary>
118 public void ImageDirect()
119 {
120 string imagePath = AppDomain.CurrentDomain.BaseDirectory + @"Image1.jpg"; //臨時文件路徑
121 string fileName = string.Empty;
122 Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
123 dlg.FileName = "我的第一個PDF";
124 dlg.DefaultExt = ".pdf";
125 dlg.Filter = "Text documents (.pdf)|*.pdf";
126 Nullable<bool> result = dlg.ShowDialog();
127 if (result == true)
128 {
129 fileName = dlg.FileName;
130 Document document = new Document();
131 PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(fileName, FileMode.Create));
132 document.Open();
133 iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(imagePath);
134 img.SetAbsolutePosition((PageSize.POSTCARD.Width - img.ScaledWidth) / 2, (PageSize.POSTCARD.Height - img.ScaledHeight) / 2);
135 writer.DirectContent.AddImage(img);
136 iTextSharp.text.Paragraph p = new iTextSharp.text.Paragraph("Foobar Film Festival", new iTextSharp.text.Font(Font.FontFamily.HELVETICA, 22f));
137 p.Alignment = Element.ALIGN_CENTER;
138 document.Add(p);
139 document.Close();
140 }//end if
141 }
142 private void ReadPdf()
143 {
144 Console.WriteLine("讀取PDF文檔");
145 try
146 {
147 // 創(chuàng)建一個PdfReader對象
148 PdfReader reader = new PdfReader(@"D:我的第一個PDF.pdf");
149 // 獲得文檔頁數(shù)
150 int n = reader.NumberOfPages;
151 // 獲得第一頁的大小
152 iTextSharp.text.Rectangle psize = reader.GetPageSize(1);
153 float width = psize.Width;
154 float height = psize.Height;
155 // 創(chuàng)建一個文檔變量
156 Document document = new Document(psize, 50, 50, 50, 50);
157 // 創(chuàng)建該文檔
158 PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(@"d:Read.pdf", FileMode.Create));
159 // 打開文檔
160 document.Open();
161 // 添加內(nèi)容
162 PdfContentByte cb = writer.DirectContent;
163 int i = 0;
164 int p = 0;
165 Console.WriteLine("一共有 " + n + " 頁.");
166 while (i < n)
167 {
168 document.NewPage();
169 p++;
170 i++;
171 PdfImportedPage page1 = writer.GetImportedPage(reader, i);
172 cb.AddTemplate(page1, .5f, 0, 0, .5f, 0, height / 2);
173 Console.WriteLine("處理第 " + i + " 頁");
174 if (i < n)
175 {
176 i++;
177 PdfImportedPage page2 = writer.GetImportedPage(reader, i);
178 cb.AddTemplate(page2, .5f, 0, 0, .5f, width / 2, height / 2);
179 Console.WriteLine("處理第 " + i + " 頁");
180 }
181 if (i < n)
182 {
183 i++;
184 PdfImportedPage page3 = writer.GetImportedPage(reader, i);
185 cb.AddTemplate(page3, .5f, 0, 0, .5f, 0, 0);
186 Console.WriteLine("處理第 " + i + " 頁");
187 }
188 if (i < n)
189 {
190 i++;
191 PdfImportedPage page4 = writer.GetImportedPage(reader, i);
192 cb.AddTemplate(page4, .5f, 0, 0, .5f, width / 2, 0);
193 Console.WriteLine("處理第 " + i + " 頁");
194 }
195 cb.SetRGBColorStroke(255, 0, 0);
196 cb.MoveTo(0, height / 2);
197 cb.LineTo(width, height / 2);
198 cb.Stroke();
199 cb.MoveTo(width / 2, height);
200 cb.LineTo(width / 2, 0);
201 cb.Stroke();
202 BaseFont bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
203 cb.BeginText();
204 cb.SetFontAndSize(bf, 14);
205 cb.ShowTextAligned(PdfContentByte.ALIGN_CENTER, "page " + p + " of " + ((n / 4) + (n % 4 > 0 ? 1 : 0)), width / 2, 40, 0);
206 cb.EndText();
207 }
208 // 關(guān)閉文檔
209 document.Close();
210 }
211 catch (Exception de)
212 {
213 Console.Error.WriteLine(de.Message);
214 Console.Error.WriteLine(de.StackTrace);
215 }
216 }
217
218 /// <summary>
219 /// 創(chuàng)建表格
220 /// </summary>
221 public void CreateFirstTable()
222 {
223 string imagePath = AppDomain.CurrentDomain.BaseDirectory + @"Image1.pm"; //臨時文件路徑
224 string fileName = string.Empty;
225 Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
226 dlg.FileName = "我的第一個PDF";
227 dlg.DefaultExt = ".pdf";
228 dlg.Filter = "Text documents (.pdf)|*.pdf";
229 Nullable<bool> result = dlg.ShowDialog();
230 BaseFont baseFont = BaseFont.CreateFont("D:\STSONG.TTF",BaseFont.IDENTITY_H,BaseFont.NOT_EMBEDDED);
231 iTextSharp.text.Font font = new iTextSharp.text.Font(baseFont, 9);
232 if (result == true)
233 {
234 fileName = dlg.FileName;
235 Document document = new Document();
236 PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(fileName, FileMode.Create));
237 document.Open();
238
239 iTextSharp.text.Paragraph p;
240 p = new iTextSharp.text.Paragraph("中華人民共和國海關(guān)出口貨物打單", font);
241 p.Alignment = Element.ALIGN_CENTER;//設(shè)置標(biāo)題居中
242 p.SpacingAfter = 12;//設(shè)置段落行 通過設(shè)置Paragraph的SpacingBefore和SpacingAfter屬性調(diào)整Paragraph對象與之間或之后段落的間距
243 p.SpacingBefore = 1;
244 document.Add(p);//添加段落
245
246 p = new iTextSharp.text.Paragraph(GetBlank(5)+"預(yù)錄入編號:" +"編號代碼"+GetBlank(15)+"海關(guān)編號:"+GetBlank(5),font);
247 //p.IndentationLeft = 20;
248 //p.IndentationLeft = 20;
249 //p.IndentationRight = 20;
250 //p.FirstLineIndent = 20;
251 //IndentationLeft屬性設(shè)置左側(cè)縮進。
252 //IndentationRight屬性設(shè)置右側(cè)縮進。
253 p.SpacingAfter = 12;
254 document.Add(p);//添加段落
255
256
257 PdfPTable table = new PdfPTable(10);//幾列
258
259 PdfPCell cell;
260 cell=new PdfPCell(new Phrase("收發(fā)貨人"+GetBlank(5)+"具體值"));
261 cell.Colspan = 4;
262
263 table.AddCell(cell);
264
265 cell = new PdfPCell(new Phrase("出關(guān)口岸"+GetBlank(10)+"具體值"));
266 cell.Rowspan = 2;
267 table.AddCell(cell);
268 cell = new PdfPCell(new Phrase("出口日期" + GetBlank(10) + "具體值"));
269 cell.Rowspan = 2;
270 table.AddCell(cell);
271 cell = new PdfPCell(new Phrase("申報日期" + GetBlank(10) + "具體值"));
272 cell.Rowspan = 2;
273 table.AddCell(cell);
274
275
276 cell = new PdfPCell(new Phrase("收發(fā)貨人" + GetBlank(5) + "具體值"));
277 cell.Colspan = 4;
278 table.AddCell(cell);
279
280 cell = new PdfPCell(new Phrase("出關(guān)口岸" + GetBlank(10) + "具體值"));
281 cell.Rowspan = 2;
282 table.AddCell(cell);
283 cell = new PdfPCell(new Phrase("出口日期" + GetBlank(10) + "具體值"));
284 cell.Rowspan = 2;
285 table.AddCell(cell);
286 cell = new PdfPCell(new Phrase("申報日期" + GetBlank(10) + "具體值"));
287 cell.Rowspan = 2;
288 table.AddCell(cell);
289
290
291 //table.AddCell("row 1; cell 1");
292 //table.AddCell("row 1; cell 2");
293 //table.AddCell("row 2; cell 1");
294 //table.AddCell("row 2; cell 2");
295 document.Add(table);
296 document.Close();
297 }//end if
298 }
299 /// <summary>
300 /// 獲得空格
301 /// </summary>
302 /// <param name="num"></param>
303 /// <returns></returns>
304 private static string GetBlank(int num)
305 {
306 StringBuilder blank = new StringBuilder();
307 for (int i = 0; i < num; i++)
308 {
309 blank.Append(" ");
310 }
311 return blank.ToString();
312 }
313
314 private void button1_Click(object sender, RoutedEventArgs e)
315 {
316 //CreatePdf();
317 //CreatePdfPageSize();
318 CreateNewPdfPage();
319 }
320 private void button2_Click(object sender, RoutedEventArgs e)
321 {
322 CreateFirstTable();
323 }
324
325 private void button3_Click(object sender, RoutedEventArgs e)
326 {
327 ImageDirect();
328 }
329
330 private void button4_Click(object sender, RoutedEventArgs e)
331 {
332 ReadPdf();
333 }
View Code
在這里用到了iTextSharp ,需要先先下載dll文件,然后引用,總結(jié)一下其中常用的用法和屬性之類的知識點,
PdfWriter的setInitialLeading操作用于設(shè)置行間距 Font font = new Font(Font.FontFamily.COURIER, 12, Font.BOLD, BaseColor.WHITE); 設(shè)置縮進 iTextSharp中,Paragraph有三個屬性可以設(shè)置縮進: //設(shè)置Paragraph對象的縮進 contentPara1.IndentationLeft = 20; contentPara1.IndentationRight = 20; contentPara1.FirstLineIndent = 20; IndentationLeft屬性設(shè)置左側(cè)縮進。 IndentationRight屬性設(shè)置右側(cè)縮進。 FirstLineIndent屬性設(shè)置首行左側(cè)縮進。 三個值都可設(shè)為正負值。 設(shè)置對齊方式 設(shè)置Alignment屬性可以調(diào)整Paragraph對象中文字的對齊方式。如: //設(shè)置Paragraph對象的對齊方式為兩端對齊 contentPara1.Alignment = Element.ALIGN_JUSTIFIED; 默認情況使用左對齊。 Paragraph之間的間距 iTextSharp中,通過設(shè)置Paragraph的SpacingBefore和SpacingAfter屬性調(diào)整Paragraph對象與之間或之后段落的間距。例如: //設(shè)置Paragraph對象與后面Paragraph對象之間的間距 contentPara1.SpacingAfter = 36; 文字分行問題 iText默認的規(guī)則是盡可能多的將完整單詞放在同一行內(nèi)。iText當(dāng)遇到空格或連字符才會分行,可以通過重新定義分隔符(split character)來改變這種規(guī)則。 分隔符(the split character) 使用nonbreaking space character,(char)160代替普通空格(char)32放入兩個單詞中間從而避免iText將它們放到不同行中。
最好的是自己設(shè)計界面和功能當(dāng)做模板使用,綁定數(shù)據(jù)實現(xiàn)如winform第三個例子樣的功能。
總結(jié)
以上是生活随笔為你收集整理的C#教程之打印和打印预览的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 'Request' object has
- 下一篇: 基本SCTP套接字编程常用函数