Blog author:
Megan00 | Posted on: 7/26/2012 | Category:
C# Blogs | Views: 1359 | Status:
[Member] |
Points: 75
|
Alert Moderator
In most cases, programmers or developers have to convert .txt to PDF due to the limitation functions of .txt format. But for PDF,it has many advantages for users to apply, thus, convert .txt to PDF is indispensable. This article will introduce you an easy method to .txt to PDF conversion task with C# via a PDF component.
The whole procedure of the conversion task needs three steps, only two key steps are required for the .txt to PDF conversion. You can preview the effective screenshot of the .txt to PDF task first and then view the full code after preview.

C# Code for .txt to PDF:using System.Drawing;
using System.Drawing.Text;
using System.IO;
using Spire.Pdf;
using Spire.Pdf.Graphics;
using Spire.Pdf.Graphics.Fonts;
namespace text_to_pdf
{
class Program
{
static void Main(string[] args)
{
// create a new PDF
PdfDocument doc = new PdfDocument();
//set PDF text format and load the .txt file from system
DrawText(doc.Sections.Add());
//save the .txt as PDF
doc.SaveToFile("result.pdf");
doc.Close();
System.Diagnostics.Process.Start("result.pdf");
}
private static void DrawText(PdfSection section)
{
PdfPageBase page = section.Pages.Add();
PdfFont font = new PdfFont(PdfFontFamily.Helvetica, 11);
PdfStringFormat format = new PdfStringFormat();
format.LineSpacing = 20f;
float pageWidth = page.Canvas.ClientSize.Width;
PdfBrush brush = PdfBrushes.DeepSkyBlue;
float y = 30;
string text = File.ReadAllText(@"..\..\test.txt");
PdfStringLayouter textLayouter = new PdfStringLayouter();
PdfStringLayoutResult result
= textLayouter.Layout(text, font, format, new SizeF(pageWidth, 0));
foreach (LineInfo line in result.Lines)
{
page.Canvas.DrawString(line.Text, font, brush, 0, y, format);
y = y + result.LineHeight;
}
}
}
}
This is from Weebly Top Programming Blog
Never give up! Smile to the world!
http://excelcsharp.blog.com/
Found interesting? Add this to: