PDF(Portable Document Format)は、デジタルドキュメントの世界で広く使用されているフォーマットの1つになっています。さまざまな業界がPDF形式を使用して、レポート、請求書、請求書、およびその他の種類のビジネスドキュメントを生成しています。一方、バーコードは、機械可読形式の情報を含むビジネスの重要な部分になっています。最近では、請求書や請求書にバーコードが記載されている場合もあります。この記事では、たとえば請求書を生成するときに、PDFファイルを作成してバーコードを埋め込む必要があるユースケースを紹介します。デモンストレーションでは、ASP.NET Core Webアプリケーション内でC#を使用してPDFファイルとバーコードを生成できるASP.NETPDFエディターを作成します。

このASP.NETWebアプリケーションには、次の機能があります。

  • PDFドキュメントのコンテンツを書き込むためのWYSIWYGエディタ。
  • 提供されたテキストに基づいてバーコードを生成するオプション。
  • バーコードの目的のシンボルを設定するオプション。

ASP.NETでバーコードを持つPDFを生成するための前提条件

以下は、バーコード機能を備えたASP.NETPDFエディターを作成するために必要なツールとAPIです。

バーコード機能を備えたASP.NETPDFエディターを作成する

旅を始めて、ワンクリックでPDFを生成してバーコードを埋め込むことができるASP.NETPDFエディターを作成する方法を見てみましょう。

  • VisualStudioで新しいASP.NETCoreWebアプリケーションを作成します。
ASP.NETCoreWebアプリケーションを作成する
  • テンプレートからWebアプリケーション(Model-View-Controller)を選択します。
ASP.NET MVC
  • Aspose.PDF、Aspose.BarCode、CKEditorのパッケージをインストールします。
Aspose.NETPDFおよびバーコードAPIを追加します
  • CKEditorのパッケージをダウンロードして解凍し、wwwrootディレクトリのフォルダをコピーして貼り付けます。要件に基づいて、お気に入りのWYSIWYGHTMLエディターを統合することもできます。

  • Views / Home/index.cshtmlビューに次のスクリプトを追加します。

@{
    ViewData["Title"] = "PDF Creator";
}
<script src="~/ckeditor/ckeditor.js"></script>
<br />
<form method="post">
    <div class="row">
        <div class="col-md-12">
            <textarea name="editor1" id="editor1" rows="80" cols="80">
                Start creating your PDF document.
            </textarea>
            <br />
            <script>
                // Replace the <textarea id="editor1"> with a CKEditor
                // instance, using default configuration.
                CKEDITOR.replace('editor1');
            </script>
        </div>
        <hr />
    </div>
    <div class="row">
        <div class="col-md-12">
            <h3>Create a Barcode</h3>
        </div>
    </div>
    <hr />
    <div class="row">
        <div class="col-md-9 form-horizontal" align="center">
            <div class="form-group">
                <label class="control-label col-sm-2" for="CodeText">Code Text</label>
                <div class="col-sm-10">
                    <input class="form-control" type="text" name="codeText" id="codeText" placeholder="Code text" />
                </div>
            </div>
            <div class="form-group">
                <label class="control-label col-sm-2" for="barcodeType">Symbology</label>
                <div class="col-sm-10">
                    <select name="barcodeType" class="form-control">
                        <option value="Code128">Code128</option>
                        <option value="Code11">Code11</option>
                        <option value="QR">QR</option>
                        <option value="Pdf417">Pdf417</option>
                        <option value="Datamatrix">Datamatrix</option>
                    </select>
                </div>
            </div>
        </div>
    </div>
    <hr />
    <div class="row">
        <div class="col-md-12" align="center">
            <input type="submit" class="btn btn-lg btn-success" value="Generate PDF" />
        </div>
    </div>
</form>
  • Controllers/HomeController.csに次のメソッドを追加します。
[HttpPost]
public FileResult Index(string editor1, string codeText, string barcodeType)
{
	// generate a barcode
	string barcodeImagePath = Path.Combine("wwwroot/barcodes/", Guid.NewGuid() + ".png");
	SymbologyEncodeType type = GetBarcodeSymbology(barcodeType);
	BarcodeGenerator generator = new BarcodeGenerator(type, codeText);
	generator.Parameters.BackColor = System.Drawing.Color.Transparent;
	// set resolution of the barcode image
	generator.Parameters.Resolution = 200;
	// generate barcode
	generator.Save(barcodeImagePath, BarCodeImageFormat.Png);

	// create a unique file name for PDF
	string fileName = Guid.NewGuid() + ".pdf";
	// convert HTML text to stream
	byte[] byteArray = Encoding.UTF8.GetBytes(editor1);
	// generate PDF from the HTML
	MemoryStream stream = new MemoryStream(byteArray);
	HtmlLoadOptions options = new HtmlLoadOptions();
	Document pdfDocument = new Document(stream, options);

	// add barcode image to the generated PDF 
	pdfDocument = InsertImage(pdfDocument, barcodeImagePath);

	// create memory stream for the PDF file
	Stream outputStream = new MemoryStream();
	// save PDF to output stream
	pdfDocument.Save(outputStream);

	// return generated PDF file
	return File(outputStream, System.Net.Mime.MediaTypeNames.Application.Pdf, fileName);
}
private SymbologyEncodeType GetBarcodeSymbology(string symbology)
{
	if (symbology.ToLower() == "qr")
		return EncodeTypes.QR;
	else if (symbology.ToLower() == "code128")
		return EncodeTypes.Code128;
	else if (symbology.ToLower() == "code11")
		return EncodeTypes.Code11;
	else if (symbology.ToLower() == "pdf417")
		return EncodeTypes.Pdf417;
	else if (symbology.ToLower() == "datamatrix")
		return EncodeTypes.DataMatrix;
	else
		return EncodeTypes.Code128; // default barcode type
}
private Document InsertImage(Document document, string barcodeImagePath)
{
	// get page from Pages collection of PDF file
	Aspose.Pdf.Page page = document.Pages[1];
	// create an image instance
	Aspose.Pdf.Image img = new Aspose.Pdf.Image();
	img.IsInLineParagraph = true;
	// set Image Width and Height in Points
	img.FixWidth = 100;
	img.FixHeight = 100;
	img.HorizontalAlignment = HorizontalAlignment.Right;
	img.VerticalAlignment = VerticalAlignment.Top;
	// set image type as SVG
	img.FileType = Aspose.Pdf.ImageFileType.Unknown;
	// path for source barcode image file
	img.File = barcodeImagePath;
	page.Paragraphs.Add(img);
	// return updated PDF document
	return document;
}
  • アプリケーションをビルドして、お気に入りのブラウザーで実行します。
バーコード機能を備えたASP.NETPDFエディター

ASP.NETPDFエディターを使用したPDFの生成

以下は、PDFファイルを生成し、シングルクリックでバーコードを埋め込む方法の手順とデモンストレーションです。

  • PDFドキュメントのコンテンツをエディタ領域に書き込むか、コピーして貼り付けます。
  • バーコードを生成するためのコードテキストを設定します。
  • 希望のバーコード記号を選択します(すべてのサポートされているバーコード記号を参照)。
  • [PDFの生成]ボタンをクリックして、バーコードが付いたPDFを作成します。

ソースコードをダウンロード

このASP.NETPDFエディターの完全なソースコードはここからダウンロードできます。

AsposeAPIを無料でお試しください

一時ライセンスを取得して、APIを1か月間無料でお試しください。

関連項目