C#_使用PdfSharp來實踐Pdf產生與寫入寫出

 
提到C#中要處理pdf相關的資料
多半會想到iTextSharp這套Library



不過由於iTextSharp採用的是AGPL授權
使用了也有義務要開放原始碼,否則要付費使用。
因此在執行處理到一定量會開始跑出警告



這邊覺得pdf處理第三方Library若不想付費但又要商用
可以改採用PdfSharp
本身採用的是MIT License

至Nuget下載PdfSharp



sourceforge官網釋出的範例與套件包


使用範例

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using PdfSharp;//PageSize
using PdfSharp.Drawing;//XGraphics,XFont需要引入的
using PdfSharp.Pdf;//PdfDocument , PdfPage需要引入的

namespace PdfSharpApp
{
    class Program
    {        
        //http://www.pdfsharp.net/wiki/HelloWorld-sample.ashx
        static void Main(string[] args)
        {
            PdfDocument document = new PdfDocument();
            Console.WriteLine("Start create pdf file");            
            document.Info.Title = "pdf title";
            document.Info.Subject = "pdf Subject";

            //增加新的一頁
            PdfPage page = document.AddPage();
            page.Orientation = PageOrientation.Portrait;
            page.Size = PageSize.A4;

            //以此頁進行畫布初始配置
            XGraphics gfx = XGraphics.FromPdfPage(page);
            //字體與大小指定
            XFont font = new XFont("Arial", 20, XFontStyle.Bold);            
            gfx.DrawString("Hello, World!", 
                            font, XBrushes.Black,new XRect(0, 0, page.Width, page.Height),
                            XStringFormats.Center);
            // Create the root bookmark. You can set the style and the color.
            PdfOutline outline = document.Outlines.Add("Root", page, true, PdfOutlineStyle.Bold, XColors.Red);

            outline.Outlines.Add("Page 1", page, true);

            page = document.AddPage();
            page.Orientation = PageOrientation.Portrait;
            page.Size = PageSize.A0;
            page.Orientation = PageOrientation.Landscape;
            outline.Outlines.Add("Page 2", page, true);
            gfx = XGraphics.FromPdfPage(page);

            XRect rect;
            XPen pen;
            double x = 50, y = 100;
            XFont fontH1 = new XFont("Times", 18, XFontStyle.Bold);
            XFont font2 = new XFont("Times", 12);
            XFont fontItalic = new XFont("Times", 12, XFontStyle.BoldItalic);
            double ls = font2.GetHeight();

            // Draw some text
            gfx.DrawString("Create PDF on the fly with PDFsharp",
                fontH1, XBrushes.Black, x, x);
            gfx.DrawString("With PDFsharp you can use the same code to draw graphic, " +
                "text and images on different targets.", font, XBrushes.Black, x, y);
            y += ls;
            gfx.DrawString("The object used for drawing is the XGraphics object.",
                font, XBrushes.Black, x, y);
            y += 2 * ls;

            // Draw an arc
            pen = new XPen(XColors.Red, 4);
            pen.DashStyle = XDashStyle.Dash;
            gfx.DrawArc(pen, x + 20, y, 100, 60, 150, 120);

            // Draw a star
            XGraphicsState gs = gfx.Save();
            gfx.TranslateTransform(x + 140, y + 30);
            for (int idx = 0; idx < 360; idx += 10)
            {
                gfx.RotateTransform(10);
                gfx.DrawLine(XPens.DarkGreen, 0, 0, 30, 0);
            }
            gfx.Restore(gs);

            // Draw a rounded rectangle
            rect = new XRect(x + 230, y, 100, 60);
            pen = new XPen(XColors.DarkBlue, 2.5);
            XColor color1 = XColor.FromKnownColor((XKnownColor)KnownColor.DarkBlue);
            XColor color2 = XColors.Red;
            XLinearGradientBrush lbrush = new XLinearGradientBrush(rect, color1, color2,
              XLinearGradientMode.Vertical);
            gfx.DrawRoundedRectangle(pen, lbrush, rect, new XSize(10, 10));

            // Draw a pie
            pen = new XPen(XColors.DarkOrange, 1.5);
            pen.DashStyle = XDashStyle.Dot;
            gfx.DrawPie(pen, XBrushes.Blue, x + 360, y, 100, 60, -130, 135);


            // Draw some more text
            y += 60 + 2 * ls;
            gfx.DrawString("With XGraphics you can draw on a PDF page as well as " +
                "on any System.Drawing.Graphics object.", font, XBrushes.Black, x, y);
            y += ls * 1.1;
            gfx.DrawString("Use the same code to", font, XBrushes.Black, x, y);
            x += 10;
            y += ls * 1.1;
            gfx.DrawString("• draw on a newly created PDF page", font, XBrushes.Black, x, y);
            y += ls;
            gfx.DrawString("• draw above or beneath of the content of an existing PDF page",
                font, XBrushes.Black, x, y);
            y += ls;
            gfx.DrawString("• draw in a window", font, XBrushes.Black, x, y);
            y += ls;
            gfx.DrawString("• draw on a printer", font, XBrushes.Black, x, y);
            y += ls;
            gfx.DrawString("• draw in a bitmap image", font, XBrushes.Black, x, y);
            x -= 10;
            y += ls * 1.1;
            gfx.DrawString("You can also import an existing PDF page and use it like " +
                "an image, e.g. draw it on another PDF page.", font, XBrushes.Black, x, y);
            y += ls * 1.1 * 2;
            gfx.DrawString("Imported PDF pages are neither drawn nor printed; create a " +
                "PDF file to see or print them!", fontItalic, XBrushes.Firebrick, x, y);
            y += ls * 1.1;
            gfx.DrawString("Below this text is a PDF form that will be visible when " +
                "viewed or printed with a PDF viewer.", fontItalic, XBrushes.Firebrick, x, y);
            y += ls * 1.1;

            PageSize[] pageSizes = (PageSize[])Enum.GetValues(typeof(PageSize));
            // Create some more pages
            for (int idx = 3; idx <= 6; idx++)
            {
                page = document.AddPage();
                page.Size = pageSizes[idx-1];
                page.Orientation = PageOrientation.Landscape;

                gfx = XGraphics.FromPdfPage(page);

                string text = "Page " + idx;
                gfx.DrawString(text, font, XBrushes.Black, 20, 50, XStringFormats.Default);                

                // Create a sub bookmark
                outline.Outlines.Add(text, page, true);
            }



            //存檔
            string fileName = "Test.pdf";
            document.Save(fileName);

            Console.WriteLine("Finish create pdf file");
            Console.ReadKey();
        }



    }
}




比較常用到的還有浮水印

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using PdfSharp;//PageSize
using PdfSharp.Drawing;//XGraphics,XFont需要引入的
using PdfSharp.Pdf;//PdfDocument , PdfPage需要引入的

namespace PdfSharpApp
{
    class Program
    {        
        //http://www.pdfsharp.net/wiki/HelloWorld-sample.ashx
        static void Main(string[] args)
        {
            PdfDocument document = new PdfDocument();
            Console.WriteLine("Start create pdf file");            
            document.Info.Title = "pdf title";
            document.Info.Subject = "pdf Subject";

            //增加新的一頁
            PdfPage page = document.AddPage();
            page.Orientation = PageOrientation.Portrait;
            page.Size = PageSize.A4;

            //以此頁進行畫布初始配置
            XGraphics gfx = XGraphics.FromPdfPage(page);           

            XRect rect;
            XPen pen;
            double x = 50, y = 100;
            XFont fontH1 = new XFont("Times", 18, XFontStyle.Bold);
            XFont font = new XFont("Times", 12);
            XFont fontItalic = new XFont("Times", 12, XFontStyle.BoldItalic);
            double ls = font.GetHeight();

            // Draw some text
            gfx.DrawString("Create PDF on the fly with PDFsharp",
                fontH1, XBrushes.Black, x, x);
            gfx.DrawString("With PDFsharp you can use the same code to draw graphic, " +
                "text and images on different targets.", font, XBrushes.Black, x, y);
            y += ls;
            gfx.DrawString("The object used for drawing is the XGraphics object.",
                font, XBrushes.Black, x, y);
            y += 2 * ls;

            // Draw an arc
            pen = new XPen(XColors.Red, 4);
            pen.DashStyle = XDashStyle.Dash;
            gfx.DrawArc(pen, x + 20, y, 100, 60, 150, 120);

            // Draw a star
            XGraphicsState gs = gfx.Save();
            gfx.TranslateTransform(x + 140, y + 30);
            for (int idx = 0; idx < 360; idx += 10)
            {
                gfx.RotateTransform(10);
                gfx.DrawLine(XPens.DarkGreen, 0, 0, 30, 0);
            }
            gfx.Restore(gs);

            // Draw a rounded rectangle
            rect = new XRect(x + 230, y, 100, 60);
            pen = new XPen(XColors.DarkBlue, 2.5);
            XColor color1 = XColor.FromKnownColor((XKnownColor)KnownColor.DarkBlue);
            XColor color2 = XColors.Red;
            XLinearGradientBrush lbrush = new XLinearGradientBrush(rect, color1, color2,
              XLinearGradientMode.Vertical);
            gfx.DrawRoundedRectangle(pen, lbrush, rect, new XSize(10, 10));

            // Draw a pie
            pen = new XPen(XColors.DarkOrange, 1.5);
            pen.DashStyle = XDashStyle.Dot;
            gfx.DrawPie(pen, XBrushes.Blue, x + 360, y, 100, 60, -130, 135);


            // Draw some more text
            y += 60 + 2 * ls;
            gfx.DrawString("With XGraphics you can draw on a PDF page as well as " +
                "on any System.Drawing.Graphics object.", font, XBrushes.Black, x, y);
            y += ls * 1.1;
            gfx.DrawString("Use the same code to", font, XBrushes.Black, x, y);
            x += 10;
            y += ls * 1.1;
            gfx.DrawString("• draw on a newly created PDF page", font, XBrushes.Black, x, y);
            y += ls;
            gfx.DrawString("• draw above or beneath of the content of an existing PDF page",
                font, XBrushes.Black, x, y);
            y += ls;
            gfx.DrawString("• draw in a window", font, XBrushes.Black, x, y);
            y += ls;
            gfx.DrawString("• draw on a printer", font, XBrushes.Black, x, y);
            y += ls;
            gfx.DrawString("• draw in a bitmap image", font, XBrushes.Black, x, y);
            x -= 10;
            y += ls * 1.1;
            gfx.DrawString("You can also import an existing PDF page and use it like " +
                "an image, e.g. draw it on another PDF page.", font, XBrushes.Black, x, y);
            y += ls * 1.1 * 2;
            gfx.DrawString("Imported PDF pages are neither drawn nor printed; create a " +
                "PDF file to see or print them!", fontItalic, XBrushes.Firebrick, x, y);
            y += ls * 1.1;
            gfx.DrawString("Below this text is a PDF form that will be visible when " +
                "viewed or printed with a PDF viewer.", fontItalic, XBrushes.Firebrick, x, y);

            // Variation 1: Draw a watermark as a text string.
            XFont font2 = new XFont("Times", 80);
            string watermark = "WaterMark Test";
            // Get an XGraphics object for drawing beneath the existing content.
            //gfx = XGraphics.FromPdfPage(page, XGraphicsPdfPageOptions.Prepend);

            // Get the size (in points) of the text.
            var size = gfx.MeasureString(watermark, font2);

            // Define a rotation transformation at the center of the page.
            gfx.TranslateTransform(page.Width / 2, page.Height / 2);
            gfx.RotateTransform(-Math.Atan(page.Height / page.Width) * 180 / Math.PI);
            gfx.TranslateTransform(-page.Width / 2, -page.Height / 2);

            // Create a string format.
            var format = new XStringFormat();
            format.Alignment = XStringAlignment.Near;
            format.LineAlignment = XLineAlignment.Near;

            // Create a dimmed red brush.
            XBrush brush = new XSolidBrush(XColor.FromArgb(128, 255, 0, 0));

            // Draw the string.
            gfx.DrawString(watermark, font2, brush,
                new XPoint((page.Width - size.Width) / 2, (page.Height - size.Height) / 2),
                format);


            //存檔
            string fileName = "Test.pdf";
            document.Save(fileName);

            Console.WriteLine("Finish create pdf file");
            Console.ReadKey();
        }



    }
}






還有多頁pdf的merge

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
//Combine Documents
//http://pdfsharp.com/PDFsharp/index.php?option=com_content&task=view&id=34&Itemid=45
//Concatenate Documents
//http://pdfsharp.com/PDFsharp/index.php%3Foption%3Dcom_content%26task%3Dview%26id%3D52%26Itemid%3D60
/// <summary>
/// 合併多個pdf檔案
/// </summary>
/// <param name="lsPdfFile"></param>
/// <param name="mergedFile"></param>
public static void MergePdfFiles_PdfSharp(List<byte[]> lsPdfFile, string mergedFile)
{
    try
    {
        PdfSharp.Pdf.PdfDocument pdfMergedDocument = new PdfSharp.Pdf.PdfDocument();

        for (int i = 0; i < lsPdfFile.Count; i++)
        {
            Stream stream = new MemoryStream(lsPdfFile[i]);
            PdfSharp.Pdf.PdfDocument inputDocument = PdfSharp.Pdf.IO.PdfReader.Open(stream,PdfSharp.Pdf.IO.PdfDocumentOpenMode.Import);
            pdfMergedDocument.Version = inputDocument.Version;
            foreach (PdfSharp.Pdf.PdfPage page in inputDocument.Pages)
            {
                pdfMergedDocument.AddPage(page);
            }
        }
        pdfMergedDocument.Save(mergedFile);
    }
    catch (Exception ex)
    {
        throw;
    }
}










Ref:



Home of PDFsharp and MigraDoc Foundation

PDFsharp and MigraDoc Wiki

使用PDFsharp產生PDF檔案

C# 利用PdfSharp生成Pdf檔案

留言

這個網誌中的熱門文章

何謂淨重(Net Weight)、皮重(Tare Weight)與毛重(Gross Weight)

Architecture(架構) 和 Framework(框架) 有何不同?_軟體設計前的事前規劃的藍圖概念

經得起原始碼資安弱點掃描的程式設計習慣培養(五)_Missing HSTS Header