使用Xamarin中的iTextSharp生成PDF(Unicode,俄语)

时间:2018-03-13 12:37:01

标签: android pdf xamarin itext

我尝试生成PDF。拉丁字母显示功能正确,但俄罗斯根本没有显示。 这是我的功能。这里有什么问题?

 public string CreatePDFfromHTML(
            string htmlText
            , string fileName
            , InvoiceData _invoiceData
            , int Pages
            , bool OpenPDF = true
            , bool landscape = false)
        {
            Document document = null;
            FileStream file = null;
            Uri uri = null;

            try
            {
                var directory = new Java.IO.File(
                    Environment.GetExternalStoragePublicDirectory(Environment.DirectoryDcim), "pdf").ToString();

                if (!Directory.Exists(directory))
                    Directory.CreateDirectory(directory);

                var absoluteFilePath = System.IO.Path.Combine(directory, fileName);

                if (System.IO.File.Exists(absoluteFilePath))
                    System.IO.File.Delete(absoluteFilePath);

                file = System.IO.File.Create(absoluteFilePath);

                if (landscape)
                    document = new Document(PageSize.A4.Rotate(), 30, 20, 20, 60);
                else
                    document = new Document(PageSize.A4, 30, 20, 40, 60);

                PdfWriter _writer = PdfWriter.GetInstance(document, file);
                HeaderFooterPageEvent _event = new HeaderFooterPageEvent(_invoiceData, Pages);
                _writer.PageEvent = _event;

                document.Open();

                string FontPath = "arialunicodems.ttf#arialunicodems";
                XMLWorkerFontProvider fontImp = new XMLWorkerFontProvider(XMLWorkerFontProvider.DONTLOOKFORFONTS);
                fontImp.Register(FontPath);
                FontFactory.FontImp = fontImp;

                byte[] byteArray = Encoding.UTF8.GetBytes(htmlText);
                Stream htmlInputStream = new MemoryStream(byteArray,true);

                XMLWorkerHelper.GetInstance().ParseXHtml(_writer, document, htmlInputStream, null, Encoding.UTF8, fontImp);

                document.Close();
                file.Close();

                uri = Uri.Parse("file:///" + absoluteFilePath);

                if (OpenPDF)
                {
                    Intent intent = new Intent(Intent.ActionView);
                    intent.SetDataAndType(uri, "application/pdf");
                    intent.SetFlags(ActivityFlags.ClearTask | ActivityFlags.NewTask);
                    Forms.Context.StartActivity(intent);
                }

                return absoluteFilePath;
            }
            catch (Exception e)
            {
                UserDialogs.Instance.AlertAsync("CreatePDFfromHTML: " + e.Message + "'", AppResources.error);
                e.PrintStackTrace();
                document.Close();
                file.Close();
            }
            catch (System.Exception e)
            {
                UserDialogs.Instance.AlertAsync("CreatePDFfromHTML: " + e.Message + "'", AppResources.error);
                document.Close();
                file.Close();
            }
            return null;
        }

1 个答案:

答案 0 :(得分:0)

解决:

步骤1:在Android项目中,我在本地保存了字体文件并确定了位置,例如:

public string ExportFontFileToSDCard(string FontFileName)
    {
        string _sdcard_directory = null;

        try
        {
            _sdcard_directory = Environment.GetExternalStoragePublicDirectory(Environment.DirectoryDcim) +
                            Java.IO.File.Separator + "MyDirName" +
                            Java.IO.File.Separator ;

            if (!Directory.Exists(_sdcard_directory))
                Directory.CreateDirectory(_sdcard_directory);

            string _target_file = System.IO.Path.Combine(_sdcard_directory, FontFileName);

            if (!File.Exists(_target_file))
            {
                var input = m_assets.Open(FontFileName);
                File.WriteAllBytes(_target_file, StreamToByteArray(input));
            }

            return _target_file;
        }
        catch (Java.IO.IOException e)
        {
            UserDialogs.Instance.AlertAsync(e.Message, AppResources.error);
            e.PrintStackTrace();

            return null;
        }
        catch (Exception e)
        {
            UserDialogs.Instance.AlertAsync(e.Message, AppResources.error);
            e.PrintStackTrace();

            return null;
        }
    }

步骤2:使用DependencyService PCL-Project:

public static string ExportFontFileToSDCard()
    {
        string _localDBPath = DependencyService.Get<IFileHelper>().GetLocalFilePath(m_unicode_font_file_name);
        return DependencyService.Get<IFileUtility>().ExportFontFileToSDCard(m_unicode_font_file_name);
    }

步骤3:实现您自己从FontFactoryImp类派生的

 public class UnicodeFontFactory : FontFactoryImp
{
    private static readonly string FontPath = App.ExportFontFileToSDCard();
    private readonly BaseFont _baseFont;

    public UnicodeFontFactory()
    {
        _baseFont = BaseFont.CreateFont(FontPath, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
    }

    public override iTextSharp.text.Font GetFont(
        string fontname, 
        string encoding, 
        bool embedded, 
        float size, 
        int style, 
        BaseColor color,
        bool cached)
    {
        iTextSharp.text.Font _font = FontFactory.GetFont(FontPath, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
        _font.Size = size;
        _font.Color = color;

        return _font;
    }
}

第4步:使用此课程:

        public string CreatePDFfromHTML(
        string htmlText
        , string fileName
        , InvoiceData _invoiceData
        , int Pages
        , bool OpenPDF = true
        , bool landscape = false)
    {
        Document document = null;
        FileStream file = null;
        Uri uri = null;

        try
        {
            var directory = new Java.IO.File(Environment.GetExternalStoragePublicDirectory(Environment.DirectoryDcim), "pdf").ToString();

            if (!Directory.Exists(directory))
                Directory.CreateDirectory(directory);

            var absoluteFilePath = System.IO.Path.Combine(directory, fileName);

            if (System.IO.File.Exists(absoluteFilePath))
                System.IO.File.Delete(absoluteFilePath);

            file = System.IO.File.Create(absoluteFilePath);

            if (landscape)
                document = new Document(PageSize.A4.Rotate(), 30, 20, 20, 60);
            else
                document = new Document(PageSize.A4, 30, 20, 40, 60);

            PdfWriter _writer = PdfWriter.GetInstance(document, file);
            HeaderFooterPageEvent _event = new HeaderFooterPageEvent(_invoiceData, Pages);
            _writer.PageEvent = _event;

            document.Open();

            //string FONTDIR = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
            //string _font_file = System.IO.Path.Combine(FONTDIR, "ArialUnicodeMS.ttf");
            //string FONTDIR_ASSETS = System.IO.Path.Combine(System.Environment.GetFolderPath
            //    (System.Environment.SpecialFolder.Personal), "Assets");
            //string _font_file_ass = System.IO.Path.Combine(FONTDIR_ASSETS, "ArialUnicodeMS.ttf");

            var worker = XMLWorkerHelper.GetInstance();
            byte[] byteArray = Encoding.UTF8.GetBytes(htmlText);
            Stream htmlInputStream = new MemoryStream(byteArray);

            // CSS
            byte[] _css_arr = Encoding.UTF8.GetBytes(m_css);
            Stream _css_arr_stream = new MemoryStream(_css_arr, true);

            worker.ParseXHtml(_writer, document, htmlInputStream, _css_arr_stream, null, new UnicodeFontFactory());

            document.Close();
            file.Close();

            uri = Uri.Parse("file:///" + absoluteFilePath);

            if (OpenPDF)
            {
                Intent intent = new Intent(Intent.ActionView);
                intent.SetDataAndType(uri, "application/pdf");
                intent.SetFlags(ActivityFlags.ClearTask | ActivityFlags.NewTask);
                Forms.Context.StartActivity(intent);
            }

            return absoluteFilePath;
        }
        catch (Exception e)
        {
            UserDialogs.Instance.AlertAsync("CreatePDFfromHTML: " + e.Message + "'", AppResources.error);
            e.PrintStackTrace();
            document.Close();
            file.Close();
        }
        catch (System.Exception e)
        {
            UserDialogs.Instance.AlertAsync("CreatePDFfromHTML: " + e.Message + "'", AppResources.error);
            document.Close();
            file.Close();
        }
        return null;
    }