如何使用itextsharp将UTF-8字符写入pdf文件?

时间:2011-05-24 12:21:39

标签: c# .net itext pdf-generation

我在谷歌上尝试了很多但却无法找到..

感谢任何帮助。

请找到以下代码: -

protected void Page_Load(object sender, EventArgs e)
    {
        StreamReader read = new StreamReader(@"D:\queryUnicode.txt", Encoding.Unicode);
        string str = read.ReadToEnd();

        Paragraph para = new Paragraph(str);

        FileStream file = new FileStream(@"D:\Query.pdf",FileMode.Create);

        Document pdfDoc = new Document();
        PdfWriter writer = PdfWriter.GetInstance(pdfDoc, file );

        pdfDoc.Open();
        pdfDoc.Add(para);
        pdfDoc.Close();

        Response.Write("Pdf file generated");
    }

1 个答案:

答案 0 :(得分:20)

您是否将HTML转换为PDF?如果是这样,你应该注意,否则没关系。我问的唯一原因是你关于获得æ的最后评论让我想到了。如果你是,请查看这篇文章: iTextSharp 5 polish character

此外,有时当人们说“Unicode”时,他们真正想做的是将像Wingdings这样的符号变成PDF。如果你的意思是看看这篇文章,并知道Unicode和Wingding符号真的根本没有关系。 Unicode symbols in iTextSharp

这是一个完整的工作示例,它使用两种方式编写Unicode字符,一种使用字符本身,另一种使用C#转义序列。确保以支持宽字符的格式保存文件。此示例使用iTextSharp 5.0.5。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using iTextSharp.text;
using iTextSharp.text.pdf;
using System.IO;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create our document object
            Document Doc = new Document(PageSize.LETTER);

            //Create our file stream
            using (FileStream fs = new FileStream(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "Test.pdf"), FileMode.Create, FileAccess.Write, FileShare.Read))
            {
                //Bind PDF writer to document and stream
                PdfWriter writer = PdfWriter.GetInstance(Doc, fs);

                //Open document for writing
                Doc.Open();

                //Add a page
                Doc.NewPage();

                //Full path to the Unicode Arial file
                string ARIALUNI_TFF = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), "ARIALUNI.TTF");

                //Create a base font object making sure to specify IDENTITY-H
                BaseFont bf = BaseFont.CreateFont(ARIALUNI_TFF, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);

                //Create a specific font object
                Font f = new Font(bf, 12, Font.NORMAL);

                //Write some text, the last character is 0x0278 - LATIN SMALL LETTER PHI
                Doc.Add(new Phrase("This is a test ɸ", f));

                //Write some more text, the last character is 0x0682 - ARABIC LETTER HAH WITH TWO DOTS VERTICAL ABOVE
                Doc.Add(new Phrase("Hello\u0682", f));

                //Close the PDF
                Doc.Close();
            }
        }
    }
}

使用iTextSharp时,您必须确保使用的字体支持您要使用的Unicode代码点。使用字体时,还需要指定IDENTITY-H。我不完全知道这意味着什么,但在这里有一些讨论:iTextSharp international text