.NET で TXT ファイルを PDF ドキュメントに変換します

ブログ カテゴリ: PDFOffice.NET

2021/07/01

書式設定されたテキストを PDF ドキュメントに変換する必要があることがよくあります。テキストの書式が複雑な場合、書式設定されたテキストを PDF コンテンツに変換するには多くの時間とコードが必要になることがあります。

VintaSoft Imaging .NET SDK バージョン 10.1 以降では、既存の DOCX および XLSX ドキュメントを編集できるようになりました。この機能を使用すると、書式設定されたテキストをプログラムで PDF コンテンツに変換する必要がなくなります。書式設定されたテキストを変換するために大量のコードを記述する代わりに、必要な書式設定された DOCX ドキュメントを作成し、必要なテキスト コンテンツを既に書式設定されたドキュメントに挿入することができます。その後、作成された DOCX ドキュメントは、VintaSoft Imaging .NET SDK の機能を使用して簡単に PDF ドキュメントに変換できます。

上記の方法に基づいて、以下の手順に従って TXT から PDF へのコンバーターを簡単に作成できます。
1. MS Word を使用して DOCX ドキュメント txtTemplate.docx を作成します。
2. アプリケーション コード内:
このアプローチにより、コンバーターの柔軟性とカスタマイズの容易さが実現します。出力ドキュメントのパラメーターを変更するには、MS Word を使用して txtTemplate.docx テンプレートのパラメーターを変更するだけです。


TXT ファイルを PDF ドキュメントに変換する方法を示すコード例を次に示します。
// The project, which uses this code, must have references to the following assemblies:
// - Vintasoft.Imaging
// - Vintasoft.Imaging.Office.OpenXml
// - Vintasoft.Imaging.Pdf

/// <summary>
/// Tests conversion from TXT file to a PDF document.
/// </summary>
public static void Test()
{
    ConvertTxtFileToPdfDocument("Products.txt", "txtTemplate.docx", "Products.pdf");
}

/// <summary>
/// Converts specified text file to a PDF document.
/// </summary>
/// <param name="txtFilename">The TXT filename.</param>
/// <param name="docxTemplateFilename">The DOCX template filename.</param>
/// <param name="outputPdfFilename">The output PDF filename.</param>
public static void ConvertTxtFileToPdfDocument(string txtFilename, string docxTemplateFilename, string outputPdfFilename)
{
    string text = System.IO.File.ReadAllText(txtFilename, System.Text.Encoding.Unicode);
    ConvertTextToPdfDocument(System.IO.Path.GetFileName(txtFilename), text, docxTemplateFilename, outputPdfFilename);
}

/// <summary>
/// Converts specified text to a PDF document.
/// </summary>
/// <param name="text">The text.</param>
/// <param name="title">The document title.</param>
/// <param name="docxTemplateFilename">The DOCX template filename.</param>
/// <param name="outputPdfFilename">The output PDF filename.</param>
public static void ConvertTextToPdfDocument(string title, string text, string docxTemplateFilename, string outputPdfFilename)
{
    // create DocxDocumentEditor and use DOCX file as a document template
    using (Vintasoft.Imaging.Office.OpenXml.Editor.DocxDocumentEditor editor =
        new Vintasoft.Imaging.Office.OpenXml.Editor.DocxDocumentEditor(docxTemplateFilename))
    {
        // replace text "[title]" by document title
        editor.Body.ReplaceText("[title]", title);

        // if document body does not contain text "[content]"
        if (!editor.Body.Contains("[content]"))
            throw new ArgumentException("Template file must be contains '[content]' text.");

        // replace text "[content]" by text content
        editor.Body["[content]"] = text;

        // export DOCX document to a PDF document
        editor.Export(outputPdfFilename);
    }
}