Note that this code only adds the plain text contents of the RichTextBox control to the PDF file. If you want to include the formatted contents of the control (including font styles, colors, etc.), you'll need to use a different format, such as RTF or HTML. To convert the contents of the control in RTF format to PDF using iTextSharp, you can use the following code:
xxxxxxxxxx
using iTextSharp.text;
using iTextSharp.text.pdf;
// Create a new PDF document
Document doc = new Document();
// Create a new PDF writer
PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream("output.pdf", FileMode.Create));
// Open the document
doc.Open();
// Add the contents of the RichTextBox control to the document in RTF format
StringReader reader = new StringReader(richTextBox1.Rtf);
doc.Add(new iTextSharp.text.rtf.RtfParser().Parse(reader));
// Close the document
doc.Close();
use a third-party library such as iTextSharp or PDFsharp. Here's an example using iTextSharp:
xxxxxxxxxx
using iTextSharp.text;
using iTextSharp.text.pdf;
// Create a new PDF document
Document doc = new Document();
// Create a new PDF writer
PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream("output.pdf", FileMode.Create));
// Open the document
doc.Open();
// Add the contents of the RichTextBox control to the document
Paragraph paragraph = new Paragraph(richTextBox1.Text);
doc.Add(paragraph);
// Close the document
doc.Close();
we're using the RtfParser class of iTextSharp to parse the RTF code of the RichTextBox control and add the resulting contents to the PDF document. To convert the contents of the control in HTML format to PDF using iTextSharp, you can use the following code:
xxxxxxxxxx
using iTextSharp.text;
using iTextSharp.text.pdf;
// Create a new PDF document
Document doc = new Document();
// Create a new PDF writer
PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream("output.pdf", FileMode.Create));
// Open the document
doc.Open();
// Add the contents of the RichTextBox control to the document in HTML format
StringReader reader = new StringReader(richTextBox1.Text);
iTextSharp.tool.xml.XMLWorkerHelper.GetInstance().ParseXHtml(writer, doc, reader);
// Close the document
doc.Close();