
複数ページを1つのPDFファイルにスキャンする方法
.NET MAUIは、開発者が単一のコードベースでクロスプラットフォームのデスクトップ、ウェブ、モバイルアプリを構築できる.NETの次世代です。これにはXamarin.Formsが含まれます。 .NET MAUIを使用すると、アプリケーションを一度作成し、Windows、macOS、iOS、Android、tvOSなどの複数のプラットフォームに同じプロジェクト名でデプロイできます。 .NET MAUIは、各プラットフォームの最新のUI機能を活用することも可能にします。例えば、macOS上のダークモードやタッチサポート、またはWindows 10上の音声認識などです。
この記事では、.NET MAUIアプリでIronPDFを使用して、多くの利点を持つPDFドキュメントを作成する方法を説明します。
.NET MAUIでPDFファイルを表示する方法
- .NETのMAUIでPDFファイルを見るためにIronPDFをインストールする
- MAUIプロジェクトのフロントエンドデザインのセットアップ
- ローカルストレージにファイルを保存し、PDFを表示する方法を処理
- URL、HTML文字列、ファイル用のレンダーメソッドを使用
- ステップ3でカスタムハンドラーにレンダリングされたPDFを渡す
IronPDF: C# PDFライブラリ
IronPDFは、PDFファイルを生成および編集することができる.NETライブラリです。 それは.NET MAUIアプリケーションでの使用に最適であり、特定のニーズに合わせてカスタマイズできる幅広い機能を提供します。 使いやすいAPIを持つIronPDFは、PDF機能を.NET MAUIプロジェクトに統合するのを簡単にします。
前提条件
IronPDFを使用して.NET MAUIでPDFおよびPDFビューアーを作成するための前提条件があります:
- 最新バージョンのVisual Studio
- .NET Framework 6または7
- Visual StudioにインストールされたMAUIパッケージ
- Visual Studioで実行される.NET MAUIアプリケーション
ステップ 1: IronPDFをインストールする
新しいプロジェクトにIronPDFをインストールする最良の方法の一つは、Visual Studio内のNuGetパッケージマネージャーコンソールを使用することです。 この方法を使用してIronPDFをインストールするには、いくつかの利点があります。
- 簡単にでき、
- 最新バージョンのIronPDFを使用していることを確認できます。
IronPDFをインストールする手順
まず、ツール > NuGetパッケージマネージャー > パッケージマネージャーコンソールを選択して、パッケージマネージャーコンソールを開きます。
パッケージマネージャーコンソール
次に、以下のコマンドを入力します:
これにより、パッケージとassetsフォルダのようなすべての依存関係がインストールされます。
IronPDFのインストール
これで、MAUIプロジェクトでIronPDFを使用し始めることができます。
ステップ 2: .NET MAUIでフロントエンドデザインを設定する
まず、IronPDFの3つの機能のためのレイアウトを作成します。
URLをPDFに変換するレイアウト
URLをPDFに変換するレイアウトには、.NET MAUIラベルコントロールを使用して、"PDFに変換するURLを入力する"というテキストを持つラベルを作成します。 その後、エントリーコントロールとボタンを横に並べるための水平スタックレイアウトを適用します。 次に、コントロールの後に行を入れて、次のセクションのコントロールを区切ります。
<Label
Text="Enter URL to Convert PDF"
SemanticProperties.HeadingLevel="Level1"
FontSize="18"
HorizontalOptions="Center"
/>
<HorizontalStackLayout
HorizontalOptions="Center">
<Border Stroke="White"
StrokeThickness="2"
StrokeShape="RoundRectangle 5,5,5,5"
HorizontalOptions="Center">
<Entry
x:Name="URL"
HeightRequest="50"
WidthRequest="300"
HorizontalOptions="Center"
/>
</Border>
<Button
x:Name="urlPDF"
Text="Convert URL to PDF"
Margin="30,0,0,0"
Clicked="UrlToPdf"
HorizontalOptions="Center" />
</HorizontalStackLayout>
<Line Stroke="White" X2="1500" />
HTMLをPDFに変換するレイアウト
HTMLをPDFに変換するセクションのレイアウトには、エディターコントロールとボタンを作成します。 エディターコントロールは、ユーザーからHTMLコンテンツの文字列を受け入れるために使用されます。 さらに、区切り線として線を追加します。
<Label
Text="Enter HTML to Convert to PDF"
SemanticProperties.HeadingLevel="Level2"
FontSize="18"
HorizontalOptions="Center" />
<Border
Stroke="White"
StrokeThickness="2"
StrokeShape="RoundRectangle 5,5,5,5"
HorizontalOptions="Center">
<Editor
x:Name="HTML"
HeightRequest="200"
WidthRequest="300"
HorizontalOptions="Center"
/>
</Border>
<Button
x:Name="htmlPDF"
Text="Convert HTML to PDF"
Clicked="HtmlToPdf"
HorizontalOptions="Center" />
<Line Stroke="White" X2="1500" />
HTMLファイルをPDFに変換するレイアウト
HTMLファイルをPDFに変換するには、ボタンを1つ追加するだけです。 そのボタンは、IronPDFを使用してHTMLファイルをPDFドキュメントに変換する役割を果たします。
<Label
Text="Convert HTML file to PDF"
SemanticProperties.HeadingLevel="Level2"
FontSize="18"
HorizontalOptions="Center" />
<Button
x:Name="htmlFilePDF"
Text="Convert HTML file to PDF"
Clicked="FileToPdf"
HorizontalOptions="Center" />
完全なUIコード
以下に.NET MAUIフロントエンドの完全なソースコードを示します。
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="PDF_Viewer.MainPage">
<ScrollView>
<VerticalStackLayout
Spacing="25"
Padding="30,0"
VerticalOptions="Center">
<Label
Text="Enter URL to Convert PDF"
SemanticProperties.HeadingLevel="Level1"
FontSize="18"
HorizontalOptions="Center"
/>
<HorizontalStackLayout
HorizontalOptions="Center">
<Border Stroke="White"
StrokeThickness="2"
StrokeShape="RoundRectangle 5,5,5,5"
HorizontalOptions="Center">
<Entry
x:Name="URL"
HeightRequest="50"
WidthRequest="300"
HorizontalOptions="Center"
/>
</Border>
<Button
x:Name="urlPDF"
Text="Convert URL to PDF"
Margin="30,0,0,0"
Clicked="UrlToPdf"
HorizontalOptions="Center" />
</HorizontalStackLayout>
<Line Stroke="White" X2="1500" />
<Label
Text="Enter HTML to Convert to PDF"
SemanticProperties.HeadingLevel="Level2"
FontSize="18"
HorizontalOptions="Center" />
<Border
Stroke="White"
StrokeThickness="2"
StrokeShape="RoundRectangle 5,5,5,5"
HorizontalOptions="Center">
<Editor
x:Name="HTML"
HeightRequest="200"
WidthRequest="300"
HorizontalOptions="Center"
/>
</Border>
<Button
x:Name="htmlPDF"
Text="Convert HTML to PDF"
Clicked="HtmlToPdf"
HorizontalOptions="Center" />
<Line Stroke="White" X2="1500" />
<Label
Text="Convert HTML file to PDF"
SemanticProperties.HeadingLevel="Level2"
FontSize="18"
HorizontalOptions="Center" />
<Button
x:Name="htmlFilePDF"
Text="Convert HTML file to PDF"
Clicked="FileToPdf"
HorizontalOptions="Center" />
</VerticalStackLayout>
</ScrollView>
</ContentPage>
ステップ 3: PDFファイルを保存して表示するためのコード
.NET MAUIにはローカルストレージにファイルを保存するための事前に構築された機能はありません。 したがって、自分でコードを書く必要があります。 保存および表示機能を作成するために、SaveAndViewという名前の部分void関数が作成されます。この関数には、ファイル名、ファイルコンテンツタイプ、およびファイルを書き込むためのメモリストリームの3つのパラメータがあります。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PDF_Viewer
{
public partial class SaveService
{
public partial void SaveAndView(string filename, string contentType, MemoryStream stream);
}
}Imports System
Imports System.Collections.Generic
Imports System.Linq
Imports System.Text
Imports System.Threading.Tasks
Namespace PDF_Viewer
Partial Public Class SaveService
Public Partial Private Sub SaveAndView(ByVal filename As String, ByVal contentType As String, ByVal stream As MemoryStream)
End Sub
End Class
End Namespace保存および閲覧の機能は、サポートを意図している各プラットフォーム(例えば、Android、macOS、またはWindows)で実装する必要があります。 Windowsプラットフォーム用に"SaveWindows.cs"という名前のファイルを作成し、SaveAndViewという部分メソッドを実装します:
using Windows.Storage;
using Windows.Storage.Pickers;
using Windows.Storage.Streams;
using Windows.UI.Popups;
namespace PDF_Viewer
{
public partial class SaveService
{
public async partial void SaveAndView(string filename, string contentType, MemoryStream stream)
{
StorageFile stFile;
string extension = Path.GetExtension(filename);
//Gets process windows handle to open the dialog in application process.
IntPtr windowHandle = System.Diagnostics.Process.GetCurrentProcess().MainWindowHandle;
if (!Windows.Foundation.Metadata.ApiInformation.IsTypePresent("Windows.Phone.UI.Input.HardwareButtons"))
{
//Creates file save picker to save a file.
FileSavePicker savePicker = new FileSavePicker();
savePicker.DefaultFileExtension = ".pdf";
savePicker.SuggestedFileName = filename;
//Saves the file as PDF file.
savePicker.FileTypeChoices.Add("PDF", new List<string>() { ".pdf" });
WinRT.Interop.InitializeWithWindow.Initialize(savePicker, windowHandle);
stFile = await savePicker.PickSaveFileAsync();
}
else
{
StorageFolder local = ApplicationData.Current.LocalFolder;
stFile = await local.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting);
}
if (stFile != null)
{
using (IRandomAccessStream zipStream = await stFile.OpenAsync(FileAccessMode.ReadWrite))
{
//Writes compressed data from memory to file.
using Stream outstream = zipStream.AsStreamForWrite();
outstream.SetLength(0);
//Saves the stream as file.
byte [] buffer = stream.ToArray();
outstream.Write(buffer, 0, buffer.Length);
outstream.Flush();
}
//Create message dialog box.
MessageDialog msgDialog = new("Do you want to view the document?", "File has been created successfully");
UICommand yesCmd = new("Yes");
msgDialog.Commands.Add(yesCmd);
UICommand noCmd = new("No");
msgDialog.Commands.Add(noCmd);
WinRT.Interop.InitializeWithWindow.Initialize(msgDialog, windowHandle);
//Showing a dialog box.
IUICommand cmd = await msgDialog.ShowAsync();
if (cmd.Label == yesCmd.Label)
{
//Launch the saved file.
await Windows.System.Launcher.LaunchFileAsync(stFile);
}
}
}
}
}Imports Windows.Storage
Imports Windows.Storage.Pickers
Imports Windows.Storage.Streams
Imports Windows.UI.Popups
Namespace PDF_Viewer
Partial Public Class SaveService
Public Async Sub SaveAndView(filename As String, contentType As String, stream As MemoryStream)
Dim stFile As StorageFile
Dim extension As String = Path.GetExtension(filename)
'Gets process windows handle to open the dialog in application process.
Dim windowHandle As IntPtr = System.Diagnostics.Process.GetCurrentProcess().MainWindowHandle
If Not Windows.Foundation.Metadata.ApiInformation.IsTypePresent("Windows.Phone.UI.Input.HardwareButtons") Then
'Creates file save picker to save a file.
Dim savePicker As New FileSavePicker()
savePicker.DefaultFileExtension = ".pdf"
savePicker.SuggestedFileName = filename
'Saves the file as PDF file.
savePicker.FileTypeChoices.Add("PDF", New List(Of String)() From {".pdf"})
WinRT.Interop.InitializeWithWindow.Initialize(savePicker, windowHandle)
stFile = Await savePicker.PickSaveFileAsync()
Else
Dim local As StorageFolder = ApplicationData.Current.LocalFolder
stFile = Await local.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting)
End If
If stFile IsNot Nothing Then
Using zipStream As IRandomAccessStream = Await stFile.OpenAsync(FileAccessMode.ReadWrite)
'Writes compressed data from memory to file.
Using outstream As Stream = zipStream.AsStreamForWrite()
outstream.SetLength(0)
'Saves the stream as file.
Dim buffer() As Byte = stream.ToArray()
outstream.Write(buffer, 0, buffer.Length)
outstream.Flush()
End Using
End Using
'Create message dialog box.
Dim msgDialog As New MessageDialog("Do you want to view the document?", "File has been created successfully")
Dim yesCmd As New UICommand("Yes")
msgDialog.Commands.Add(yesCmd)
Dim noCmd As New UICommand("No")
msgDialog.Commands.Add(noCmd)
WinRT.Interop.InitializeWithWindow.Initialize(msgDialog, windowHandle)
'Showing a dialog box.
Dim cmd As IUICommand = Await msgDialog.ShowAsync()
If cmd.Label = yesCmd.Label Then
'Launch the saved file.
Await Windows.System.Launcher.LaunchFileAsync(stFile)
End If
End If
End Sub
End Class
End NamespaceAndroidおよびmacOSについては、同様のSaveAndView実装を持つ別々のファイルを作成する必要があります。 作業例はこのMAUI PDF Viewer GitHubリポジトリから取得できます。
ステップ 4: PDF機能のコード
それでは、PDF機能のコードを作成する時が来ました。 URLをPDFに変換する機能から始めましょう。
URLをPDFに変換する機能
URLからPDFへの機能を作成するために、UrlToPdf関数を作成します。 関数内で、ChromePdfRendererオブジェクトをインスタンス化し、RenderUrlAsPdf関数を使用してURLをPDFドキュメントに変換します。 RenderUrlAsPdf関数は、ウェブサーバーからURLのデータを取得し、これを処理してPDFドキュメントに変換します。 URLエントリーコントロールにテキストを渡し、SaveAndView関数を使用します。 SaveAndView関数のパラメータに生成されたPDFファイルのストリームを渡します。
SaveAndView関数は、ファイルをカスタマイズされたパスに保存し、PDFファイルを表示するオプションを提供します。 最後に、PDFファイルの作成についての情報を持つアラートボックスを表示します。ユーザーが空のエントリコントロールでPDFファイルを作成しようとすると、エラーメッセージと警告を持つアラートボックスが表示されます。
private void UrlToPdf(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(URL.Text))
{
var renderer = new IronPdf.ChromePdfRenderer();
var pdf = renderer.RenderUrlAsPdf(URL.Text.Trim());
SaveService saveService = new SaveService();
saveService.SaveAndView("URLtoPDF.pdf", "application/pdf", pdf.Stream);
DisplayAlert("Success", "PDF from URL Created!", "OK");
}
else
{
DisplayAlert("Error", "Field can't be empty! \nPlease enter URL!", "OK");
}
}Imports Microsoft.VisualBasic
Private Sub UrlToPdf(ByVal sender As Object, ByVal e As EventArgs)
If Not String.IsNullOrEmpty(URL.Text) Then
Dim renderer = New IronPdf.ChromePdfRenderer()
Dim pdf = renderer.RenderUrlAsPdf(URL.Text.Trim())
Dim saveService As New SaveService()
saveService.SaveAndView("URLtoPDF.pdf", "application/pdf", pdf.Stream)
DisplayAlert("Success", "PDF from URL Created!", "OK")
Else
DisplayAlert("Error", "Field can't be empty! " & vbLf & "Please enter URL!", "OK")
End If
End SubHTMLをPDFに変換する機能
HTMLをPDFに変換する機能のために、HtmlToPdf関数を作成し、RenderHtmlAsPdf関数を使用します。 エディターコントロールのテキストを使用し、それをRenderHtmlAsPdf関数のパラメータに渡します。 上記の関数と同様に、SaveAndView関数を使用して、保存後にPDFファイルを表示する機能を有効にします。
private void HtmlToPdf(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(HTML.Text))
{
var renderer = new IronPdf.ChromePdfRenderer();
var pdf = renderer.RenderHtmlAsPdf(HTML.Text);
SaveService saveService = new SaveService();
saveService.SaveAndView("IronPDF HTML string.pdf", "application/pdf", pdf.Stream);
DisplayAlert("Success", "PDF from HTML Created!", "OK");
}
else
{
DisplayAlert("Error", "Field can't be empty! \nPlease enter valid HTML!", "OK");
}
}Imports Microsoft.VisualBasic
Private Sub HtmlToPdf(ByVal sender As Object, ByVal e As EventArgs)
If Not String.IsNullOrEmpty(HTML.Text) Then
Dim renderer = New IronPdf.ChromePdfRenderer()
Dim pdf = renderer.RenderHtmlAsPdf(HTML.Text)
Dim saveService As New SaveService()
saveService.SaveAndView("IronPDF HTML string.pdf", "application/pdf", pdf.Stream)
DisplayAlert("Success", "PDF from HTML Created!", "OK")
Else
DisplayAlert("Error", "Field can't be empty! " & vbLf & "Please enter valid HTML!", "OK")
End If
End SubHTMLファイルをPDFに変換する機能
HTMLファイルをPDFファイルに変換するために、FileToPdf関数を作成します。 RenderHtmlFileAsPdf関数を使用し、HTMLファイルパスをパラメータとして渡します。 すべてのHTMLコンテンツをPDFに変換し、出力ファイルを保存します。
private void FileToPdf(object sender, EventArgs e)
{
var renderer = new IronPdf.ChromePdfRenderer();
var pdf = renderer.RenderHtmlFileAsPdf(@"C:\Users\Administrator\Desktop\index.html");
SaveService saveService = new SaveService();
saveService.SaveAndView("HTML File to PDF.pdf", "application/pdf", pdf.Stream);
DisplayAlert("Success", "PDF from File Created!", "OK");
}Private Sub FileToPdf(ByVal sender As Object, ByVal e As EventArgs)
Dim renderer = New IronPdf.ChromePdfRenderer()
Dim pdf = renderer.RenderHtmlFileAsPdf("C:\Users\Administrator\Desktop\index.html")
Dim saveService As New SaveService()
saveService.SaveAndView("HTML File to PDF.pdf", "application/pdf", pdf.Stream)
DisplayAlert("Success", "PDF from File Created!", "OK")
End Sub出力
プロジェクトを実行した後、出力は次のようになります。
出力
このセクションにMicrosoftのウェブサイトURLを入力して、ボタンをクリックします。
URLからPDFへ
PDFファイルを作成した後、カスタマイズ可能な保存先にファイルを保存するためのダイアログボックスが表示されます。
ファイルの保存
ファイルを保存した後、このポップアップが表示され、PDFファイルを見るためのPDFビューアを選択するオプションが提供されます。
PDFビューアポップアップ
IronPDFは、URLを素晴らしい形でPDFに変換します。 それは、すべての色と画像を元の形とフォーマットで保持します。
PDFビューアポップアップ
他のすべての機能でも同じ手順を行う必要があります。 IronPDFのBlazorでの動作を学ぶには、このIronPDFのBlazorブログをご覧ください。
XAMLとしてのMAUIページをPDFドキュメントに変換する方法を"MAUIでのXAMLからPDFへの変換方法"を訪れて学びます。
まとめ
このチュートリアルでは、.NET MAUIアプリでIronPDFを使用してPDFファイルとPDFビューアを作成しました。 .NET MAUIは、単一のコードベースでマルチプラットフォームアプリケーションを作成するための素晴らしいツールです。 IronPDFは、.NETアプリケーションでPDFファイルを簡単に作成およびカスタマイズするのに役立ちます。 IronPDFは、.NET MAUIプラットフォームと完全に互換性があります。
IronPDFは開発のために無料です。 無料トライアルキーを取得して、IronPDFを本番環境で試すことができます。 IronPDF公式ウェブサイトで、IronPDFとその機能についての更なる情報をぜひご覧ください。

Curtis Chauは、カールトン大学でコンピュータサイエンスの学士号を取得し、Node.js、TypeScript、JavaScript、およびReactに精通したフロントエンド開発を専門としています。直感的で美しいユーザーインターフェースを作成することに情熱を持ち、Curtisは現代のフレームワークを用いた開発や、構造の良い視覚的に魅力的なマニュアルの作成を楽しんでいます。
関連する記事


