最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

使用C#創(chuàng)建PDF文檔的完整教程(文本、圖片、形狀與表格插入)

 更新時(shí)間:2026年01月01日 11:57:31   作者:大丸子  
在企業(yè)級(jí)應(yīng)用和信息系統(tǒng)中,PDF 一直是最常見(jiàn)、也是最穩(wěn)定的文檔輸出格式之一,因此,在后端代碼中動(dòng)態(tài)生成 PDF 文檔,幾乎是每一個(gè) .NET 項(xiàng)目都會(huì)涉及的需求,本文將圍繞?Free Spire.PDF for .NET,系統(tǒng)地介紹如何在 C# 中創(chuàng)建 PDF 文檔,需要的朋友可以參考下

引言

在企業(yè)級(jí)應(yīng)用和信息系統(tǒng)中,PDF 一直是最常見(jiàn)、也是最穩(wěn)定的文檔輸出格式之一。無(wú)論是財(cái)務(wù)報(bào)表、合同文檔、業(yè)務(wù)統(tǒng)計(jì)報(bào)告,還是系統(tǒng)自動(dòng)生成的通知文件,PDF 都具備版式固定、跨平臺(tái)一致、不可隨意修改等優(yōu)勢(shì)。因此,在后端代碼中動(dòng)態(tài)生成 PDF 文檔,幾乎是每一個(gè) .NET 項(xiàng)目都會(huì)涉及的需求。

相比于依賴(lài) Office 環(huán)境或手工拼接 PDF,使用專(zhuān)業(yè)的 PDF 組件可以顯著降低開(kāi)發(fā)復(fù)雜度。本文將圍繞 Free Spire.PDF for .NET,系統(tǒng)地介紹如何在 C# 中創(chuàng)建 PDF 文檔,并逐步實(shí)現(xiàn)以下常見(jiàn)功能:

從零創(chuàng)建 PDF 頁(yè)面、繪制結(jié)構(gòu)化文本內(nèi)容、插入業(yè)務(wù)相關(guān)圖片、繪制圖形元素,以及生成支持分頁(yè)和樣式控制的復(fù)雜表格。通過(guò)完整示例,你可以快速將這些能力應(yīng)用到實(shí)際項(xiàng)目中。

一、創(chuàng)建 PDF 文檔并繪制結(jié)構(gòu)化文本內(nèi)容

在實(shí)際業(yè)務(wù)中,PDF 的第一頁(yè)通常用于展示標(biāo)題、說(shuō)明性文字或報(bào)告概覽,因此文本排版能力尤為重要。Free Spire.PDF 提供了靈活的文本繪制 API,可以同時(shí)控制字體、顏色、對(duì)齊方式以及行距等樣式。

下面的示例演示了如何創(chuàng)建一個(gè) PDF 文檔,并在頁(yè)面中繪制標(biāo)題與正文說(shuō)明。

using Spire.Pdf;
using Spire.Pdf.Graphics;
using System.Drawing;

namespace PdfGenerationTutorial
{
    class AddText
    {
        static void Main(string[] args)
        {
            PdfDocument doc = new PdfDocument();
            PdfPageBase page = doc.Pages.Add();

            // 報(bào)告標(biāo)題
            PdfTrueTypeFont titleFont = new PdfTrueTypeFont(
                new Font("微軟雅黑", 16f, FontStyle.Bold), true);
            PdfBrush titleBrush = PdfBrushes.DarkSlateBlue;

            page.Canvas.DrawString(
                "2025 年度銷(xiāo)售數(shù)據(jù)分析報(bào)告",
                titleFont,
                titleBrush,
                60,
                40
            );

            // 報(bào)告正文說(shuō)明
            string description =
                "本報(bào)告用于匯總展示公司 2025 年度的核心銷(xiāo)售數(shù)據(jù)," +
                "內(nèi)容涵蓋主要產(chǎn)品的銷(xiāo)售數(shù)量、單價(jià)及總金額統(tǒng)計(jì)。" +
                "通過(guò)系統(tǒng)自動(dòng)生成 PDF 文檔,可以確保數(shù)據(jù)的一致性和可追溯性," +
                "同時(shí)減少人工整理報(bào)表的工作量,適用于內(nèi)部匯報(bào)、管理決策及歸檔場(chǎng)景。";

            PdfTrueTypeFont bodyFont = new PdfTrueTypeFont(
                new Font("宋體", 11f), true);
            PdfBrush bodyBrush = PdfBrushes.Black;

            RectangleF textArea = new RectangleF(
                60,
                90,
                page.Canvas.ClientSize.Width - 120,
                page.Canvas.ClientSize.Height - 160
            );

            PdfStringFormat textFormat = new PdfStringFormat();
            textFormat.Alignment = PdfTextAlignment.Justify;
            textFormat.LineSpacing = 18f;

            page.Canvas.DrawString(
                description,
                bodyFont,
                bodyBrush,
                textArea,
                textFormat
            );

            doc.SaveToFile("Report_Text.pdf");
            doc.Dispose();
        }
    }
}

運(yùn)行該代碼,將生成如下 PDF 文檔:

在這個(gè)示例中,標(biāo)題與正文使用了不同的字體大小和顏色,并通過(guò) RectangleF 明確限定了文本繪制區(qū)域。這樣做的好處是,無(wú)論文本內(nèi)容長(zhǎng)度如何變化,布局都能保持穩(wěn)定,同時(shí)自動(dòng)處理?yè)Q行問(wèn)題。

二、在 PDF 中插入圖片并作為頁(yè)面視覺(jué)元素或水印

除了文本內(nèi)容,圖片在 PDF 中同樣扮演著重要角色。例如企業(yè) Logo、產(chǎn)品示意圖、審批章或背景水印,都會(huì)頻繁出現(xiàn)在正式文檔中。

下面的代碼展示了三種常見(jiàn)圖片使用方式:普通插入、縮放展示以及半透明水印。

using Spire.Pdf;
using Spire.Pdf.Graphics;
using System.Drawing;

namespace PdfGenerationTutorial
{
    class AddImage
    {
        static void Main(string[] args)
        {
            PdfDocument doc = new PdfDocument();
            PdfPageBase page = doc.Pages.Add();

            Image image = Image.FromFile("company_logo.png");
            PdfImage pdfImage = PdfImage.FromImage(image);

            // 左上角插入公司 Logo
            page.Canvas.DrawImage(pdfImage, 50, 50, 120, 60);

            // 頁(yè)面中部插入示意圖
            RectangleF imageArea = new RectangleF(50, 150, 220, 140);
            page.Canvas.DrawImage(pdfImage, imageArea);

            // 頁(yè)面居中水印
            float pageWidth = page.Canvas.ClientSize.Width;
            float pageHeight = page.Canvas.ClientSize.Height;

            float wmWidth = pdfImage.Width * 0.4f;
            float wmHeight = pdfImage.Height * 0.4f;
            float x = (pageWidth - wmWidth) / 2;
            float y = (pageHeight - wmHeight) / 2;

            page.Canvas.Save();
            page.Canvas.SetTransparency(0.25f, 0.25f, PdfBlendMode.Multiply);
            page.Canvas.DrawImage(pdfImage, x, y, wmWidth, wmHeight);
            page.Canvas.Restore();

            doc.SaveToFile("Report_Image.pdf");
            doc.Dispose();
        }
    }
}

生成文檔示例:

通過(guò) SetTransparency 方法,可以輕松實(shí)現(xiàn) PDF 水印效果。這在合同、報(bào)價(jià)單和內(nèi)部資料中非常常見(jiàn),既能體現(xiàn)品牌,又不會(huì)影響正文內(nèi)容的可讀性。

三、繪制圖形元素用于結(jié)構(gòu)劃分和視覺(jué)強(qiáng)調(diào)

在報(bào)表類(lèi) PDF 中,線條、矩形或簡(jiǎn)單圖形常用于分隔內(nèi)容區(qū)域,增強(qiáng)頁(yè)面結(jié)構(gòu)感。Free Spire.PDF 提供了與 GDI+ 類(lèi)似的繪圖接口,使用起來(lái)非常直觀。

using Spire.Pdf;
using Spire.Pdf.Graphics;
using System.Drawing;

namespace PdfGenerationTutorial
{
    class Shapes
    {
        static void Main(string[] args)
        {
            PdfDocument doc = new PdfDocument();
            PdfPageBase page = doc.Pages.Add();

            // 分割線
            PdfPen linePen = new PdfPen(Color.DarkGray, 1.5f);
            page.Canvas.DrawLine(linePen, 50, 80, 500, 80);

            // 信息塊背景
            PdfPen rectPen = new PdfPen(Color.SteelBlue, 1f);
            PdfBrush rectBrush = new PdfSolidBrush(Color.AliceBlue);
            page.Canvas.DrawRectangle(rectPen, rectBrush, 50, 100, 200, 90);

            // 高亮標(biāo)識(shí)
            PdfPen circlePen = new PdfPen(Color.Orange, 2f);
            PdfBrush circleBrush = new PdfSolidBrush(Color.Moccasin);
            page.Canvas.DrawEllipse(circlePen, circleBrush, 300, 120, 60, 60);

            doc.SaveToFile("Report_Shapes.pdf");
            doc.Close();
        }
    }
}

運(yùn)行該代碼,將生成如下 PDF 文檔:

這些基礎(chǔ)圖形雖然簡(jiǎn)單,但在實(shí)際報(bào)表中可以用于突出重點(diǎn)數(shù)據(jù)區(qū)域或增強(qiáng)整體排版層次。

四、生成支持分頁(yè)和樣式控制的業(yè)務(wù)數(shù)據(jù)表格

PDF 表格是業(yè)務(wù)系統(tǒng)中最常見(jiàn)、也是最復(fù)雜的輸出形式之一。下面的示例模擬了一個(gè)“產(chǎn)品銷(xiāo)售明細(xì)表”,并演示如何設(shè)置表頭樣式、隔行背景以及跨頁(yè)重復(fù)表頭。

using Spire.Pdf;
using Spire.Pdf.Graphics;
using Spire.Pdf.Tables;
using System.Data;
using System.Drawing;

namespace PdfGenerationTutorial
{
    class DataTableExample
    {
        static void Main(string[] args)
        {
            PdfDocument doc = new PdfDocument();
            PdfPageBase page = doc.Pages.Add();

            DataTable tableData = new DataTable();
            tableData.Columns.Add("編號(hào)");
            tableData.Columns.Add("產(chǎn)品名稱(chēng)");
            tableData.Columns.Add("單價(jià)(元)");
            tableData.Columns.Add("銷(xiāo)量");
            tableData.Columns.Add("銷(xiāo)售額(元)");

            for (int i = 0; i < 25; i++)
            {
                decimal price = 49.9m + i;
                int qty = i + 2;
                tableData.Rows.Add(
                    i + 1,
                    $"智能設(shè)備型號(hào)-{i + 1}",
                    price,
                    qty,
                    price * qty
                );
            }

            PdfTable table = new PdfTable();
            table.DataSource = tableData;

            table.Style.BorderPen = new PdfPen(Color.Gray, 0.5f);
            table.Style.DefaultStyle.Font =
                new PdfTrueTypeFont(new Font("微軟雅黑", 10f), true);
            table.Style.DefaultStyle.StringFormat =
                new PdfStringFormat(PdfTextAlignment.Left, PdfVerticalAlignment.Middle);

            table.Style.HeaderSource = PdfHeaderSource.Rows;
            table.Style.HeaderRowCount = 1;
            table.Style.ShowHeader = true;
            table.Style.HeaderStyle.BackgroundBrush =
                new PdfSolidBrush(Color.LightSkyBlue);
            table.Style.HeaderStyle.Font =
                new PdfTrueTypeFont(new Font("微軟雅黑", 11f, FontStyle.Bold), true);
            table.Style.RepeatHeader = true;

            table.Style.AlternateStyle = new PdfCellStyle();
            table.Style.AlternateStyle.BackgroundBrush =
                new PdfSolidBrush(Color.WhiteSmoke);
            table.Style.AlternateStyle.StringFormat =
                new PdfStringFormat(PdfTextAlignment.Left, PdfVerticalAlignment.Middle);

            table.Columns[0].Width = 50;
            table.Columns[1].Width = 160;
            table.Columns[2].Width = 90;
            table.Columns[3].Width = 70;
            table.Columns[4].Width = 100;

            table.Draw(page, new PointF(40, 50));

            doc.SaveToFile("Sales_Table.pdf");
            doc.Close();
        }
    }
}

生成的 PDF 文檔如下:

在這個(gè)場(chǎng)景中,即使數(shù)據(jù)行數(shù)超過(guò)一頁(yè),表格也會(huì)自動(dòng)分頁(yè),并在每一頁(yè)頂部重復(fù)顯示表頭,非常適合正式業(yè)務(wù)報(bào)表的生成需求。

關(guān)鍵類(lèi)、屬性與方法總結(jié)

類(lèi) / 屬性 / 方法說(shuō)明
PdfDocument表示一個(gè) PDF 文檔對(duì)象,所有頁(yè)面和內(nèi)容都基于該對(duì)象創(chuàng)建
PdfDocument.Pages.Add()向文檔中添加一個(gè)新的 PDF 頁(yè)面
PdfPageBase表示 PDF 中的單個(gè)頁(yè)面,所有繪制操作都在此進(jìn)行
page.Canvas頁(yè)面畫(huà)布對(duì)象,用于繪制文本、圖片、圖形等元素
PdfTrueTypeFont使用系統(tǒng)字體創(chuàng)建 PDF 字體,支持中文顯示
PdfBrush / PdfPen分別用于填充顏色和描邊繪制
Canvas.DrawString()在指定位置或區(qū)域繪制文本內(nèi)容
PdfStringFormat控制文本對(duì)齊方式、行距、段落布局
RectangleF定義文本或圖片的繪制區(qū)域,用于布局控制
PdfImage.FromImage()將 System.Drawing.Image 轉(zhuǎn)換為 PDF 可用圖片
Canvas.DrawImage()在頁(yè)面中繪制圖片,支持縮放和定位
Canvas.SetTransparency()設(shè)置繪制內(nèi)容透明度,常用于水印效果
PdfTable用于創(chuàng)建 PDF 表格并綁定數(shù)據(jù)源
PdfTable.DataSource綁定 DataTable 或其他數(shù)據(jù)集合
PdfTable.Style統(tǒng)一控制表格邊框、字體、背景等樣式
PdfTable.Draw()將表格繪制到指定頁(yè)面位置
PdfDocument.SaveToFile()將 PDF 文檔保存為文件
PdfDocument.Dispose() / Close()釋放資源,結(jié)束文檔操作

總結(jié)

通過(guò)本文的完整示例,可以看到使用 Free Spire.PDF for .NET 在 C# 中創(chuàng)建 PDF 文檔,并不是零散 API 的堆砌,而是一個(gè)可系統(tǒng)化設(shè)計(jì)的文檔生成過(guò)程。從頁(yè)面初始化、內(nèi)容布局,到數(shù)據(jù)驅(qū)動(dòng)的表格輸出,都可以通過(guò)清晰、可維護(hù)的代碼完成。

對(duì)于需要長(zhǎng)期輸出業(yè)務(wù)報(bào)表、系統(tǒng)憑證或歸檔文檔的 .NET 項(xiàng)目而言,這種方式不僅能夠提升開(kāi)發(fā)效率,也有助于保持文檔風(fēng)格的一致性和專(zhuān)業(yè)性。只要合理規(guī)劃頁(yè)面結(jié)構(gòu)和數(shù)據(jù)來(lái)源,就可以將 PDF 生成作為系統(tǒng)中一個(gè)穩(wěn)定、可靠的基礎(chǔ)能力來(lái)使用。

以上就是使用C#創(chuàng)建PDF文檔的完整教程(文本、圖片、形狀與表格插入)的詳細(xì)內(nèi)容,更多關(guān)于C#創(chuàng)建PDF文檔的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

最新評(píng)論

油尖旺区| 沁源县| 巨野县| 上杭县| 桑日县| 广昌县| 克东县| 望城县| 宜兴市| 买车| 德安县| 油尖旺区| 恩平市| 永泰县| 杨浦区| 万州区| 鄯善县| 图木舒克市| 黄冈市| 马公市| 随州市| 南澳县| 永春县| 兴隆县| 改则县| 彭山县| 铜鼓县| 襄樊市| 铜山县| 徐汇区| 岢岚县| 崇州市| 从化市| 广安市| 手游| 册亨县| 上虞市| 宝丰县| 长宁县| 苍山县| 安塞县|