C#教程之打印和打印預覽


    最近研究一了一下關於PDF打印和打印預覽的功能,在此小小的總結記錄一下學習過程。

實現打印和打印預覽的方法,一般要實現如下的菜單項:打印、打印預覽、頁面設置、

PrintDocument類

  PrintDocument組件是用於完成打印的類,其常用的屬性、方法事件如下:

屬性DocumentName:字符串類型,記錄打印文檔時顯示的文檔名(例如,在打印狀態對話框或打印機隊列中顯示),即用戶填寫生成pdf文件名時的默認值為DocumentName
方法Print:開始文檔的打印。
事件BeginPrint:在調用Print方法后,在打印文檔的第一頁之前發生。
事件PrintPage:需要打印新的一頁時發生。
事件EndPrint:在文檔的最后一頁打印后發生。

若要打印,首先創建PrintDocument組建的對象,然后使用頁面上設置對話框PageSetupDialog設置頁面打印方式,這些設置作為打印頁的默認設置、使用打印對話框PrintDialog設置對文檔進行打印的打印機的參數。在打開兩個對話框前,首先設置對話框的屬性Document為指定的PrintDocument類對象,修改的設置將保存到PrintDocument組件對象中。

第三步是調用PrintDocument.Print方法來實際打印文檔,調用該方法后,引發下列事件:BeginPrint、PrintPage、EndPrint。其中每打印一頁都引發PrintPage事件,打印多頁,要多次引發PrintPage事件。完成一次打印,可以引發一個或多個PrintPage事件。

        /// <summary>
        /// 打印紙設置
        /// </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>
        /// 打印機設置
        /// </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>
        /// 預覽功能
        /// </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
            { // 腳本學堂 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());
                }
            }
        }

程序員應為這3個事件編寫事件處理函數。BeginPrint事件處理函數進行打印初始化,一般設置在打印時所有頁的相同屬性或共用的資源,例如所有頁共同使用的字體、建立要打印的文件流等。PrintPage事件處理函數負責打印一頁數據。EndPrint事件處理函數進行打印善后工作。這些處理函數的第2個參數System.Drawing.Printing.PrintEventArgs e提供了一些附加信息,主要有:
l e.Cancel:布爾變量,設置為true,將取消這次打印作業。
l e.Graphics:所使用的打印機的設備環境,參見第五章。
l e.HasMorePages:布爾變量。PrintPage事件處理函數打印一頁后,仍有數據未打印,退出事件處理函數前設置HasMorePages=true,退出PrintPage事件處理函數后,將再次引發PrintPage事件,打印下一頁。
l e.MarginBounds:打印區域的大小,是Rectangle結構,元素包括左上角坐標:Left和Top,寬和高:Width和Height。單位為1/100英寸。
l e.MarginBounds:打印紙的大小,是Rectangle結構。單位為1/100英寸。
l e.PageSettings:PageSettings類對象,包含用對話框PageSetupDialog設置的頁面打印方式的全部信息。可用幫助查看PageSettings類的屬性。

注意:本例打印或預覽RichTextBox中的內容,增加變量:StringReader streamToPrint=null。如果打印或預覽文件,改為:StreamReader streamToPrint,

    接下來用winform的例子具體實現一個小功能:

   首先我們要生成的pdf 文件中的數據來源有:從其他文本中獲得,用戶將現有的數據按照某只格式輸出為pdf文件

   首先介紹一下,讀取txt文件中的內容,生成pdf文件的具體代碼:

 PrintDocument printDocument;
        StreamReader lineReader = null;
        public Form1()
        {
            InitializeComponent();
            // 這里的printDocument對象可以通過將PrintDocument控件拖放到窗體上來實現,注意要設置該控件的PrintPage事件。
            printDocument=new PrintDocument();
            printDocument.DocumentName = "張海倫測試";
            printDocument.PrintPage += new PrintPageEventHandler (this.printDocument_PrintPage);
        }

        /// <summary>
        /// 打印內容頁面布局
        /// </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; //行計數器
            float leftMargin = e.MarginBounds.Left; //左邊距
            float topMargin = e.MarginBounds.Top; //上邊距
            string line = null;
            System.Drawing.Font printFont = this.textBox.Font; //當前的打印字體
            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); //每頁可打印的行數
            //逐行的循環打印一頁
            while (count < linesPerPage && ((line = lineReader.ReadLine()) != null))
            {
                yPosition = topMargin + (count * printFont.GetHeight(g));
                g.DrawString(line, printFont, myBrush, leftMargin, yPosition, new StringFormat());
                count++;           
            }        
        
        }
        
        /// <summary>
        /// 打印紙設置
        /// </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>
        /// 打印機設置
        /// </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>
        /// 預覽功能
        /// </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
            { // 腳本學堂 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

  其次,根據現有數據數據某種文本樣式的pdf文件具體代碼如下:

  ///GetPrintSw方法用來構造打印文本,內部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 + " \n");
            sb.AppendLine("--------------------------------------");
            sb.AppendLine("日期:" + DateTime.Now.ToShortDateString() + " " + "單號:" + saleID);
            sb.AppendLine("-----------------------------------------");
            sb.AppendLine("項目" + "      " + "數量" + "    " + "單價" + "    " + "小計");
            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("數量:" + count + "  合計: " + total);
            sb.AppendLine("付款:" + fukuan);
            sb.AppendLine("現金找零:" + (fukuan - total));
            sb.AppendLine("-----------------------------------------");
            sb.AppendLine("地址:" + address + "");
            sb.AppendLine("電話:123456789 123456789");
            sb.AppendLine("謝謝惠顧歡迎下次光臨 ");
            sb.AppendLine("-----------------------------------------");
            return sb;

        }
View Code

最后我們在軟件中,經常使用的是將現有的某條記錄生成一個pdf文件表格,里面有用戶從數據庫中獲取的值。具體代碼如下:

private void printDocument_PrintPage(object sender, PrintPageEventArgs e)
        {
            Font titleFont = new Font("宋體", 9, FontStyle.Bold);//標題字體            
            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); //設置黑色背景
                //一排數據
                g.DrawRectangle(p, 100, 100, 80, 20);//在畫板上畫矩形,起始坐標為(10,10),寬為80,高為20
                g.DrawRectangle(p, 180, 100, 80, 20);//在畫板上畫矩形,起始坐標為(90,10),寬為80,高為20
                g.DrawRectangle(p, 260, 100, 80, 20);//
                g.DrawRectangle(p, 340, 100, 80, 20);//
                g.DrawString("目標", font, brush, 12, 12);//
                g.DrawString("完成數", font, brush, 92, 12);
                g.DrawString("完成率", font, brush, 172, 12);//進行繪制文字。起始坐標為(172, 12)
                g.DrawString("效率", font, brush, 252, 12);//關鍵的一步,進行繪制文字。

                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);//關鍵的一步,進行繪制文字。
                g.DrawString("60%", font, brush, 172, 32);//關鍵的一步,進行繪制文字。
                g.DrawString("50%", font, brush, 252, 32);//關鍵的一步,進行繪制文字。

                g.DrawRectangle(p, 10, 50, 80, 20);
                g.DrawRectangle(p, 90, 50, 80, 20);
                g.DrawRectangle(p, 170, 50, 160, 20);//在畫板上畫矩形,起始坐標為(170,10),寬為160,高為20
                g.DrawString("總查數", font, brush, 12, 52);
                g.DrawString("不良數", 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中實現的,最后一個功能的實現比較復雜,不是很好,

 下面是倆個wpf實現打印的例子,

  簡單的一個具體代碼有:

  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         /// 設置頁面大小、作者、標題等相關信息設置
 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                 //設置頁面大小
 42                 iTextSharp.text.Rectangle pageSize = new iTextSharp.text.Rectangle(216f, 716f);
 43                 pageSize.BackgroundColor = new iTextSharp.text.BaseColor(0xFF, 0xFF, 0xDE);
 44                 //設置邊界
 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("焦濤");
 53                 document.Open();
 54                 // 添加文檔內容
 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         /// 創建多個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 = "創建多個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                 // 添加第二頁內容
 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                 // 添加新內容
 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                 // 重新開始頁面計數
103                 document.ResetPageCount();
104                 // 新建一頁
105                 document.NewPage();
106                 // 第四頁
107                 // 添加第四頁內容
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 + @"Image\1.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                 // 創建一個PdfReader對象
148                 PdfReader reader = new PdfReader(@"D:\我的第一個PDF.pdf");
149                 // 獲得文檔頁數
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                 // 創建一個文檔變量
156                 Document document = new Document(psize, 50, 50, 50, 50);
157                 // 創建該文檔
158                 PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(@"d:\Read.pdf", FileMode.Create));
159                 // 打開文檔
160                 document.Open();
161                 // 添加內容
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                 // 關閉文檔
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         /// 創建表格
220         /// </summary>
221         public void CreateFirstTable()
222         {
223             string imagePath = AppDomain.CurrentDomain.BaseDirectory + @"Image\1.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("中華人民共和國海關出口貨物打單", font);
241                 p.Alignment = Element.ALIGN_CENTER;//設置標題居中
242                 p.SpacingAfter = 12;//設置段落行 通過設置Paragraph的SpacingBefore和SpacingAfter屬性調整Paragraph對象與之間或之后段落的間距
243                 p.SpacingBefore = 1;
244                 document.Add(p);//添加段落
245 
246                 p = new iTextSharp.text.Paragraph(GetBlank(5)+"預錄入編號:" +"編號代碼"+GetBlank(15)+"海關編號:"+GetBlank(5),font);
247                 //p.IndentationLeft = 20;
248                 //p.IndentationLeft = 20;
249                 //p.IndentationRight = 20;
250                 //p.FirstLineIndent = 20;
251                 //IndentationLeft屬性設置左側縮進。
252                 //IndentationRight屬性設置右側縮進。
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("收發貨人"+GetBlank(5)+"具體值"));
261                 cell.Colspan = 4;
262                 
263                 table.AddCell(cell);
264                 
265                 cell = new PdfPCell(new Phrase("出關口岸"+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("收發貨人" + GetBlank(5) + "具體值"));
277                 cell.Colspan = 4;
278                 table.AddCell(cell);
279 
280                 cell = new PdfPCell(new Phrase("出關口岸" + 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文件,然后引用,總結一下其中常用的用法和屬性之類的知識點,

PdfWriter的setInitialLeading操作用於設置行間距
Font font = new Font(Font.FontFamily.COURIER, 12, Font.BOLD, BaseColor.WHITE);
設置縮進
iTextSharp中,Paragraph有三個屬性可以設置縮進:
//設置Paragraph對象的縮進
contentPara1.IndentationLeft = 20;
contentPara1.IndentationRight = 20;
contentPara1.FirstLineIndent = 20;
IndentationLeft屬性設置左側縮進。
IndentationRight屬性設置右側縮進。
FirstLineIndent屬性設置首行左側縮進。
三個值都可設為正負值。
設置對齊方式
設置Alignment屬性可以調整Paragraph對象中文字的對齊方式。如:
//設置Paragraph對象的對齊方式為兩端對齊
contentPara1.Alignment = Element.ALIGN_JUSTIFIED;
默認情況使用左對齊。
Paragraph之間的間距
iTextSharp中,通過設置Paragraph的SpacingBefore和SpacingAfter屬性調整Paragraph對象與之間或之后段落的間距。例如:
//設置Paragraph對象與后面Paragraph對象之間的間距
contentPara1.SpacingAfter = 36;
文字分行問題
iText默認的規則是盡可能多的將完整單詞放在同一行內。iText當遇到空格或連字符才會分行,可以通過重新定義分隔符(split character)來改變這種規則。
 
分隔符(the split character)
使用nonbreaking space character,(char)160代替普通空格(char)32放入兩個單詞中間從而避免iText將它們放到不同行中。

最好的是自己設計界面和功能當做模板使用,綁定數據實現如winform第三個例子樣的功能。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM