在很多时候由于txt文本文档作为简单的文件格式,只限于用户可以编辑文本,然而在很多时候,客户需要对文档进行更多操作,如文件保护、保存文档到公司服务器、使用其他软件来阅读,所有这些功能对于文本文档来说都具有比较大的局限性,因此客户可以转换TXT文本文档为PDF文件,
Spire.PDF是一款专业的PDF控件,不仅可以轻松实现文本文档转换为PDF文件,还可以从PDF文档中提取文本和图片等操作,下面的代码讲述了如何转换TXT文档为PDF格式:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Drawing;
namespace TexttoPDF
{
class Program
{
static void Main(string[] args)
{
string text = File.ReadAllText("TestDocument.txt");
PdfDocument doc = new PdfDocument();
PdfSection section = doc.Sections.Add();
PdfPageBase page = section.Pages.Add();
PdfFont font = new PdfFont(PdfFontFamily.Helvetica, 11);
PdfStringFormat format = new PdfStringFormat();
format.LineSpacing = 20f;
PdfBrush brush = PdfBrushes.Black;
PdfTextWidget textWidget = new PdfTextWidget(text, font, brush);
float y = 0;
PdfTextLayout textLayout = new PdfTextLayout();
textLayout.Break = PdfLayoutBreakType.FitPage;
textLayout.Layout = PdfLayoutType.Paginate;
RectangleF bounds = new RectangleF(new PointF(0, y), page.Canvas.ClientSize);
textWidget.StringFormat = format;
textWidget.Draw(page, bounds, textLayout);
doc.SaveToFile("TxtToPDf.pdf", FileFormat.PDF);
}
}