This section is designed to introduce a simple method to clearly convert text to PDF for WPF. During the text to PDF conversion task, font, font color, line space and other text format also can be quickly set according to your own need via a WPF PDF component Spire.PDF for WPF.
Spire.PDF for WPF will display a solution of two key steps to realize text to PDF task as well as customize text in PDF. Compared with some text to PDF converters, Spire.PDF for WPF not only has the function of convert HTML, text and image to PDF, but also owns the ability to read, write and manipulate PDF document without Adobe Acrobat or any third party component library.
Below screenshot gives you a clear view of the text to PDF conversion effect:
Please download Spire.PDF for WPF on system. Then, perform your text to PDF by below key steps.
Step1: Read all text information to s string
In this step, you need to read all the text from a text file to a string.
string text = File.ReadAllText(@"..\texttopdf.txt");
Dim text As String = File.ReadAllText("..\texttopdf.txt")
Step2: Draw string to PDF document with custom layout.
This step allows you to set the text font, font color, text format and position in PDF document at your own will by below code:
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.DarkBlue; float y = 30; 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; }
Dim page As PdfPageBase = section.Pages.Add() Dim font As New PdfFont(PdfFontFamily.Helvetica, 11) Dim format As New PdfStringFormat() format.LineSpacing = 20F Dim pageWidth As Single = page.Canvas.ClientSize.Width Dim brush As PdfBrush = PdfBrushes.DarkBlue Dim y As Single = 30 Dim textLayouter As New PdfStringLayouter() Dim result As PdfStringLayoutResult = textLayouter.Layout(text, font, format, New SizeF(pageWidth, 0)) For Each line As LineInfo In result.Lines page.Canvas.DrawString(line.Text, font, brush, 0, y, format) y = y + result.LineHeight Next
Now that is all the core codes for draw text in PDF. Apart from converting text to PDF, Spire.PDF for WPF also can extract PDF text.