2
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

C# PDFの作成法

Posted at

PDFは、「Portable Document Format」の略で、データを実際に紙に印刷したときの状態を、そのまま保存することができるファイル形式です。今回は Spire.PDFという無料のライブラリを利用して、PDFの作成法を紹介しましょう!

下準備

1.E-iceblueの公式サイトからFree Spire.PDF無料版をダウンロードしてください。

f:id:lendoris:20210512144931p:plain

2.Visual Studioを起動して新規プロジェクトを作成してから、インストールされたファイルにあった相応しいSpire. PDF.dllを参照に追加してください。

(Net 4.0を例としたら、デフォルトパスは“Bin→NET4.0→PDF.dll”というようです。)

f:id:lendoris:20210512144944p:plain

コード

```C# using Spire.Pdf; using Spire.Pdf.Graphics; using System.Drawing;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
//PdfDocument objectを作成します。
PdfDocument document = new PdfDocument();

        //マージンを設定します。
        PdfUnitConvertor unitCvtr = new PdfUnitConvertor();
        PdfMargins margins = new PdfMargins();
        margins.Top = unitCvtr.ConvertUnits(2.54f, PdfGraphicsUnit.Centimeter, PdfGraphicsUnit.Point);
        margins.Bottom = margins.Top;
        margins.Left = unitCvtr.ConvertUnits(3.17f, PdfGraphicsUnit.Centimeter, PdfGraphicsUnit.Point);
        margins.Right = margins.Left;

        //新規ページを追加します。
        PdfPageBase page = document.Pages.Add(PdfPageSize.A4, margins);

        //カスタムのPdfTrueTypeFont、PdfPenインスタンスを作成します。
        PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Ms mincho", 20f), true);
        PdfPen pen = new PdfPen(Color.Black);

        //DrawStringメソッドでテキストを書きます。
        string text = "初めてのPDFです!";
        page.Canvas.DrawString(text, font, pen, 100, 50);

        //保存します・
        document.SaveToFile("PDF作成.pdf");

    }
}

}

<h4><strong>実行結果</strong></h4>
<p><img src="https://cdn-ak.f.st-hatena.com/images/fotolife/l/lendoris/20210512/20210512145023.png" alt="f:id:lendoris:20210512145023p:plain" title="" class="hatena-fotolife" itemprop="image" /></p>
<p> </p>
2
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?