sample unicode
[[sample_unicode]] last edit on Feb 13, 2008 9:45 AM by thomas_hoevel

Unicode

This sample shows how to use Unicode text in PDFsharp. You found code snippets for the following graphical primitives:
  • XPdfFontOptions
  • XTextFormatter

PDF Output File

See the PDF file created by this sample: Unicode.pdf (12 kB)

Source Code Listing

using System;
using System.Diagnostics;
using System.IO;
using PdfSharp.Pdf;
using PdfSharp.Drawing;
using PdfSharp.Drawing.Layout;

namespace Unicode
{
/// <summary>
/// This sample shows how to use Unicode text in PDFsharp.
/// </summary>
class Program
{
  [STAThread]
  static void Main(string[] args)
  {
    // Create new document
    PdfDocument document = new PdfDocument();

    // Set unicode flag to true
    XPdfFontOptions options = new XPdfFontOptions(false, true);

    XFont font = new XFont("Times New Roman", 12, XFontStyle.Regular, options);

    // Draw text in different languages
    for (int idx = 0; idx < texts.Length; idx++)
    {
      PdfPage page = document.AddPage();
      XGraphics gfx = XGraphics.FromPdfPage(page);
      XTextFormatter tf = new XTextFormatter(gfx);
      tf.Alignment = XParagraphAlignment.Justify;

      tf.DrawString(texts[idx], font, XBrushes.Black,
        new XRect(100, 100, page.Width - 200, 600), XStringFormat.TopLeft);
    }

    string filename = "Unicode.pdf";
    // Save the document...
    document.Save(filename);
    // ...and start a viewer.
    Process.Start(filename);
  }

  static string[] texts = new string[]
  {
    // International version of the text in English
    "English\n" +
    "PDFsharp is a .NET library for creating and processing PDF documents 'on the fly'. " +
    "The library is completely written in C# and based exclusively on safe, managed code. " +
    "PDFsharp offers two powerful abstraction levels to create and process PDF documents.\n" +
    "For drawing text, graphics, and images there is a set of classes which are modeled similar to the classes " +
    "of the name space System.Drawing of the .NET framework. With these classes it is not only possible to create " +
    "the content of PDF pages in an easy way, but they can also be used to draw in a window or on a printer.\n" +
    "Additionally PDFsharp completely models the structure elements PDF is based on. With them existing PDF documents " +
    "can be modified, merged, or split with ease.\n" +
    "The source code of PDFsharp is Open Source under the MIT license (http://en.wikipedia.org/wiki/MIT_License). " +
    "Therefore it is possible to use PDFsharp without limitations in non open source or commercial projects/products.",

    // PDFsharp is 'Made in Germany'
    "German\n" +
    "PDFsharp ist eine .NET-Bibliothek zum Erzeugen und Verarbeiten von PDF-Dokumenten 'On the Fly'. " +
    "Die Bibliothek ist vollständig in C# geschrieben und basiert ausschließlich auf sicherem, verwaltetem Code. " +
    "PDFsharp bietet zwei leistungsstarke Abstraktionsebenen zur Erstellung und Verarbeitung von PDF-Dokumenten.\n" +
    "Zum Zeichnen von Text, Grafik und Bildern gibt es einen Satz von Klassen, die sehr stark an die Klassen " +
    "des Namensraums System.Drawing des .NET Frameworks angelehnt sind. Mit diesen Klassen ist es nicht " +
    "nur auf einfache Weise möglich, den Inhalt von PDF-Seiten zu gestalten, sondern sie können auch zum " +
    "Zeichnen in einem Fenster oder auf einem Drucker verwendet werden.\n" +
    "Zusätzlich modelliert PDFsharp vollständig die Stukturelemente, auf denen PDF basiert. Dadurch können existierende " +
    "PDF-Dokumente mit Leichtigkeit zerlegt, ergänzt oder umgebaut werden.\n" +
    "Der Quellcode von PDFsharp ist Open-Source unter der MIT-Lizenz (http://de.wikipedia.org/wiki/MIT-Lizenz). " +
    "Damit kann PDFsharp auch uneingeschränkt in Nicht-Open-Source- oder kommerziellen Projekten/Produkten eingesetzt werden.",

    // Greek version
    // The text was translated by Babel Fish. We here in Germany have no idea what it means.
    // If you are a native speaker please correct it and mail it to mailto:PDFsharpSupport@pdfsharp.de
    "Greek (Translated with Babel Fish)\n" +
    "&#932;&#959; PDFsharp &#949;&#943;&#957;&#945;&#953; &#946;&#953;&#946;&#955;&#953;&#959;&#952;&#942;&#954;&#951; &#948;&#953;&#954;&#964;&#973;&#959;&#965; &#945;. &#947;&#953;&#945; &#964;&#951; &#948;&#951;&#956;&#953;&#959;&#965;&#961;&#947;	
43;α και την επεξεργασία των εγγράφων PDF 'σχετικά με τη
; μύγα'. Η βιβλιοθήκη γράφεται εντελώς γ # και βασίζε&#
964;αι αποκλειστικά εκτός από, διοικούμενος κώδικας
;. Το PDFsharp προσφέρει δύο ισχυρά επίπεδα αφαίρεσης για &#
957;α δημιουργήσει και να επεξεργαστεί τα έγγραφα PDF. Γ
;ια το κείμενο, τη γραφική παράσταση, και τις εικόν^
9;ς σχεδίων υπάρχει ένα σύνολο κατηγοριών που διαμ
ορφώνονται παρόμοιος με τις κατηγορίες του διασ
64;ημικού σχεδίου συστημάτων ονόματος του. πλαισίο
υ δικτύου. Με αυτές τις κατηγορίες που είναι όχι μό
;νο δυνατό να δημιουργηθεί το περιεχόμενο των σελ&
  1. 943;δων PDF με έναν εύκολο τρόπο, αλλά αυτοί μπορεί επίσ
51;ς να χρησιμοποιηθεί για να επισύρει την προσοχή `
3;ε ένα παράθυρο ή σε έναν εκτυπωτή. Επιπλέον PDFsharp διαμ&
  1. 959;ρφώνει εντελώς τα στοιχεία PDF δομών είναι βασισμέ
νο. Με τους τα υπάρχοντα έγγραφα PDF μπορούν να τροπο&#
960;οιηθούν, συγχωνευμένος, ή να χωρίσουν με την ευκο&#
955;ία. Ο κώδικας πηγής PDFsharp είναι ανοικτή πηγή με άδεια MIT
(http://en.wikipedia.org/wiki/MIT_License). Επομένως είναι δυνατό να χρησιμοποιηθε
43; PDFsharp χωρίς προβλήματα στη μη ανοικτή πηγή ή τα εμπορ
ικά προγράμματα/τα προϊόντα.",

    // Russian version
    // The text was translated by Babel Fish. We here in Germany have no idea what it means.
    // If you are a native speaker please correct it and mail it to mailto:PDFsharpSupport@pdfsharp.de
    "Russia (Translated with Babel Fish)\n" +
    "PDFsharp &#1073;&#1091;&#1076;&#1077;&#1090; &#1072;&#1088;&#1093;&#1080;&#1074;&#1086;&#1084; NET &#1076;&#1083;&#1103; &#1089;&#1086;&#1079;&#1076;&#1072;&#1074;&#1072;&#1090;&#1100; &#1080; &#1086;&#1073;&#1088;&#1072;&#1073;&#1072;&#1090;&#1099;
;вать документы pdf ' на мухе '. Архив вполне напи&
  1. 1089;ан в ч # и основан исключительн на за исключ&
  2. 1077;нием, управляемое Кодий. PDFsharp предлагает 2 мощ&
  3. 1085;ых уровня абстракции для того чтобы создk
2;ть и обработать документы pdf. Для рисуя текс

90;а, графиков, и изображений будет комплект т
;ипов которые моделированные подобными к

90;ипам названного космоса System.Drawing рамок NET. С этими &#
1090;ипами not only по возможности создать содержани
;е страниц pdf в легкой дороге, но их можно такж
077; использовать для того чтобы нарисовать в
окне или на принтере. Дополнительно PDFsharp впол&
  1. 1085;е моделирует элементы структуры, котор pdf о&
  2. 1089;нован дальше. С ими существуя документы pdf м
ожно доработать, после того как я слиты, или
разделение с легкостью. Кодим источника PDFsharp &#
1073;удет открытый источник под лицензией mit (http://en.wikipe
dia.org/wiki/MIT_License). Поэтому по возможности использовать
PDFsharp без проблем в non открытом источнике или коl
4;мерчески projects/products.",

    // International version of the text in Portuguese (Brazil)
    "Português\n" +
    "PDFsharp é uma biblioteca .NET para criação e processamento de documentos PDF 'em tempo de execução'. " +
    "A biblioteca é completamente escrita em C# e baseada exclusivamente no código seguro, código gerenciado. " +
    "PDFsharp oferece dois níveis de abstração para criar e processar documentos PDF.\n" +
    "Para desenhar texto, gráficos, e imagens há um conjunto de classes as quais são modeladas de modo similar às classes " +
    "do espaço de nomes System.Drawing do .NET framework. Com estas classes não é apenas possível criar " +
    "o conteúdo das páginas PDF de modo fácil, mas elas podem também serem usadas para desenhar em uma janela ou em uma impressora.\n" +
    "Adicionalmente o PDFsharp modela os elementos de estrutura da mesma maneira que um PDF é baseado. Os documentos PDF existentes " +
    "podem ser modificados, mesclados, ou divididos com facilidade.\n" +
    "O código fonte do PDFsharp é de Código Aberto sobre a licença MIT (http://pt.wikipedia.org/wiki/Licen%C3%A7a_MIT). " +
    "Conseqüentemente é possível usar o PDFsharp sem limitações em projetos ou produtos que não sejam de código aberto ou que sejam comerciais.",

    // Your language may come here
    "Invitation\n" +
    "If you use PDFsharp and haven't found your native language in this document, we will be pleased to get your translation of the text above and include it here.\n" +
    "Mail to PDFsharpSupport@pdfsharp.de"


    // The current implementation of PDFsharp is limited to left-to-right languages.
    // Languages like Arabic cannot yet be created even with Unicode fonts. Also the so called
    // CJK (Chinese, Japanese, Korean) support in PDF can also not be addressed with PDF sharp.
    // However, we plan to support as much as possible languages with PDFsharp. If you are a
    // programmer and a native speaker of one of these languages and you like to create PDF
    // documents in your language, you can help us to implement it in PDFsharp. You don't have
    // to do the programming, but just help us to verify our implementation.
  };
}
}