溫馨提示×

溫馨提示×

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

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

C#如何利用PdfSharp生成Pdf文件

發(fā)布時間:2021-04-02 11:31:58 來源:億速云 閱讀:1143 作者:小新 欄目:開發(fā)技術(shù)

這篇文章給大家分享的是有關(guān)C#如何利用PdfSharp生成Pdf文件的內(nèi)容。小編覺得挺實(shí)用的,因此分享給大家做個參考,一起跟隨小編過來看看吧。

PdfSharp一款開源的用于創(chuàng)建,操作PDF文檔的.Net類庫。

PdfSharp下載

在本例中,主要通過NuGet包管理器進(jìn)行下載安裝,目前PdfSharp版本為v1.5.0.5147,如下所示:

C#如何利用PdfSharp生成Pdf文件

涉及知識點(diǎn)

在生成PDF文檔過程中,主要知識點(diǎn)如下:

  1. PdfDocument : 表示一個PDF文檔對象,調(diào)用save方法保存文檔到指定路徑。

  2. PdfPage : 表示PDF文檔中的一頁。

  3. XGraphics:表示頁面上的繪制對象,所有的頁面內(nèi)容,都可通過此對象繪制。如:DrawString繪制文本內(nèi)容,DrawLine繪制直線等。

  4. XFont:繪制文本的字體,字體名稱只能取C:\Windows\Fonts目錄下的ttf字體文件,不能是ttc格式的字體。

  5. XTextFormatter:表示一個簡單的文本字體格式,如識別文本的換行符而實(shí)現(xiàn)自動換行等內(nèi)容。

文檔示例圖

在本例中,主要是將頁面內(nèi)容寫入PDF文件中,頁面如下所示:

C#如何利用PdfSharp生成Pdf文件

生成的PDF文件,如下所示:

C#如何利用PdfSharp生成Pdf文件

核心代碼

在本例中,核心代碼主要包括如下幾個部分:

  • 創(chuàng)建文檔

  • 繪制文本

  • 繪制直線

  • 設(shè)置紙張大小,

  • 設(shè)置邊界

  • 文本的自動換行

具體代碼,如下所示:

/// <summary>
    /// 生成Pdf
    /// </summary>
    /// <param name="filePath"></param>
    /// <param name="bo"></param>
    /// <returns></returns>
    public bool GeneratePdf(string filePath, PdfBo bo) {
      int margin_left_right = 30;//左右邊距
      int margin_top_bottom = 30;//上下邊距
      //1. 定義文檔對象
      PdfDocument document = new PdfDocument();
      //2. 新增一頁
      PdfPage page = document.AddPage();
      // 設(shè)置紙張大小
      page.Size = PageSize.A4;
      //3. 創(chuàng)建一個繪圖對象
      XGraphics gfx = XGraphics.FromPdfPage(page);
      XFont font = new XFont("華文宋體", 40, XFontStyle.Bold);
      //定制化內(nèi)容開始
      int cur_x = 0 + margin_left_right;
      int cur_y = 0 + margin_top_bottom;
      //標(biāo)題1
      gfx.DrawString(bo.Head1, font, XBrushes.Red, new XRect(cur_x, cur_y, page.Width-2*cur_x, 80), XStringFormats.Center);
      //序號
      font = new XFont("華文宋體", 12, XFontStyle.Regular);
      cur_y = cur_y + 80;
      gfx.DrawString(bo.No, font, XBrushes.Black, new XRect(cur_x, cur_y, 100, 20), XStringFormats.CenterLeft);
      //密級
      cur_x = cur_x + 200;
      gfx.DrawString(string.Format("密級[{0}]",bo.Private), font, XBrushes.Black, new XRect(cur_x, cur_y, 100, 20), XStringFormats.CenterLeft);
      //緩級
      cur_x = cur_x + 100;
      gfx.DrawString(string.Format("緩級[{0}]", bo.Speed), font, XBrushes.Black, new XRect(cur_x, cur_y, 100, 20), XStringFormats.CenterLeft);
      //簽發(fā)人
      cur_x = cur_x + 100;
      gfx.DrawString(string.Format("簽發(fā)人:{0}", bo.Person), font, XBrushes.Black, new XRect(cur_x, cur_y, 100, 20), XStringFormats.CenterLeft);
      //一條橫線
      cur_x = 0 + margin_left_right;
      cur_y = cur_y + 20;
      XPen pen = new XPen(XColor.FromKnownColor(XKnownColor.Black), 1);
      gfx.DrawLine(pen, cur_x, cur_y, page.Width-cur_x, cur_y+2);
      //標(biāo)題2
      font = new XFont("華文宋體", 20, XFontStyle.Regular);
      cur_y = cur_y + 10;
      gfx.DrawString(bo.Head2, font, XBrushes.Black, new XRect(cur_x, cur_y, page.Width-2*cur_x, 40), XStringFormats.Center);
      //抬頭
      font = new XFont("華文宋體", 15, XFontStyle.Bold);
      cur_y = cur_y + 40;
      gfx.DrawString(bo.Title, font, XBrushes.Black, new XRect(cur_x, cur_y, page.Width, 40), XStringFormats.CenterLeft);
      //正文 ,自動換行
      cur_y = cur_y + 40;
      XTextFormatter tf = new XTextFormatter(gfx);
      font = new XFont("華文宋體", 12, XFontStyle.Regular);

      //測量當(dāng)前內(nèi)容下,一行可以多少個漢字
      int cnt = 0;
      int height = 0;
      for (int i = 0; i < bo.Content.Length; i++) {
        XSize xsize=gfx.MeasureString(bo.Content.Substring(0,i+1), font, XStringFormats.TopLeft);
        double width = xsize.Width;
        if (width >= page.Width - 2 * cur_x) {
          cnt = i; //表示一行可以放多少個漢字。
          height =(int) xsize.Height;
          break;
        }
      }
      cnt = cnt > 0 ? cnt : bo.Content.Length;//每一行多少漢字
      string[] arrContent = bo.Content.Split('\n');
      string new_content = "";
      int total_lines = 0;
      foreach (string content in arrContent) {
        if (content.Length <= cnt)
        {
          new_content+=string.Format("{0}\n",content);
          total_lines++;
        }
        else {
          string tmpContent = content;
          int lines = content.Length / cnt + 1;
          for (int j = 0; j < lines; j++) {
            tmpContent = tmpContent.Insert(j * cnt, "\n");
            total_lines++;
          }
          new_content += string.Format("{0}\n", tmpContent);
        }
      }
      int num = new_content.Length - new_content.Replace("\r", "").Length;
      //計算矩形
      XRect rect = new XRect(cur_x, cur_y, page.Width - 2 * cur_x, (total_lines+num)*(height+2));
      tf.DrawString(new_content, font, XBrushes.Black, rect, XStringFormats.TopLeft);
      //主題詞
      cur_y = cur_y + (total_lines + num) * (height + 2) + 20;
      font = new XFont("華文宋體", 12, XFontStyle.Bold);
      gfx.DrawString(string.Format("主題詞:{0}",bo.Keyword), font, XBrushes.Black, new XRect(cur_x, cur_y, page.Width, 40), XStringFormats.CenterLeft);
      //再加一條橫線
      cur_y = cur_y + 40;
      gfx.DrawLine(pen, cur_x, cur_y, page.Width - cur_x, cur_y + 2);
      cur_y = cur_y + 2;
      font = new XFont("華文宋體", 10, XFontStyle.Regular);
      gfx.DrawString(string.Format("{0}{1}",bo.Company, bo.Dept), font, XBrushes.Black, new XRect(cur_x, cur_y, page.Width-2*cur_x, 40), XStringFormats.CenterLeft);
      gfx.DrawString(DateTime.Now.ToString("yyyy 年 MM 月 dd 日 印發(fā)"), font, XBrushes.Black, new XRect(cur_x, cur_y, page.Width-2*cur_x, 40), XStringFormats.CenterRight);
      //水印開始
      font = new XFont("華文宋體", 20, XFontStyle.BoldItalic);
      // 計算長度
      var size = gfx.MeasureString(bo.Watermark, font);

      // 定義旋轉(zhuǎn)中心
      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);

      // 字符樣式
      var format = new XStringFormat();
      format.Alignment = XStringAlignment.Near;
      format.LineAlignment = XLineAlignment.Near;

      //畫刷
      XBrush brush = new XSolidBrush(XColor.FromArgb(128, 255, 0, 0));
      for (int i = 0; i < 3; i++) {
        gfx.DrawString(bo.Watermark, font, brush,
        new XPoint((page.Width - size.Width) / (1.5+i*0.5), (page.Height - size.Height) / (1.5 + i * 0.5)),
        format);
      }
      //水印結(jié)束
      //6. 保存文檔
      document.Save(filePath);
      return true;
    }

感謝各位的閱讀!關(guān)于“C#如何利用PdfSharp生成Pdf文件”這篇文章就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,讓大家可以學(xué)到更多知識,如果覺得文章不錯,可以把它分享出去讓更多的人看到吧!

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

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

AI