Converti un file TXT in un documento PDF in .NET
Categoria del blog: PDF ; Office ; .NET
01.07.2021
// 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);
}
}