透かしなしで本番環境でテストしてください。
必要な場所で動作します。
30日間、完全に機能する製品をご利用いただけます。
数分で稼働させることができます。
製品トライアル期間中にサポートエンジニアリングチームへの完全アクセス
C#のPDF生成機能は、レポート作成から請求システムまで、多くの現代的なアプリケーションにとって重要です。 この記事では、PDFファイルをC#を使用して生成するための6つの人気のある方法を探ります。IronPDFのようなコードベースのライブラリや、オンラインAPIおよびツールを紹介します。 ウェブアプリでPDFファイルを動的に生成する必要がある場合や、既存のドキュメントからPDFファイルを作成するだけの場合でも、これらのツールが対応しています。
IronPDF は、高品質なHTMLからPDFファイルへの変換を必要とする開発者向けに設計されたプレミアムな.NET PDFライブラリです。 IronPDFは、Chromiumベースのレンダリングエンジンを使用して正確な変換を実現し、HTMLページやウェブベースのレポートをC#でPDFファイルに変換したいウェブアプリケーションに最適な選択肢です。 そのツールは、既存のPDFドキュメントの堅牢な処理で知られ、PDFの編集、結合、または分割の機能を提供します。
IronPDFは、NuGetパッケージマネージャーを通じてC#プロジェクトに簡単に統合され、わずか数行のコードでPDFドキュメントの生成を開始できます。 それは動的なHTMLコンテンツとサーバー生成のPDFファイル出力の両方に対応した多用途ツールです。
using IronPdf;
class Program
{
static void Main()
{
string html = "<h1>Hello, World!</h1><p>This PDF is generated from HTML.</p>";
ChromePdfRenderer renderer = new ChromePdfRenderer(); // Create an instance of ChromePdfRenderer
PdfDocument pdf = renderer.RenderHtmlAsPdf(html); // Render the HTML as a PDF document
pdf.SaveAs("Generated.pdf"); // Save the PDF to a specified file
}
}
using IronPdf;
class Program
{
static void Main()
{
string html = "<h1>Hello, World!</h1><p>This PDF is generated from HTML.</p>";
ChromePdfRenderer renderer = new ChromePdfRenderer(); // Create an instance of ChromePdfRenderer
PdfDocument pdf = renderer.RenderHtmlAsPdf(html); // Render the HTML as a PDF document
pdf.SaveAs("Generated.pdf"); // Save the PDF to a specified file
}
}
Imports IronPdf
Friend Class Program
Shared Sub Main()
Dim html As String = "<h1>Hello, World!</h1><p>This PDF is generated from HTML.</p>"
Dim renderer As New ChromePdfRenderer() ' Create an instance of ChromePdfRenderer
Dim pdf As PdfDocument = renderer.RenderHtmlAsPdf(html) ' Render the HTML as a PDF document
pdf.SaveAs("Generated.pdf") ' Save the PDF to a specified file
End Sub
End Class
Namespace Import: using IronPdf; は、クラスやメソッドにアクセスするためにIronPDFライブラリをインポートします。
HTML文字列: 変数HTMLには、PDFに変換したいHTMLコンテンツが含まれています。
レンダラーインスタンス: new ChromePdfRenderer(); は、HTMLコンテンツをPDF形式にレンダリングするためのメソッドを提供するHtmlToPdfクラスのインスタンスを作成します。
PDF のレンダー: PdfDocument PDF = renderer.RenderHtmlAsPdf(html); は、HTML 文字列を PDF ドキュメントに変換します。
iTextSharpは、PDFファイルの作成と編集に幅広い機能を提供する、実績のある.NET PDFライブラリです。 これは、文書をカスタマイズし、セキュリティを確保する必要がある金融や法務などの業界で広く使用されています。 iTextSharpは、PDFファイルを一から作成し、フォームに入力し、PDFファイルを変更することを可能にし、ドキュメントの内容に広範な制御を提供します。 これは、請求書や契約書のように、正確なレイアウトと動的データを備えたPDFファイルを生成する必要があるエンタープライズアプリケーションに特に役立ちます。
using System;
using System.Collections.Generic;
using System.Data.Entity.Core.Mapping;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.tool.xml;
using Voodoo;
namespace Helpers
{
public class PdfGenerator
{
public static Byte[] GeneratePdfFromFragment(string htmlFragment)
{
var html = string.Format(@"
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en'>
<head>
<style type='text/css'>
table,td {{border: 1px solid black;}}
div {{ white-space: nowrap; padding: 2px;}}
table{{ border-collapse: collapse; width: 100%; empty-cells: show;}}
body table {{font-size: 50%;}}
th {{width:500px; height: 28px;}}
td {{width:300px; height: 28px;}}
</style>
</head><body>{0}</body></html>", htmlFragment);
return generate(html);
}
public static Byte[] GeneratePdfFromPage(string htmlPage)
{
return generate(htmlPage);
}
private static Byte[] generate (string html)
{
using (var memoryStream = new MemoryStream())
{
var pdfDocument = new Document(PageSize.LETTER);
var pdfWriter = PdfWriter.GetInstance(pdfDocument, memoryStream);
pdfDocument.Open();
using (var fw = new StringReader(html))
{
XMLWorkerHelper.GetInstance().ParseXHtml(pdfWriter, pdfDocument, fw);
pdfDocument.Close();
fw.Close();
}
return memoryStream.ToArray();
}
}
}
}
using System;
using System.Collections.Generic;
using System.Data.Entity.Core.Mapping;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.tool.xml;
using Voodoo;
namespace Helpers
{
public class PdfGenerator
{
public static Byte[] GeneratePdfFromFragment(string htmlFragment)
{
var html = string.Format(@"
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en'>
<head>
<style type='text/css'>
table,td {{border: 1px solid black;}}
div {{ white-space: nowrap; padding: 2px;}}
table{{ border-collapse: collapse; width: 100%; empty-cells: show;}}
body table {{font-size: 50%;}}
th {{width:500px; height: 28px;}}
td {{width:300px; height: 28px;}}
</style>
</head><body>{0}</body></html>", htmlFragment);
return generate(html);
}
public static Byte[] GeneratePdfFromPage(string htmlPage)
{
return generate(htmlPage);
}
private static Byte[] generate (string html)
{
using (var memoryStream = new MemoryStream())
{
var pdfDocument = new Document(PageSize.LETTER);
var pdfWriter = PdfWriter.GetInstance(pdfDocument, memoryStream);
pdfDocument.Open();
using (var fw = new StringReader(html))
{
XMLWorkerHelper.GetInstance().ParseXHtml(pdfWriter, pdfDocument, fw);
pdfDocument.Close();
fw.Close();
}
return memoryStream.ToArray();
}
}
}
}
Imports System
Imports System.Collections.Generic
Imports System.Data.Entity.Core.Mapping
Imports System.IO
Imports System.Linq
Imports System.Text
Imports System.Threading.Tasks
Imports iTextSharp.text
Imports iTextSharp.text.pdf
Imports iTextSharp.tool.xml
Imports Voodoo
Namespace Helpers
Public Class PdfGenerator
Public Shared Function GeneratePdfFromFragment(ByVal htmlFragment As String) As Byte()
Dim html = String.Format("
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en'>
<head>
<style type='text/css'>
table,td {{border: 1px solid black;}}
div {{ white-space: nowrap; padding: 2px;}}
table{{ border-collapse: collapse; width: 100%; empty-cells: show;}}
body table {{font-size: 50%;}}
th {{width:500px; height: 28px;}}
td {{width:300px; height: 28px;}}
</style>
</head><body>{0}</body></html>", htmlFragment)
Return generate(html)
End Function
Public Shared Function GeneratePdfFromPage(ByVal htmlPage As String) As Byte()
Return generate(htmlPage)
End Function
Private Shared Function generate(ByVal html As String) As Byte()
Using memoryStream As New MemoryStream()
Dim pdfDocument = New Document(PageSize.LETTER)
Dim pdfWriter = PdfWriter.GetInstance(pdfDocument, memoryStream)
pdfDocument.Open()
Using fw = New StringReader(html)
XMLWorkerHelper.GetInstance().ParseXHtml(pdfWriter, pdfDocument, fw)
pdfDocument.Close()
fw.Close()
End Using
Return memoryStream.ToArray()
End Using
End Function
End Class
End Namespace
GeneratePdfFromFragment: HTMLフラグメント(部分的なHTMLドキュメントのようなもの)を受け取り、それをベーシックなと
テンプレートでラッピングして完全なHTML構造に変換します。 それから、内部のgenerateメソッドを呼び出します。GeneratePdfFromPage: 完全なHTMLページを受け取り、直接生成メソッドを呼び出します。
generate: このメソッドはHTMLをPDFに変換します。
それは、メモリ内に生成されたPDFを保持するためのMemoryStreamを初期化します。
4.
PDFSharpは、基本的なPDF作成タスクに最適な、軽量でオープンソースの.NET PDFライブラリです。 アプリケーションがテキスト、画像、またはテーブルを追加するような単純な操作のみを必要とする場合、PdfSharpはC#でPDF文書を生成するための使いやすいオプションです。 高度な機能であるHTMLからPDFへの変換は欠けていますが、C#で小規模から中規模のPDFファイルを生成する際のシンプルさが際立っています。
using PdfSharp.Pdf;
using PdfSharp.Drawing;
class Program
{
static void Main()
{
// Create a new PDF document
PdfDocument document = new PdfDocument();
document.Info.Title = "Created with PdfSharp";
// Add a page to the document
PdfPage page = document.AddPage();
// Create an XGraphics object to draw on the page
XGraphics gfx = XGraphics.FromPdfPage(page);
// Set a font to use for drawing text
XFont font = new XFont("Verdana", 20, XFontStyle.Bold);
// Draw the text on the PDF page
gfx.DrawString("Hello, World!", font, XBrushes.Black,
new XRect(0, 0, page.Width, page.Height), XStringFormats.Center);
// Save the document to disk
document.Save("Generated.pdf");
}
}
using PdfSharp.Pdf;
using PdfSharp.Drawing;
class Program
{
static void Main()
{
// Create a new PDF document
PdfDocument document = new PdfDocument();
document.Info.Title = "Created with PdfSharp";
// Add a page to the document
PdfPage page = document.AddPage();
// Create an XGraphics object to draw on the page
XGraphics gfx = XGraphics.FromPdfPage(page);
// Set a font to use for drawing text
XFont font = new XFont("Verdana", 20, XFontStyle.Bold);
// Draw the text on the PDF page
gfx.DrawString("Hello, World!", font, XBrushes.Black,
new XRect(0, 0, page.Width, page.Height), XStringFormats.Center);
// Save the document to disk
document.Save("Generated.pdf");
}
}
Imports PdfSharp.Pdf
Imports PdfSharp.Drawing
Friend Class Program
Shared Sub Main()
' Create a new PDF document
Dim document As New PdfDocument()
document.Info.Title = "Created with PdfSharp"
' Add a page to the document
Dim page As PdfPage = document.AddPage()
' Create an XGraphics object to draw on the page
Dim gfx As XGraphics = XGraphics.FromPdfPage(page)
' Set a font to use for drawing text
Dim font As New XFont("Verdana", 20, XFontStyle.Bold)
' Draw the text on the PDF page
gfx.DrawString("Hello, World!", font, XBrushes.Black, New XRect(0, 0, page.Width, page.Height), XStringFormats.Center)
' Save the document to disk
document.Save("Generated.pdf")
End Sub
End Class
Syncfusion PDF Library は、幅広いアプリケーションでPDFを操作する必要がある企業向けに設計された高性能で包括的なツールです。 これは、さまざまな形式やプラットフォームに対応したライブラリを提供する、より広範なSyncfusionスイートの一部です。 PDFライブラリは、単純なドキュメント作成を超えてフォームの記入、デジタル署名、ドキュメントのセキュリティを含む詳細な操作を可能にする豊富な機能セットのために際立っています。
using Syncfusion.Pdf;
using Syncfusion.Pdf.Parsing;
using Syncfusion.Pdf.Graphics;
using Syncfusion.Pdf.Grid;
class Program
{
static void Main()
{
//Create a new PDF document.
PdfDocument document = new PdfDocument();
//Add a page to the document.
PdfPage page = document.Pages.Add();
//Create PDF graphics for the page.
PdfGraphics graphics = page.Graphics;
//Set the standard font.
PdfFont font = new PdfStandardFont(PdfFontFamily.Helvetica, 20);
//Draw the text.
graphics.DrawString("Hello World!!!", font, PdfBrushes.Black, new PointF(0, 0));
//Save the document.
document.Save("Output.pdf");
//Close the document.
document.Close(true);
}
}
using Syncfusion.Pdf;
using Syncfusion.Pdf.Parsing;
using Syncfusion.Pdf.Graphics;
using Syncfusion.Pdf.Grid;
class Program
{
static void Main()
{
//Create a new PDF document.
PdfDocument document = new PdfDocument();
//Add a page to the document.
PdfPage page = document.Pages.Add();
//Create PDF graphics for the page.
PdfGraphics graphics = page.Graphics;
//Set the standard font.
PdfFont font = new PdfStandardFont(PdfFontFamily.Helvetica, 20);
//Draw the text.
graphics.DrawString("Hello World!!!", font, PdfBrushes.Black, new PointF(0, 0));
//Save the document.
document.Save("Output.pdf");
//Close the document.
document.Close(true);
}
}
Imports Syncfusion.Pdf
Imports Syncfusion.Pdf.Parsing
Imports Syncfusion.Pdf.Graphics
Imports Syncfusion.Pdf.Grid
Friend Class Program
Shared Sub Main()
'Create a new PDF document.
Dim document As New PdfDocument()
'Add a page to the document.
Dim page As PdfPage = document.Pages.Add()
'Create PDF graphics for the page.
Dim graphics As PdfGraphics = page.Graphics
'Set the standard font.
Dim font As PdfFont = New PdfStandardFont(PdfFontFamily.Helvetica, 20)
'Draw the text.
graphics.DrawString("Hello World!!!", font, PdfBrushes.Black, New PointF(0, 0))
'Save the document.
document.Save("Output.pdf")
'Close the document.
document.Close(True)
End Sub
End Class
PDFShiftはHTMLをPDFファイルに変換するために設計されたクラウドベースのサービスです。 それは、APIを介してC#アプリケーションとスムーズに統合し、動的に生成されたHTMLウェブページをプロフェッショナル品質のPDFに変換できるようにします。 PDFShiftは、請求書やレポートなどのHTMLコンテンツからPDF文書をオンデマンドで生成したいWeb開発者に特に便利です。 PDFShiftはそのREST APIを通じて完全に動作するため、サービスにわずか数行のHTMLを送信するだけで、ダウンロード可能なPDFファイルを受け取ることができます。 それは、WebベースのPDFファイル生成のためのシンプルでスケーラブルなソリューションです。
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
class Program
{
static async Task Main(string[] args)
{
using (HttpClient client = new HttpClient())
{
string htmlContent = "<h1>Hello, World!</h1><p>This is generated using PDFShift API.</p>";
var content = new StringContent(htmlContent, Encoding.UTF8, "application/json");
HttpResponseMessage response = await client.PostAsync("https://api.pdfshift.io/v3/convert", content);
byte[] pdfBytes = await response.Content.ReadAsByteArrayAsync();
System.IO.File.WriteAllBytes("Generated.pdf", pdfBytes);
}
}
}
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
class Program
{
static async Task Main(string[] args)
{
using (HttpClient client = new HttpClient())
{
string htmlContent = "<h1>Hello, World!</h1><p>This is generated using PDFShift API.</p>";
var content = new StringContent(htmlContent, Encoding.UTF8, "application/json");
HttpResponseMessage response = await client.PostAsync("https://api.pdfshift.io/v3/convert", content);
byte[] pdfBytes = await response.Content.ReadAsByteArrayAsync();
System.IO.File.WriteAllBytes("Generated.pdf", pdfBytes);
}
}
}
Imports System.Net.Http
Imports System.Text
Imports System.Threading.Tasks
Friend Class Program
Shared Async Function Main(ByVal args() As String) As Task
Using client As New HttpClient()
Dim htmlContent As String = "<h1>Hello, World!</h1><p>This is generated using PDFShift API.</p>"
Dim content = New StringContent(htmlContent, Encoding.UTF8, "application/json")
Dim response As HttpResponseMessage = Await client.PostAsync("https://api.pdfshift.io/v3/convert", content)
Dim pdfBytes() As Byte = Await response.Content.ReadAsByteArrayAsync()
System.IO.File.WriteAllBytes("Generated.pdf", pdfBytes)
End Using
End Function
End Class
DocRaptorは、HTMLとCSSを高品質なPDFに変換する強力なAPIベースのPDF生成サービスです。 HTMLドキュメントの優れたレンダリングで知られており、特に複雑なCSSスタイル、メディアクエリ、ウェブフォントの処理に秀でています。 これにより、DocRaptorは、レポート、請求書、eBookなどのプロフェッショナルな外観のドキュメントをHTMLテンプレートから直接生成するのに最適な選択肢となります。
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
class Program
{
static async Task Main(string[] args)
{
using (HttpClient client = new HttpClient())
{
string apiKey = "YOUR_API_KEY";
string htmlContent = "<h1>Professional Report</h1><p>Generated using DocRaptor API.</p>";
string jsonData = $"{{\"test\": true, \"document_content\": \"{htmlContent}\", \"name\": \"Generated.pdf\", \"document_type\": \"pdf\"}}";
var content = new StringContent(jsonData, Encoding.UTF8, "application/json");
HttpResponseMessage response = await client.PostAsync($"https://docraptor.com/docs?user_key={apiKey}", content);
byte[] pdfBytes = await response.Content.ReadAsByteArrayAsync();
System.IO.File.WriteAllBytes("Generated.pdf", pdfBytes);
}
}
}
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
class Program
{
static async Task Main(string[] args)
{
using (HttpClient client = new HttpClient())
{
string apiKey = "YOUR_API_KEY";
string htmlContent = "<h1>Professional Report</h1><p>Generated using DocRaptor API.</p>";
string jsonData = $"{{\"test\": true, \"document_content\": \"{htmlContent}\", \"name\": \"Generated.pdf\", \"document_type\": \"pdf\"}}";
var content = new StringContent(jsonData, Encoding.UTF8, "application/json");
HttpResponseMessage response = await client.PostAsync($"https://docraptor.com/docs?user_key={apiKey}", content);
byte[] pdfBytes = await response.Content.ReadAsByteArrayAsync();
System.IO.File.WriteAllBytes("Generated.pdf", pdfBytes);
}
}
}
Imports System.Net.Http
Imports System.Text
Imports System.Threading.Tasks
Friend Class Program
Shared Async Function Main(ByVal args() As String) As Task
Using client As New HttpClient()
Dim apiKey As String = "YOUR_API_KEY"
Dim htmlContent As String = "<h1>Professional Report</h1><p>Generated using DocRaptor API.</p>"
Dim jsonData As String = $"{{""test"": true, ""document_content"": ""{htmlContent}"", ""name"": ""Generated.pdf"", ""document_type"": ""pdf""}}"
Dim content = New StringContent(jsonData, Encoding.UTF8, "application/json")
Dim response As HttpResponseMessage = Await client.PostAsync($"https://docraptor.com/docs?user_key={apiKey}", content)
Dim pdfBytes() As Byte = Await response.Content.ReadAsByteArrayAsync()
System.IO.File.WriteAllBytes("Generated.pdf", pdfBytes)
End Using
End Function
End Class
コードを書きたくない場合や、PDF生成のための迅速な解決策が必要な場合、いくつかのオンラインツールを使用してPDFを迅速かつ簡単に作成することができます。 以下は注目すべきオプションです。
Smallpdf は、多様なファイル形式からPDFを作成する機能を含む、PDF関連のツールを提供するオンラインプラットフォームです。 コードを書く必要がなく、シンプルなドラッグ&ドロップインターフェースを求めているユーザー向けに設計されています。 Smallpdfは、Wordドキュメント、Excelシート、画像をPDFに変換するなどの迅速なファイル変換に広く使用されています。 また、PDFの結合、圧縮、分割のためのツールを提供しており、基本的なPDF作業において多用途なツールとなります。
PDFescapeは、ユーザーがソフトウェアをインストールすることなくPDFを作成、編集、表示できる、使いやすいWebベースのPDFエディターです。 フォームへの記入、テキスト注釈の追加、画像の挿入など、PDFに迅速に編集を加える必要がある方には素晴らしいツールです。 PDFescapeは、基本的なドキュメント作成のための柔軟な選択肢となる、新しいPDFをゼロから作成するためのツールも提供しています。
PDF Candyは、ファイル変換から編集まで、PDF関連の幅広いタスクを網羅する無料のオンラインPDFツールセットです。 アカウント登録やソフトウェアのインストールをせずに、迅速なPDF操作を実行したいユーザーにとって、優れた選択肢です。 PDF Candyは、Word文書、画像、テキストファイルなど、さまざまなファイルタイプをPDFに変換することをサポートしています。 また、PDFの結合、分割、圧縮のためのツールも提供します。
C#でPDFファイルを生成するための適切なツールを選ぶことは、あなたのニーズによります。 HTMLコンテンツからPDFドキュメントを生成する必要がある場合、IronPDFとPDFShiftは優れた選択肢です。 iTextSharpやSyncfusionは、より複雑なプロジェクトに対して、文書構造のカスタマイズオプションと制御を幅広く提供しています。 よりシンプルでオープンソースのソリューションを求める場合、PDFsharpはPDFファイルの変更や基本的なPDFの作成において信頼性の高い選択肢です。 最後に、開発者でない方には、Smallpdf、PDFescape、PDF CandyがPDFファイルを扱うための簡単でコード不要なオプションを提供します。
IronPDFを試してみたい方には、HTMLからPDFへの変換とPDF操作機能を購入前にテストできるため、開発者にとって優れた選択肢です。 試用版では、高品質なPDFファイルの生成、セキュリティオプション、既存のPDFドキュメントの修正などのプレミアム機能を探索でき、ツールの機能を実際に体験することができます。 あなたのプロジェクトが頻繁なHTMLからPDFへの変換や複雑なPDF編集を必要とする場合、IronPDFの無料トライアルはそれがあなたのニーズに合っているかどうかを確認するための素晴らしい方法です。
各ツールの特定の機能とプロジェクトの範囲を評価することで、C#でPDFファイルを効率的に生成するための最適なソリューションを選択できます。