溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Winform怎么用分頁控件實(shí)現(xiàn)導(dǎo)出PDF文檔功能

發(fā)布時(shí)間:2023-05-12 14:23:43 來源:億速云 閱讀:110 作者:iii 欄目:開發(fā)技術(shù)

本篇內(nèi)容主要講解“Winform怎么用分頁控件實(shí)現(xiàn)導(dǎo)出PDF文檔功能”,感興趣的朋友不妨來看看。本文介紹的方法操作簡單快捷,實(shí)用性強(qiáng)。下面就讓小編來帶大家學(xué)習(xí)“Winform怎么用分頁控件實(shí)現(xiàn)導(dǎo)出PDF文檔功能”吧!

1、PDF的導(dǎo)出插件

使用PDF導(dǎo)出的插件有很多,如Aspose.PDF、Spire.PDF、PdfSharp、iTextSharp等等很多,有些是收費(fèi)的,有些是開源免費(fèi)的,我們這里使用iTextSharp開源組件進(jìn)行PDF的導(dǎo)出處理操作。

Winform怎么用分頁控件實(shí)現(xiàn)導(dǎo)出PDF文檔功能

在測試的時(shí)候,我們可以對一個(gè)表格內(nèi)容進(jìn)行數(shù)據(jù)的導(dǎo)出,以便驗(yàn)證效果,然后在考慮整合到分頁控件的內(nèi)部中使用,如下測試界面所示。

Winform怎么用分頁控件實(shí)現(xiàn)導(dǎo)出PDF文檔功能

大概的效果如下所示。

Winform怎么用分頁控件實(shí)現(xiàn)導(dǎo)出PDF文檔功能

如果需要,我們可以進(jìn)一步定義頁眉和頁腳,增加一些特殊的信息等等。

我們可以測試導(dǎo)出列表中的DataTable數(shù)據(jù)源,如下所示。

private void btnExportPdf_Click(object sender, EventArgs e)
        {
            //帶參數(shù)處理
            bool isLandscape = true;//是否為橫向打印,默認(rèn)為true
            bool includeHeader = true;//是否每頁包含表頭信息
            int headerAlignment = Element.ALIGN_CENTER;//頭部的對其方式,默認(rèn)為居中對齊
            float headerFontSize = 9f;//頭部字體大小
            float rowFontSize = 9f;//行記錄字體大小
            float? headerFixHeight = null;//頭部的固定高度,否則為自適應(yīng)
            <strong>TextSharpHelper</strong><strong>.ExportPdf</strong>(isLandscape, includeHeader, headerAlignment, headerFontSize, rowFontSize, headerFixHeight);
        }

2、導(dǎo)出PDF的邏輯處理

上面的操作,對輔助類TextSharpHelper.ExportPdf 的操作進(jìn)行封裝了,我們可以看到,方法留出了幾個(gè)特殊的配置信息,可供我們進(jìn)行調(diào)整格式。

一般使用列表的輸出為橫向較為美觀,字體比正常窗體顯示的字體小一點(diǎn),并可以設(shè)置是否每頁P(yáng)DF包含表頭信息等等。

輔助類的全部代碼如下所示:

/// <summary>
    /// 基于iTextSharp.text.pdf對PDF的導(dǎo)出處理
    /// </summary>
    public static class TextSharpHelper
    {
        /// <summary>
        /// datatable轉(zhuǎn)PDF方法
        /// </summary>
        /// <param name="data">dataTable數(shù)據(jù)</param>
        /// <param name="pdfFile">PDF文件保存的路徑</param>
        /// <param name="isLandscape">是否為橫向打印,默認(rèn)為true</param>
        /// <param name="includeHeader">是否每頁包含表頭信息</param>
        /// <param name="headerAlignment">頭部的對其方式,默認(rèn)為居中對齊</param>
        /// <param name="headerFontSize">頭部字體大小</param>
        /// <param name="rowFontSize">行記錄字體大小</param>
        /// <param name="headerFixHeight">頭部的固定高度,否則為自適應(yīng)</param>
        /// <returns></returns>
        public static bool ExportTableToPdf(DataTable data, string pdfFile, bool isLandscape = true, bool includeHeader = true, int headerAlignment = Element.ALIGN_CENTER, float headerFontSize = 9f, float rowFontSize = 9f, float? headerFixHeight = null)
        {
            //默認(rèn)頁面大小
            var document = new Document();
            var retangle = new iTextSharp.text.Rectangle(0, 0, isLandscape ? PageSize.A4.Height : PageSize.A4.Width, isLandscape ? PageSize.A4.Width : PageSize.A4.Height);
            document.SetPageSize(retangle);
            var writer = PdfWriter.GetInstance(document, new FileStream(pdfFile, FileMode.Create));
            document.Open();

            //設(shè)置字體
            var bfChinese = BaseFont.CreateFont("C:\\WINDOWS\\Fonts\\simsun.ttc,1", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
            var fontHeader = new iTextSharp.text.Font(bfChinese, headerFontSize, iTextSharp.text.Font.BOLD, new BaseColor(0, 0, 0));
            var fontRow = new iTextSharp.text.Font(bfChinese, rowFontSize, iTextSharp.text.Font.NORMAL, new BaseColor(0, 0, 0));

            var table = new PdfPTable(data.Columns.Count);
            table.WidthPercentage = 100f; // percentage
            table.DefaultCell.Padding = 1;
            table.DefaultCell.BorderWidth = 1;
            table.DefaultCell.BorderWidth = 0.1f;
            table.DefaultCell.HorizontalAlignment = Element.ALIGN_LEFT;
            table.HeaderRows = includeHeader ? 1 : 0;

            //將datatable表頭轉(zhuǎn)換成PDFTable的表頭
            var EventRowBackColor = Color.LightCyan;
            foreach (DataColumn dc in data.Columns)
            {
                var caption = !string.IsNullOrEmpty(dc.Caption) ? dc.Caption : dc.ColumnName;

                var cell = new PdfPCell();
                if (headerFixHeight.HasValue)
                {
                    cell.FixedHeight = headerFixHeight.Value;
                }
                cell.HorizontalAlignment = headerAlignment;
                cell.VerticalAlignment = Element.ALIGN_MIDDLE;
                cell.Phrase = new Phrase(caption, fontHeader);
                table.AddCell(cell);
            }

            //插入數(shù)據(jù)
            for (int i = 0; i < data.Rows.Count; i++)
            {
                var backgroudColor = new BaseColor((i % 2 == 0) ? Color.White : EventRowBackColor);
                for (int j = 0; j < data.Columns.Count; j++)
                {
                    var cell = new PdfPCell();
                    var text = data.Rows[i][j].ToString();
                    cell.BackgroundColor = backgroudColor;
                    cell.Phrase = new Phrase(text, fontRow);
                    table.AddCell(cell);
                }
            }
            document.Add(table);
            document.Close();
            writer.Close();
            return true;
        }
    }

上面根據(jù)方法的參數(shù)對字體,頁面寬度高度、表格間隔顏色,表頭等信息進(jìn)行設(shè)置處理,然后使用插件進(jìn)行輸出PDF的內(nèi)容即可,PDF內(nèi)容的輸出,有點(diǎn)類似DataTable的表格控制,單元格的信息可以獨(dú)立控制。

為了不用重復(fù)的引用代碼或者輔助類,我們可以整合到分頁控件的列表中,在其中封裝處理邏輯即可,這樣所有列表都具有通用的導(dǎo)出PDF操作了,如下界面所示。

Winform怎么用分頁控件實(shí)現(xiàn)導(dǎo)出PDF文檔功能

我們一般導(dǎo)出是通過事件進(jìn)行處理的,因此,我們在底部的分頁中定義一個(gè)觸發(fā)的事件,如下所示。

public delegate void <strong>ExportPdfEventHandler</strong>(object sender, EventArgs e);
    /// <summary>
    /// 分頁工具條用戶控件,僅提供分頁信息顯示及改變頁碼操作
    /// </summary>
    public class Pager : DevExpress.XtraEditors.XtraUserControl
    {
        /// <summary>
        /// 導(dǎo)出PDF的事件
        /// </summary>
        public event <strong>ExportPdfEventHandler</strong> ExportPdf;

按鈕單擊的時(shí)候,觸發(fā)事件的處理,如下代碼所示。

private void btnExportPdf_Click(object sender, EventArgs e)
        {
            if (ExportPdf != null)
            {
                ExportPdf(sender, e);
            }
        }

這樣事件會傳遞到外面的容器組件中,對容器組件中的數(shù)據(jù)源進(jìn)行導(dǎo)出處理即可。

private void WinGridViewPager_Load(object sender, EventArgs e)
        {
            if (!this.DesignMode)
            {
                this.pager.PageChanged += new PageChangedEventHandler(pager_PageChanged);
                this.pager.ExportCurrent += new ExportCurrentEventHandler(pager_ExportCurrent);
                this.pager.ExportAll += new ExportAllEventHandler(pager_ExportAll);
                <strong>this.pager.ExportPdf += Pager_ExportPdf;</strong>

對于列表的數(shù)據(jù)源,我們可以統(tǒng)一轉(zhuǎn)換為DataTable格式,如下 分析數(shù)據(jù)源的格式進(jìn)行轉(zhuǎn)換。

DataTable sourcetable = null;
            if (this.DataSource is DataView)
            {
                DataView dv = (DataView)AllToExport;//默認(rèn)導(dǎo)出顯示內(nèi)容
                sourcetable = dv.ToTable();
            }
            else if (this.DataSource is DataTable)
            {
                sourcetable = this.DataSource as DataTable;
            }
            else
            {
                sourcetable = ReflectionUtil.CreateTable(this.DataSource);
            }

而對于表格內(nèi)容的中文注釋,我們可以讀取表格里面的頭部信息作為PDF表頭的中文信息,如下所示。

var table = new DataTable();
    for (int i = 0; i < this.gridView1.Columns.Count; i++)
    {
        if (this.gridView1.Columns[i].Visible)
        {
            var column = new DataColumn(this.gridView1.Columns[i].FieldName, typeof(string));
            column.Caption = this.gridView1.Columns[i].Caption;
            table.Columns.Add(column);
        }
    }

而每行的內(nèi)容,可以逐一讀取并寫入其中即可。

for (int i = 0; i < sourcetable.Rows.Count; i++)
    {
        var row = table.NewRow();
        for (int j = 0; j < table.Columns.Count; j++)
        {
            var columnName = table.Columns[j].ColumnName;
            var displayText = this.gridView1.GetRowCellDisplayText(i, columnName);
            row[columnName] = displayText ?? "";
        }
        table.Rows.Add(row);
    }

最后調(diào)用輔助類進(jìn)行導(dǎo)出PDF文檔即可,導(dǎo)出后進(jìn)行打開處理。

var success =<strong> TextSharpHelper.ExportTableToPdf</strong>(table, pdfFile, isLandscape, includeHeader, headerAlignment, headerFontSize, rowFontSize, headerFixHeight);
    if (success)
    {
        Process.Start(pdfFile);
    }

Winform怎么用分頁控件實(shí)現(xiàn)導(dǎo)出PDF文檔功能

導(dǎo)出PDF和前面的效果一樣了。

到此,相信大家對“Winform怎么用分頁控件實(shí)現(xiàn)導(dǎo)出PDF文檔功能”有了更深的了解,不妨來實(shí)際操作一番吧!這里是億速云網(wǎng)站,更多相關(guān)內(nèi)容可以進(jìn)入相關(guān)頻道進(jìn)行查詢,關(guān)注我們,繼續(xù)學(xué)習(xí)!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI