none
调用虚拟打印机生成pdf时失败 RRS feed

  • 问题

  • 调用PrintForm()的时候报如下错误:

    12:41:46.298 [WorflowThread] {DEBUG} [Action] - PrintForm:8
    12:41:46.298 [WorflowThread] {DEBUG} [Action] - PrintForm:9
    12:41:46.480 [WorflowThread] {ERROR} [Action] - I/O error when opening file 'C:\WINDOWS\FONTS\MSYHBD.TTF'.
    System.IO.IOException: I/O error when opening file 'C:\WINDOWS\FONTS\MSYHBD.TTF'.
       at MS.Internal.FontCache.FileMapping.OpenFile(String fileName)
       at MS.Internal.FontCache.FontSource.GetStream()
       at System.Windows.Media.GlyphTypeface.GetFontStream()
       at Microsoft.Internal.GDIExporter.FontStreamContext.GetStream()
       at Microsoft.Internal.GDIExporter.FontStreamContext.UpdateStreamLength()
       at Microsoft.Internal.GDIExporter.FontInstallInfo.Install(FontStreamContext context, String& newFamilyName, UInt32 faceIndex)
       at Microsoft.Internal.GDIExporter.FontInfo.UsePrivate(GlyphTypeface typeface)
       at Microsoft.Internal.GDIExporter.CGDIDevice.CheckFont(GlyphTypeface typeface, String name)
       at Microsoft.Internal.GDIExporter.CGDIRenderTarget.CreateFontW(GlyphRun pGlyphRun, Double fontSize, Double scaleY)
       at Microsoft.Internal.GDIExporter.CGDIRenderTarget.RenderTextThroughGDI(GlyphRun pGlyphRun, Brush pBrush)
       at Microsoft.Internal.GDIExporter.CGDIRenderTarget.DrawGlyphRun(Brush pBrush, GlyphRun glyphRun)
       at Microsoft.Internal.AlphaFlattener.BrushProxyDecomposer.Microsoft.Internal.AlphaFlattener.IProxyDrawingContext.DrawGlyphs(GlyphRun glyphrun, Geometry clip, Matrix trans, BrushProxy foreground)
       at Microsoft.Internal.AlphaFlattener.PrimitiveRenderer.DrawGlyphs(GlyphRun glyphrun, Rect bounds, Matrix trans, String desp)
       at Microsoft.Internal.AlphaFlattener.Flattener.AlphaRender(Primitive primitive, List`1 overlapping, Int32 overlapHasTransparency, Boolean disjoint, String desp)
       at Microsoft.Internal.AlphaFlattener.Flattener.AlphaFlatten(IProxyDrawingContext dc, Boolean disjoint)
       at Microsoft.Internal.AlphaFlattener.Flattener.Convert(Primitive tree, ILegacyDevice dc, Double width, Double height, Double dpix, Double dpiy, Nullable`1 quality)
       at Microsoft.Internal.AlphaFlattener.MetroDevice0.FlushPage(ILegacyDevice sink, Double width, Double height, Nullable`1 outputQuality)
       at Microsoft.Internal.AlphaFlattener.MetroToGdiConverter.FlushPage()
       at System.Windows.Xps.Serialization.NgcSerializationManager.EndPage()
       at System.Windows.Xps.Serialization.NgcDocumentPageSerializer.SerializeObject(Object serializedObject)
       at System.Windows.Xps.Serialization.NgcDocumentPaginatorSerializer.SerializeObject(Object serializedObject)
       at System.Windows.Xps.Serialization.NgcSerializationManager.SaveAsXaml(Object serializedObject)
       at System.Windows.Xps.XpsDocumentWriter.SaveAsXaml(Object serializedObject, Boolean isSync)
       at System.Windows.Xps.XpsDocumentWriter.Write(DocumentPaginator documentPaginator)
       at System.Windows.Controls.PrintDialog.PrintDocument(DocumentPaginator documentPaginator, String description)
       at VTMBusinessActivity.ApplicationFormHelper`1.PrintForm()
    12:41:46.684 [WorflowThread] {DEBUG} [Action] - PringForm Fail

    代码文件如下:

    /// <summary>
        /// 打印申请单帮助类
        /// </summary>
        /// <typeparam name="T"></typeparam>
        public class ApplicationFormHelper<T>
        {
            #region Fields
            private String templatePath = string.Empty;
            private T ApplicationiForm = default(T);
            #endregion

            #region Constructors
            public ApplicationFormHelper(T form, string templateName)
            {
                templatePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "PrintTemplate\\" + templateName + ".xaml");//CcbApplicationForm.xaml");
                ApplicationiForm = form;
            }
            #endregion

            #region Methods

            /// <summary>
            /// 打印申请单
            /// </summary>
            public bool PrintForm()
            {
                try
                {
                    Log.Action.LogDebugFormat("PrintForm:1");
                    string strXaml = string.Empty;

                    using (FileStream fs = new FileStream(templatePath, FileMode.Open, FileAccess.Read))
                    {
                        Log.Action.LogDebugFormat("PrintForm:2");
                        StreamReader reader = new StreamReader(fs, System.Text.Encoding.GetEncoding("UTF-8"));
                        strXaml = reader.ReadToEnd();
                        Log.Action.LogDebugFormat("PrintForm:3");
                    }
                    Log.Action.LogDebugFormat("PrintForm:4");
                    ParserContext pc = new ParserContext();
                    pc.XamlTypeMapper = new XamlTypeMapper(new string[] { });
                    pc.XamlTypeMapper.AddMappingProcessingInstruction("http://schemas.microsoft.com/expression/2010/drawing", "Microsoft.Expression.Controls", "Microsoft.Expression.Drawing");
                    pc.XmlnsDictionary.Add("ed", "http://schemas.microsoft.com/expression/2010/drawing");
                    Log.Action.LogDebugFormat("PrintForm:5");
                    strXaml = SetValue(strXaml);
                    Log.Action.LogDebugFormat("PrintForm:6");
                    FlowDocument doc = (FlowDocument)System.Windows.Markup.XamlReader.Load(new MemoryStream(Encoding.UTF8.GetBytes(strXaml)), pc);
                    Log.Action.LogDebugFormat("PrintForm:7");
                    if (null != doc)
                    {
                        Log.Action.LogDebugFormat("PrintForm:8");
                        PrintDialog pd = new PrintDialog();
                        Log.Action.LogDebugFormat("PrintForm:9");
                        pd.PrintDocument(((IDocumentPaginatorSource)doc).DocumentPaginator, "ApplicationForm");
                        Log.Action.LogDebugFormat("PrintForm:10");
                    }
                    return true;
                }
                catch (Exception ex)
                {
                    Log.Action.LogError(ex.Message,ex);
                    return false;
                }

            }

            /// <summary>
            /// 将指定字符串替换为T中的属性,并设置值
            /// </summary>
            /// <param name="strXaml">模板内容</param>
            /// <returns></returns>
            private string SetValue(string strXaml)
            {
                List<PropertyInfo> propeties = typeof(T).GetProperties().ToList();
                for (int i = 0; i < propeties.Count; i++)
                {
                    if (propeties[i].PropertyType.Equals(typeof(string)))
                    {
                        strXaml = strXaml.Replace("@str_" + propeties[i].Name, propeties[i].GetValue(this.ApplicationiForm, null) == null ? "" : propeties[i].GetValue(this.ApplicationiForm, null).ToString());
                    }
                    else if (propeties[i].PropertyType.Equals(typeof(bool)))
                    {
                        Log.Action.LogDebugFormat("当前属性名称:{0}",propeties[i].Name);
                        strXaml = strXaml.Replace("@ckb_" + propeties[i].Name, "IsChecked=\"" + (propeties[i].GetValue(this.ApplicationiForm, null) == null ? "" : propeties[i].GetValue(this.ApplicationiForm, null).ToString()) + "\"");
                    }
                    else if (propeties[i].PropertyType.Equals(typeof(ImageSource)))
                    {
                        strXaml = strXaml.Replace("@img_" + propeties[i].Name, "Source=\"" + (propeties[i].GetValue(this.ApplicationiForm, null) == null ? "" : propeties[i].GetValue(this.ApplicationiForm, null).ToString()) + "\"");
                    }
                    //成功发卡或发网银盾
                    else if (propeties[i] != null && propeties[i].PropertyType.Equals(typeof(List<TwinScreenPrintDetail>)) && propeties[i].Name == "PrintSuccessDetail")
                    {
                        Log.Action.LogDebug("Print SuccessCardAndUkey detail");
                        StringBuilder str = new StringBuilder();
                        if (propeties[i].GetValue(this.ApplicationiForm, null) != null)
                        {
                            foreach (TwinScreenPrintDetail detail in propeties[i].GetValue(this.ApplicationiForm, null) as List<TwinScreenPrintDetail>)
                            {
                                if (detail != null)
                                {
                                    string rowTemplate = "<TableRow>" +
                         "<TableCell ><Paragraph TextAlignment=\"Center\" Margin=\"5,2,5,2\"><Run>@CardNumber</Run> </Paragraph></TableCell>" +
                         "<TableCell><Paragraph TextAlignment=\"Center\" Margin=\"5,2,5,2\"><Run>@CustmerName</Run></Paragraph></TableCell>" +
                         "<TableCell><Paragraph TextAlignment=\"Center\"  Margin=\"5,2,5,2\"><Run>@CustmerID</Run></Paragraph></TableCell>" +
                         "<TableCell><Paragraph TextAlignment=\"Center\" Margin=\"5,2,5,2\"><Run>@CustmerPhone</Run></Paragraph></TableCell>" +
                         "<TableCell><Paragraph TextAlignment=\"Center\"  Margin=\"5,2,5,2\"><Run>@CustomerAddFlag</Run></Paragraph></TableCell>" +
                         "<TableCell><Paragraph TextAlignment=\"Center\"  Margin=\"5,2,5,2\"><Run>@CustomerReviseContent</Run></Paragraph></TableCell>" +
                         "<TableCell><Paragraph TextAlignment=\"Center\"  Margin=\"0,2,0,2\"><Run>@Date</Run></Paragraph></TableCell>" +
                         "</TableRow>";
                                    rowTemplate = rowTemplate.Replace("@CardNumber", detail.CardNumber);
                                    rowTemplate = rowTemplate.Replace("@CustmerName", detail.CustomerName);
                                    rowTemplate = rowTemplate.Replace("@CustmerID", detail.CustomerID);
                                    rowTemplate = rowTemplate.Replace("@CustmerPhone", detail.CustomerPhone);
                                    rowTemplate = rowTemplate.Replace("@CustomerAddFlag", detail.CustomerAddFlag);
                                    rowTemplate = rowTemplate.Replace("@CustomerReviseContent", detail.CustomerReviseContent);
                                    rowTemplate = rowTemplate.Replace("@Date", detail.CreateDate);
                                    str.Append(rowTemplate);
                                }
                            }
                        }
                        Log.Action.LogDebug("SuccessCardAndUkey:" + str.ToString());
                        strXaml = strXaml.Replace("@list_SuccessCardAndUkey", str.ToString());
                    }
                    //失败发卡或发网银盾
                    else if (propeties[i] != null && propeties[i].PropertyType.Equals(typeof(List<TwinScreenPrintDetail>)) && propeties[i].Name == "PrintFailedDetail")
                    {
                        Log.Action.LogDebug("Print FailedCardAndUkey detail");
                        StringBuilder str = new StringBuilder();
                        if (propeties[i].GetValue(this.ApplicationiForm, null) != null)
                        {
                            foreach (TwinScreenPrintDetail detail in propeties[i].GetValue(this.ApplicationiForm, null) as List<TwinScreenPrintDetail>)
                            {
                                if (detail != null)
                                {
                                    string rowTemplate = "<TableRow>" +
                         "<TableCell ><Paragraph TextAlignment=\"Center\" Margin=\"5,2,5,2\"><Run>@CardNumber</Run> </Paragraph></TableCell>" +
                         "<TableCell><Paragraph TextAlignment=\"Center\" Margin=\"5,2,5,2\"><Run>@CustmerName</Run></Paragraph></TableCell>" +
                         "<TableCell><Paragraph TextAlignment=\"Center\"  Margin=\"5,2,5,2\"><Run>@CustmerID</Run></Paragraph></TableCell>" +
                         "<TableCell><Paragraph TextAlignment=\"Center\" Margin=\"5,2,5,2\"><Run>@CustmerPhone</Run></Paragraph></TableCell>" +
                         "<TableCell><Paragraph TextAlignment=\"Center\"  Margin=\"0,2,0,2\"><Run>@Date</Run></Paragraph></TableCell>" +
                         "</TableRow>";
                                    rowTemplate = rowTemplate.Replace("@CardNumber", detail.CardNumber);
                                    rowTemplate = rowTemplate.Replace("@CustmerName", detail.CustomerName);
                                    rowTemplate = rowTemplate.Replace("@CustmerID", detail.CustomerID);
                                    rowTemplate = rowTemplate.Replace("@CustmerPhone", detail.CustomerPhone);
                                    rowTemplate = rowTemplate.Replace("@Date", detail.CreateDate);
                                    str.Append(rowTemplate);
                                }
                            }
                        }
                        Log.Action.LogDebug("FailedCardAndUkey:" + str.ToString());
                        strXaml = strXaml.Replace("@list_FailedCardAndUkey", str.ToString());
                    }
                    //吞客户卡
                    else if (propeties[i] != null && propeties[i].PropertyType.Equals(typeof(List<TwinScreenPrintDetail>)) && propeties[i].Name == "PrintCaptureDetail")
                    {
                        Log.Action.LogDebug("Print CaptureCard detail");
                        StringBuilder str = new StringBuilder();
                        if (propeties[i].GetValue(this.ApplicationiForm, null) != null)
                        {
                            if ((propeties[i].GetValue(this.ApplicationiForm, null) as List<TwinScreenPrintDetail>).Count > 0)
                            {
                                string rowHeader = "<Section Padding=\"15,0,15,0\" FontSize=\"12\"><Paragraph><Run>吞卡明细:</Run></Paragraph>" +
                    "<Table CellSpacing=\"0\" BorderBrush=\"Black\" FontFamily=\"Microsoft YaHei\" BorderThickness=\"0.01cm\">" +
                       "<Table.Resources><Style TargetType=\"{x:Type TableCell}\"><Setter Property=\"FontFamily\" Value=\"icrosoft YaHei\" />" +
                            "<Setter Property=\"BorderBrush\" Value=\"Black\"/>" +
                            "<Setter Property=\"BorderThickness\" Value=\"0.008cm\"/>" +
                            "<Setter Property=\"FontSize\" Value=\"12\"/>" +
                            "<Setter Property=\"Foreground\" Value=\"#484747\" /></Style> </Table.Resources>" +
                    "<Table.Columns><TableColumn Width=\"0.4*\" /><TableColumn Width=\"*\" /> </Table.Columns><TableRowGroup>" +
                    "<TableRow><TableCell ><Paragraph TextAlignment=\"Center\" Margin=\"0,5,5,0\"><Run>卡号</Run></Paragraph></TableCell><TableCell>" +
                        "<Paragraph TextAlignment=\"Center\"  Margin=\"0,5,5,0\"> <Run>操作时间</Run> </Paragraph></TableCell></TableRow>";
                                str.Append(rowHeader);

                                foreach (TwinScreenPrintDetail detail in propeties[i].GetValue(this.ApplicationiForm, null) as List<TwinScreenPrintDetail>)
                                {
                                    if (detail != null)
                                    {
                                        string rowTemplate = "<TableRow>" +
                             "<TableCell ><Paragraph TextAlignment=\"Center\" Margin=\"5,2,5,2\"><Run>@CardNumber</Run> </Paragraph></TableCell>" +
                             "<TableCell><Paragraph TextAlignment=\"Center\"  Margin=\"0,2,0,2\"><Run>@Date</Run></Paragraph></TableCell>" +
                             "</TableRow>";
                                        rowTemplate = rowTemplate.Replace("@CardNumber", detail.CardNumber);
                                        rowTemplate = rowTemplate.Replace("@Date", detail.CreateDate);
                                        str.Append(rowTemplate);
                                    }
                                }
                                string rowFooter = "</TableRowGroup> </Table></Section>";
                                str.Append(rowFooter);
                            }
                        }
                        Log.Action.LogDebug("CaptureCard:" + str.ToString());
                        strXaml = strXaml.Replace("@list_CaptureCard", str.ToString());
                    }
                }
                return strXaml;
            }
            #endregion
        }

    2015年7月10日 6:51

答案

  • Hi wfoolish,

    >>"System.IO.IOException: I/O error when opening file 'C:\WINDOWS\FONTS\MSYHBD.TTF'."

    我看了下你的代码,没有发现哪里有问题,但是我根据你的异常信息,我觉得是你的windows字体库里没有这个“MSYHBD”的字体文件存在,你可以检查一下“'C:\WINDOWS\FONTS”这个文件夹里有没有那个文件存在,其次你不一定要直接打印出来,你可以本地先检测一下,你根据xaml模板生成的表格是否正确,你可以将FlowDocument 显示在DocumentView控件中,比如:

    <StackPanel>
            <DocumentViewer x:Name="documentView">
                
            </DocumentViewer>
            
        </StackPanel>
    documentView.Document = yourDoc;

    希望我的回答对你有帮助.

    Best Regards,

    Xavier Eoro


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.

    2015年7月14日 3:18
    版主