TXT 파일을 PDF 문서로 변환.NET

블로그 카테고리: PDFOffice.NET

202107/01

서식이 지정된 텍스트를 PDF 문서로 변환해야 하는 경우가 많습니다. 텍스트에 복잡한 서식이 있는 경우 서식이 지정된 텍스트를 PDF 콘텐츠로 변환하는 데 많은 시간과 코드가 필요할 수 있습니다.

VintaSoft Imaging .NET SDK 버전 10.1부터 기존 DOCX 및 XLSX 문서를 편집할 수 있게 되었습니다. 이 기능을 사용하면 서식이 지정된 텍스트를 PDF 콘텐츠로 프로그래밍 방식으로 변환할 필요가 없어집니다. 서식이 지정된 텍스트를 변환하기 위해 많은 코드를 작성하는 대신, 필요한 서식이 지정된 DOCX 문서를 만들고 필요한 텍스트 콘텐츠를 이미 서식이 지정된 문서에 삽입할 수 있습니다. 그런 다음 생성된 DOCX 문서를 VintaSoft Imaging .NET SDK의 기능을 사용하여 PDF 문서로 쉽게 변환할 수 있습니다.

위에서 설명한 방법을 기반으로 다음 단계를 따르면 TXT-PDF 변환기를 쉽게 만들 수 있습니다.
1. MS Word를 사용하여 txtTemplate.docx라는 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);
    }
}