在 .NET 中将 TXT 文件转换为 PDF 文档

博客类别:PDF办公.NET

2021/07/01

通常需要将格式化文本转换为 PDF 文档。如果文本格式复杂,则将格式化文本转换为 PDF 内容可能需要花费大量时间和编写大量代码。

自 VintaSoft Imaging .NET SDK 10.1 版本起,可以编辑现有的 DOCX 和 XLSX 文档。可以使用此功能来避免以编程方式将格式化文本转换为 PDF 内容。与其编写大量代码来转换格式化文本,不如创建一个具有必要格式的 DOCX 文档,并将所需的文本内容插入到该已格式化的文档中。之后,可以使用 VintaSoft Imaging .NET SDK 的功能轻松地将创建的 DOCX 文档转换为 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);
    }
}