0

I want to pass the text of a richTextBox from Visual Studio (c#) to a .pdf file, using iTextSharp. My code does create the .pdf file and the text is passed on the file. However, the Greek words - characters included do not appear in the text of the file (only english characters, numbers and symbols eg. dash etc do). I understand I need somehow need to alter the default base-font to some other, so that the Greek letters can also show up, and have tried numerous suggestions I have come across, but still can't make it work. Here is my code:

  SaveFileDialog sfd = new SaveFileDialog();

  private void button1_Click(object sender, EventArgs e)
  {
        sfd.Title = "Save As PDF";
        sfd.Filter = "(*.pdf)|*.pdf";
        sfd.InitialDirectory = @"C:\";

        if (sfd.ShowDialog() == DialogResult.OK)
        {

            iTextSharp.text.Document doc = new iTextSharp.text.Document();

            PdfWriter.GetInstance(doc, new FileStream(sfd.FileName, FileMode.Create));
            doc.Open();

            doc.Add(new iTextSharp.text.Paragraph(richTextBox1.Text));
            doc.Close();
        }
   }
Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
arch1
  • 19
  • 3

1 Answers1

1

Firstly, iTextSharp is deprecated. In NuGet package manager you can see that they specifically tell you to use itext7 instead.

In itext7 you will have to make and use a font that supports the greek charset.

This seemed to work for me:

using iText.Kernel.Font;
using iText.Kernel.Pdf;
using iText.Layout;
using iText.Layout.Element;

private void Test()
{
    string fileName = Path.GetDirectoryName(Application.ExecutablePath) + \\test.pdf";
    PdfWriter pdfWriter = new PdfWriter(fileName);
    PdfDocument pdf = new PdfDocument(pdfWriter);
    Document doc = new Document(pdf);

    var font = PdfFontFactory.CreateFont("C:\\Windows\\Fonts\\arial.ttf", "Identity-H", PdfFontFactory.EmbeddingStrategy.FORCE_EMBEDDED);

    Paragraph p = new Paragraph("Α α, Β β, Γ γ, Δ δ, Ε ε, Ζ ζ, Η η, Θ θ, Ι ι, Κ κ, Λ λ, Μ");
    p.SetFont(font);

    doc.Add(p);
    doc.Close();
}
Avo Nappo
  • 620
  • 4
  • 9
  • I changed to iText7 and followed your example code. It all works fine now! Thanks for the great help! – arch1 Sep 25 '21 at 09:01
  • While this indeed is correct, the older iTextSharp (which is iText 5.*) also allowed to use a font with Identity-H encoding to show Latin and Greek (and many other scripts) side-by-side. – mkl Sep 27 '21 at 16:09