/// <summary>Adds the destination.</summary> /// <param name="tagWorker">the tag worker</param> /// <param name="element">the element</param> /// <returns>the outline handler</returns> internal virtual OutlineHandler AddDestination(ITagWorker tagWorker, IElementNode element) { String tagName = element.Name(); if (null != tagWorker && HasTagPriorityMapping(tagName) && destinationsInProcess.Count > 0) { String content = destinationsInProcess.JRemoveFirst(); if (tagWorker.GetElementResult() is IElement) { tagWorker.GetElementResult().SetProperty(Property.DESTINATION, content); } else { ILog logger = LogManager.GetLogger(typeof(OutlineHandler)); logger.Warn(MessageFormatUtil.Format(iText.Html2pdf.LogMessageConstant.NO_IPROPERTYCONTAINER_RESULT_FOR_THE_TAG , tagName)); } } return(this); }
public object CreateFromParameterizedConstructor(Type nodeType, IElementNode node) { var ctorInfo = nodeType.GetTypeInfo() .DeclaredConstructors.FirstOrDefault( ci => ci.GetParameters().Length != 0 && ci.IsPublic && ci.GetParameters().All(pi => pi.CustomAttributes.Any(attr => attr.AttributeType == typeof(ParameterAttribute)))); object[] arguments = CreateArgumentsArray(node, ctorInfo); if (arguments != null) { return(ctorInfo?.Invoke(arguments)); } else { return(null); } }
/* (non-Javadoc) * @see com.itextpdf.html2pdf.css.apply.ICssApplierFactory#getCssApplier(com.itextpdf.html2pdf.html.node.IElementNode) */ public ICssApplier GetCssApplier(IElementNode tag) { ICssApplier cssApplier = GetCustomCssApplier(tag); if (cssApplier == null) { Type cssApplierClass = GetCssApplierClass(defaultMapping, tag); if (cssApplierClass != null) { try { return((ICssApplier)System.Activator.CreateInstance(cssApplierClass)); } catch (Exception) { throw new CssApplierInitializationException(CssApplierInitializationException.ReflectionFailed, cssApplierClass .FullName, tag.Name()); } } } return(cssApplier); }
/// <summary>Applies paddings to the table's cells.</summary> /// <param name="node">the node</param> /// <param name="paddingStyle">cellpadding</param> private static void ApplyPaddingsToTableCells(INode node, IDictionary <String, String> paddingStyle) { IList <INode> nodes = node.ChildNodes(); foreach (INode childNode in nodes) { if (childNode is IElementNode) { IElementNode elementNode = (IElementNode)childNode; if (TagConstants.TD.Equals(elementNode.Name()) || TagConstants.TH.Equals(elementNode.Name())) { elementNode.AddAdditionalHtmlStyles(paddingStyle); } else { ApplyPaddingsToTableCells(childNode, paddingStyle); } } } }
/// <summary> /// Creates a new /// <see cref="PageCountWorker"/> /// instance. /// </summary> /// <param name="element">the element</param> /// <param name="context">the context</param> public PageCountWorker(IElementNode element, ProcessorContext context) : base(element, context) { if (element is PageCountElementNode) { CounterDigitsGlyphStyle digitsStyle = ((PageCountElementNode)element).GetDigitsGlyphStyle(); if (element is PageTargetCountElementNode) { pageCountElement = new PageTargetCountElement(((PageTargetCountElementNode)element).GetTarget(), digitsStyle ); } else { bool totalPageCount = ((PageCountElementNode)element).IsTotalPageCount(); pageCountElement = new PageCountElement(digitsStyle); pageCountElement.SetProperty(Html2PdfProperty.PAGE_COUNT_TYPE, totalPageCount ? PageCountType.TOTAL_PAGE_COUNT : PageCountType.CURRENT_PAGE_NUMBER); } } }
/// <summary> /// Creates a new /// <see cref="ImgTagWorker"/> /// instance. /// </summary> /// <param name="element">the element</param> /// <param name="context">the context</param> public ImgTagWorker(IElementNode element, ProcessorContext context) { String src = element.GetAttribute(AttributeConstants.SRC); PdfXObject imageXObject = context.GetResourceResolver().RetrieveImageExtended(src); if (imageXObject != null) { if (imageXObject is PdfImageXObject) { image = new ImgTagWorker.HtmlImage((PdfImageXObject)imageXObject); } else { if (imageXObject is PdfFormXObject) { image = new ImgTagWorker.HtmlImage((PdfFormXObject)imageXObject); } else { throw new InvalidOperationException(); } } } display = element.GetStyles() != null?element.GetStyles().Get(CssConstants.DISPLAY) : null; // TODO this is a workaround for now Imgto that image is not added as inline if (element.GetStyles() != null && CssConstants.ABSOLUTE.Equals(element.GetStyles().Get(CssConstants.POSITION ))) { display = CssConstants.BLOCK; } if (image != null) { String altText = element.GetAttribute(AttributeConstants.ALT); if (altText != null) { image.GetAccessibilityProperties().SetAlternateDescription(altText); } AccessiblePropHelper.TrySetLangAttribute(image, element); } }
public IEnumerable <Instruction> ProvideValue(IElementNode node, ModuleDefinition module, ILContext context, out TypeReference memberRef) { memberRef = module.ImportReferenceCached(typeof(Type)); INode typeNameNode; var name = new XmlName("", "TypeName"); if (!node.Properties.TryGetValue(name, out typeNameNode) && node.CollectionItems.Any()) { typeNameNode = node.CollectionItems[0]; } var valueNode = typeNameNode as ValueNode; if (valueNode == null) { throw new XamlParseException("TypeName isn't set.", node as XmlLineInfo); } if (!node.Properties.ContainsKey(name)) { node.Properties[name] = typeNameNode; node.CollectionItems.Clear(); } var typeref = module.ImportReference(XmlTypeExtensions.GetTypeReference(valueNode.Value as string, module, node as BaseNode)); if (typeref == null) { throw new XamlParseException($"Can't resolve type `{valueNode.Value}'.", node as IXmlLineInfo); } context.TypeExtensions[node] = typeref; var getTypeFromHandle = module.ImportReferenceCached(typeof(Type).GetMethod("GetTypeFromHandle", new[] { typeof(RuntimeTypeHandle) })); return(new List <Instruction> { Instruction.Create(OpCodes.Ldtoken, module.ImportReference(typeref)), Instruction.Create(OpCodes.Call, module.ImportReference(getTypeFromHandle)) }); }
// renders the given node to the internal ElementData dictionary. If the given node is // not a element, will recursively descend until we render its elements. private EffectIntents RenderNode(IElementNode node) { EffectIntents effectIntents = new EffectIntents(); var leafs = node.GetLeafEnumerator(); foreach (IElementNode elementNode in leafs) { if (HasDiscreteColors && IsElementDiscrete(elementNode)) { IEnumerable <Color> colors = ColorModule.getValidColorsForElementNode(elementNode, false); if (!colors.Contains(Color)) { continue; } } var intent = CreateIntent(leafs.First(), Color, IntensityLevel, TimeSpan); effectIntents.AddIntentForElement(elementNode.Element.Id, intent, TimeSpan.Zero); } return(effectIntents); }
public IEnumerable <Instruction> ProvideValue(IElementNode node, ModuleDefinition module, ILContext context, out TypeReference memberRef) { var typeNode = node.Properties[new XmlName("", "Type")] as IElementNode; var typeTypeRef = context.TypeExtensions[typeNode]; var n = node.CollectionItems.Count; var instructions = new List <Instruction>(); instructions.Add(Instruction.Create(OpCodes.Ldc_I4, n)); instructions.Add(Instruction.Create(OpCodes.Newarr, typeTypeRef)); memberRef = typeTypeRef.MakeArrayType(); for (var i = 0; i < n; i++) { instructions.Add(Instruction.Create(OpCodes.Dup)); instructions.Add(Instruction.Create(OpCodes.Ldc_I4, i)); instructions.Add(Instruction.Create(OpCodes.Ldloc, context.Variables[node.CollectionItems[i] as IElementNode])); instructions.Add(Instruction.Create(OpCodes.Stelem_Ref)); } return(instructions); }
public object CreateFromParameterizedConstructor(Type nodeType, IElementNode node) { var ctorInfo = nodeType.GetTypeInfo() .DeclaredConstructors.FirstOrDefault( ci => ci.GetParameters().Length != 0 && ci.IsPublic && ci.GetParameters().All(pi => pi.CustomAttributes.Any(attr => attr.AttributeType == typeof(ParameterAttribute)))); object[] arguments = CreateArgumentsArray(node, ctorInfo); try { return(ctorInfo.Invoke(arguments)); } catch (Exception e) when(e is TargetInvocationException || e is MissingMemberException) { return(XamlLoader.InstantiationFailedCallback?.Invoke(new XamlLoader.CallbackTypeInfo { XmlNamespace = node.XmlType.NamespaceUri, XmlTypeName = node.XmlType.Name }, nodeType, e) ?? throw e); } }
/// <summary> /// Creates a new /// <see cref="HtmlTagWorker"/> /// instance. /// </summary> /// <param name="element">the element</param> /// <param name="context">the context</param> public HtmlTagWorker(IElementNode element, ProcessorContext context) { bool immediateFlush = context.IsImmediateFlush() && !context.GetCssContext().IsPagesCounterPresent(); PdfDocument pdfDocument = context.GetPdfDocument(); document = new Document(pdfDocument, pdfDocument.GetDefaultPageSize(), immediateFlush); document.SetRenderer(new HtmlDocumentRenderer(document, immediateFlush)); document.SetProperty(Property.COLLAPSING_MARGINS, true); document.SetFontProvider(context.GetFontProvider()); if (context.GetTempFonts() != null) { document.SetProperty(Property.FONT_SET, context.GetTempFonts()); } String fontFamily = element.GetStyles().Get(CssConstants.FONT_FAMILY); // TODO DEVSIX-2534 IList <String> fontFamilies = FontFamilySplitter.SplitFontFamily(fontFamily); document.SetProperty(Property.FONT, fontFamilies.ToArray(new String[fontFamilies.Count])); inlineHelper = new WaitingInlineElementsHelper(element.GetStyles().Get(CssConstants.WHITE_SPACE), element. GetStyles().Get(CssConstants.TEXT_TRANSFORM)); }
protected EffectIntents CreateIntentsForElement(IElementNode element, double intensity, Color color, TimeSpan duration) { EffectIntents effectIntents = new EffectIntents(); foreach (IElementNode elementNode in element.GetLeafEnumerator()) { if (HasDiscreteColors && IsElementDiscrete(elementNode)) { IEnumerable <Color> colors = ColorModule.getValidColorsForElementNode(elementNode, false); if (!colors.Contains(color)) { continue; } } IIntent intent = CreateIntent(elementNode, color, intensity, duration); effectIntents.AddIntentForElement(elementNode.Element.Id, intent, TimeSpan.Zero); } return(effectIntents); }
/// <summary> /// Creates a new /// <see cref="TextAreaTagWorker"/> /// instance. /// </summary> /// <param name="element">the element</param> /// <param name="context">the context</param> public TextAreaTagWorker(IElementNode element, ProcessorContext context) { String name = element.GetAttribute(AttributeConstants.ID); if (name == null) { name = DEFAULT_TEXTAREA_NAME; } name = context.GetFormFieldNameResolver().ResolveFormName(name); textArea = new TextArea(name); int?rows = CssUtils.ParseInteger(element.GetAttribute(AttributeConstants.ROWS)); int?cols = CssUtils.ParseInteger(element.GetAttribute(AttributeConstants.COLS)); textArea.SetProperty(Html2PdfProperty.FORM_FIELD_ROWS, rows); textArea.SetProperty(Html2PdfProperty.FORM_FIELD_COLS, cols); textArea.SetProperty(Html2PdfProperty.FORM_FIELD_FLATTEN, !context.IsCreateAcroForm()); String placeholder = element.GetAttribute(AttributeConstants.PLACEHOLDER); if (null != placeholder) { Paragraph paragraph; if (String.IsNullOrEmpty(placeholder)) { paragraph = new Paragraph(); } else { if (String.IsNullOrEmpty(placeholder.Trim())) { paragraph = new Paragraph("\u00A0"); } else { paragraph = new Paragraph(placeholder); } } textArea.SetPlaceholder(paragraph.SetMargin(0)); } display = element.GetStyles() != null?element.GetStyles().Get(CssConstants.DISPLAY) : null; }
/// <summary>Creates a destination</summary> /// <param name="tagWorker">the tagworker that is building the (iText) element</param> /// <param name="element">the (HTML) element being converted</param> /// <param name="context">the Processor context</param> public static void CreateDestination(ITagWorker tagWorker, IElementNode element, ProcessorContext context) { String id = element.GetAttribute(AttributeConstants.ID); if (id == null) { return; } if (!context.GetLinkContext().IsUsedLinkDestination(id)) { return; } IPropertyContainer propertyContainer = null; if (tagWorker != null) { if (tagWorker is SpanTagWorker) { IList <IPropertyContainer> spanElements = ((SpanTagWorker)tagWorker).GetAllElements(); if (!spanElements.IsEmpty()) { propertyContainer = spanElements[0]; } } else { propertyContainer = tagWorker.GetElementResult(); } } if (propertyContainer == null) { ILog logger = LogManager.GetLogger(typeof(iText.Html2pdf.Attach.Util.LinkHelper)); String tagWorkerClassName = tagWorker != null?tagWorker.GetType().FullName : "null"; logger.Warn(MessageFormatUtil.Format(iText.Html2pdf.LogMessageConstant.ANCHOR_LINK_NOT_HANDLED, element.Name (), id, tagWorkerClassName)); return; } propertyContainer.SetProperty(Property.DESTINATION, id); }
public IEnumerable <Instruction> ProvideValue(IElementNode node, ModuleDefinition module, out TypeReference memberRef) { INode ntype; if (!node.Properties.TryGetValue(new XmlName("", "Member"), out ntype)) { ntype = node.CollectionItems [0]; } var member = ((ValueNode)ntype).Value as string; if (IsNullOrEmpty(member) || !member.Contains(".")) { var lineInfo = node as IXmlLineInfo; throw new XamlParseException("Syntax for x:Static is [Member=][prefix:]typeName.staticMemberName", lineInfo); } var dotIdx = member.LastIndexOf('.'); var typename = member.Substring(0, dotIdx); var membername = member.Substring(dotIdx + 1); var typeRef = GetTypeReference(typename, module, node); var fieldRef = GetFieldReference(typeRef, membername, module); var propertyDef = GetPropertyDefinition(typeRef, membername, module); if (fieldRef == null && propertyDef == null) { throw new XamlParseException(Format("x:Static: unable to find a public static field or property named {0} in {1}", membername, typename), node as IXmlLineInfo); } if (fieldRef != null) { memberRef = fieldRef.FieldType; return(new [] { Instruction.Create(OpCodes.Ldsfld, fieldRef) }); } memberRef = propertyDef.PropertyType; var getterDef = propertyDef.GetMethod; return(new [] { Instruction.Create(OpCodes.Call, getterDef) }); }
/* (non-Javadoc) * @see com.itextpdf.styledxmlparser.css.selector.item.ICssSelectorItem#matches(com.itextpdf.styledxmlparser.html.node.INode) */ public virtual bool Matches(INode node) { if (!(node is IElementNode) || node is ICustomElementNode || node is IDocumentNode) { return(false); } IElementNode element = (IElementNode)node; String classAttr = element.GetAttribute(CommonAttributeConstants.CLASS); if (classAttr != null && classAttr.Length > 0) { String[] classNames = iText.IO.Util.StringUtil.Split(classAttr, " "); foreach (String currClassName in classNames) { if (this.className.Equals(currClassName.Trim())) { return(true); } } } return(false); }
/// <summary> /// Creates a new /// <see cref="SelectTagWorker"/> /// instance. /// </summary> /// <param name="element">the element</param> /// <param name="context">the context</param> public SelectTagWorker(IElementNode element, ProcessorContext context) { String name = context.GetFormFieldNameResolver().ResolveFormName(element.GetAttribute(AttributeConstants.NAME )); bool multipleAttr = element.GetAttribute(AttributeConstants.MULTIPLE) != null; int? sizeAttr = CssDimensionParsingUtils.ParseInteger(element.GetAttribute(AttributeConstants.SIZE)); int size = GetSelectSize(sizeAttr, multipleAttr); if (size > 1 || multipleAttr) { selectElement = new ListBoxField(name, size, multipleAttr); } else { selectElement = new ComboBoxField(name); } String lang = element.GetAttribute(AttributeConstants.LANG); selectElement.SetProperty(Html2PdfProperty.FORM_ACCESSIBILITY_LANGUAGE, lang); selectElement.SetProperty(Html2PdfProperty.FORM_FIELD_FLATTEN, !context.IsCreateAcroForm()); display = element.GetStyles() != null?element.GetStyles().Get(CssConstants.DISPLAY) : null; }
public object[] CreateArgumentsArray(IElementNode enode, ConstructorInfo ctorInfo) { var n = ctorInfo.GetParameters().Length; var array = new object[n]; for (var i = 0; i < n; i++) { var parameter = ctorInfo.GetParameters()[i]; var propname = parameter.CustomAttributes.First(attr => attr.AttributeType == typeof(ParameterAttribute)) .ConstructorArguments.First() .Value as string; var name = new XmlName("", propname); INode node; if (!enode.Properties.TryGetValue(name, out node)) { String msg = ""; if (propname != null) { msg = String.Format("The Property {0} is required to create a {1} object.", propname, ctorInfo.DeclaringType.FullName); } else { msg = "propname is null."; } throw new XamlParseException(msg, enode as IXmlLineInfo); } if (!enode.SkipProperties.Contains(name)) { enode.SkipProperties.Add(name); } var value = Context.Values[node]; var serviceProvider = new XamlServiceProvider(enode, Context); var convertedValue = value.ConvertTo(parameter.ParameterType, () => parameter, serviceProvider); array[i] = convertedValue; } return(array); }
private ITagWorker ProcessRunningElement(ITagWorker tagWorker, IElementNode element, ProcessorContext context ) { String runningPrefix = CssConstants.RUNNING + "("; String positionVal; int endBracketInd; if (element.GetStyles() == null || (positionVal = element.GetStyles().Get(CssConstants.POSITION)) == null || !positionVal.StartsWith(runningPrefix) || // closing bracket should be there and there should be at least one symbol between brackets (endBracketInd = positionVal.IndexOf(")", StringComparison.Ordinal)) <= runningPrefix.Length) { return(tagWorker); } String runningElemName = positionVal.JSubstring(runningPrefix.Length, endBracketInd).Trim(); if (String.IsNullOrEmpty(runningElemName)) { return(tagWorker); } // TODO For now the whole ITagWorker of the running element is preserved inside RunningElementContainer // for the sake of future processing in page margin box. This is somewhat a workaround and storing // tag workers might be easily seen as something undesirable, however at least for now it seems to be // most suitable solution because: // - in any case, processing of the whole running element with it's children should be done in // "normal flow", i.e. in DefaultHtmlProcessor, based on the spec that says that element should be // processed as it was still in the same position in DOM, but visually as if "display: none" was set. // - the whole process would need to be repeated in PageContextProcessor again, so it's a double work; // also currently there is still no convenient way for unifying the processing here and in // PageContextProcessor, currently only running elements require processing of the whole hierarchy of // children outside of the default DOM processing and also it's unclear whether this code would be suitable // for the simplified approach of processing all other children of page margin boxes. // - ITagWorker is only publicly passed to the constructor, but there is no exposed way to get it out of // RunningElementContainer, so it would be fairly easy to change this approach in future if needed. RunningElementContainer runningElementContainer = new RunningElementContainer(element, tagWorker); context.GetCssContext().GetRunningManager().AddRunningElement(runningElemName, runningElementContainer); return(new RunningElementTagWorker(runningElementContainer)); }
/// <summary>Resolves node styles without inheritance of parent element styles.</summary> /// <param name="node">the node</param> /// <param name="cssContext">the CSS context (RootFontSize, etc.)</param> /// <returns>the map containing the resolved styles that are defined in the body of the element</returns> public virtual IDictionary <String, String> ResolveNativeStyles(INode node, AbstractCssContext cssContext) { IDictionary <String, String> styles = new Dictionary <String, String>(); // Load in from collected style sheets IList <CssDeclaration> styleSheetDeclarations = css.GetCssDeclarations(node, MediaDeviceDescription.CreateDefault ()); foreach (CssDeclaration ssd in styleSheetDeclarations) { styles.Put(ssd.GetProperty(), ssd.GetExpression()); } // Load in attributes declarations if (node is IElementNode) { IElementNode eNode = (IElementNode)node; foreach (IAttribute attr in eNode.GetAttributes()) { ProcessAttribute(attr, styles); } } return(styles); }
public QRCodeTagWorker(IElementNode tag, ProcessorContext context, string content) { var hints = new Dictionary <EncodeHintType, object>(); string charset = tag.GetAttribute("charset"); _content = content; if (CheckCharSet(charset)) { hints.Add(EncodeHintType.CHARACTER_SET, charset); } string errorCorrection = tag.GetAttribute("errorcorrection"); if (CheckErrorCorrectionAllowed(errorCorrection)) { ErrorCorrectionLevel errorCorrectionLevel = getErrorCorrectionLevel(errorCorrection); hints.Add(EncodeHintType.ERROR_CORRECTION, errorCorrectionLevel); } qrCode = new BarcodeQRCode("placeholder", hints); }
/// <summary>Recursively processes a node to preprocess target-counters.</summary> /// <param name="node">the node</param> private void VisitToProcessCounters(INode node) { if (node is IElementNode) { IElementNode element = (IElementNode)node; if (cssResolver is DefaultCssResolver) { ((DefaultCssResolver)cssResolver).ResolveContentAndCountersStyles(node, context.GetCssContext()); } CounterProcessorUtil.StartProcessingCounters(context.GetCssContext(), element); VisitToProcessCounters(CreatePseudoElement(element, null, CssConstants.BEFORE)); foreach (INode childNode in element.ChildNodes()) { if (!context.IsProcessingInlineSvg()) { VisitToProcessCounters(childNode); } } VisitToProcessCounters(CreatePseudoElement(element, null, CssConstants.AFTER)); CounterProcessorUtil.EndProcessingCounters(context.GetCssContext(), element); } }
public object CreateFromFactory(Type nodeType, IElementNode node) { object[] arguments = CreateArgumentsArray(node); if (!node.Properties.ContainsKey(XmlName.xFactoryMethod)) { //non-default ctor return(Activator.CreateInstance(nodeType, arguments)); } var factoryMethod = ((string)((ValueNode)node.Properties[XmlName.xFactoryMethod]).Value); Type[] types = arguments == null ? new Type[0] : arguments.Select(a => a.GetType()).ToArray(); var mi = nodeType.GetRuntimeMethod(factoryMethod, types); if (mi == null || !mi.IsStatic) { throw new MissingMemberException(String.Format("No static method found for {0}::{1} ({2})", nodeType.FullName, factoryMethod, string.Join(", ", types.Select(t => t.FullName)))); } return(mi.Invoke(null, arguments)); }
public override void ProcessEnd(IElementNode element, ProcessorContext context) { base.ProcessEnd(element, context); IPropertyContainer elementResult = base.GetElementResult(); if (elementResult is IAccessibleElement) { ((IAccessibleElement)elementResult).GetAccessibilityProperties().SetRole(StandardRoles.TH); if (context.GetPdfDocument() == null || context.GetPdfDocument().IsTagged()) { String scope = element.GetAttribute(AttributeConstants.SCOPE); AccessibilityProperties properties = ((IAccessibleElement)elementResult).GetAccessibilityProperties(); PdfDictionary attributes = new PdfDictionary(); attributes.Put(PdfName.O, PdfName.Table); if (scope != null && (AttributeConstants.ROW.EqualsIgnoreCase(scope) || AttributeConstants.ROWGROUP.EqualsIgnoreCase (scope))) { attributes.Put(PdfName.Scope, PdfName.Row); properties.AddAttributes(new PdfStructureAttributes(attributes)); } else { if (scope != null && (AttributeConstants.COL.EqualsIgnoreCase(scope) || AttributeConstants.COLGROUP.EqualsIgnoreCase (scope))) { attributes.Put(PdfName.Scope, PdfName.Column); properties.AddAttributes(new PdfStructureAttributes(attributes)); } else { ILog logger = LogManager.GetLogger(typeof(iText.Html2pdf.Attach.Impl.Tags.ThTagWorker)); logger.Warn(MessageFormatUtil.Format(iText.Html2pdf.LogMessageConstant.NOT_SUPPORTED_TH_SCOPE_TYPE, scope) ); } } } } }
public IEnumerable <Instruction> ProvideValue(IElementNode node, ModuleDefinition module, ILContext context, out TypeReference memberRef) { memberRef = module.ImportReference(("mscorlib", "System", "Type")); INode typeNameNode; var name = new XmlName("", "TypeName"); if (!node.Properties.TryGetValue(name, out typeNameNode) && node.CollectionItems.Any()) { typeNameNode = node.CollectionItems[0]; } var valueNode = typeNameNode as ValueNode; if (valueNode == null) { throw new XamlParseException("TypeName isn't set.", node as XmlLineInfo); } if (!node.Properties.ContainsKey(name)) { node.Properties[name] = typeNameNode; node.CollectionItems.Clear(); } var typeref = module.ImportReference(XmlTypeExtensions.GetTypeReference(valueNode.Value as string, module, node as BaseNode)); if (typeref == null) { throw new XamlParseException($"Can't resolve type `{valueNode.Value}'.", node as IXmlLineInfo); } context.TypeExtensions[node] = typeref; return(new List <Instruction> { Instruction.Create(OpCodes.Ldtoken, module.ImportReference(typeref)), Instruction.Create(OpCodes.Call, module.ImportMethodReference(("mscorlib", "System", "Type"), methodName: "GetTypeFromHandle", paramCount: 1, predicate: md => md.IsStatic)), });
public virtual ISvgProcessorResult Process(INode root, ISvgConverterProperties converterProps) { if (root == null) { throw new SvgProcessingException(SvgLogMessageConstant.INODEROOTISNULL); } if (converterProps == null) { converterProps = new SvgConverterProperties(); } //Setup processorState PerformSetup(root, converterProps); //Find root IElementNode svgRoot = FindFirstElement(root, SvgConstants.Tags.SVG); if (svgRoot != null) { //Iterate over children ExecuteDepthFirstTraversal(svgRoot); ISvgNodeRenderer rootSvgRenderer = CreateResultAndClean(); return new SvgProcessorResult(namedObjects, rootSvgRenderer, context.GetFontProvider(), context.GetTempFonts ()); } else { throw new SvgProcessingException(SvgLogMessageConstant.NOROOT); } }
/* (non-Javadoc) * @see com.itextpdf.html2pdf.css.resolve.HtmlStylesToCssConverter.IAttributeConverter#convert(com.itextpdf.styledxmlparser.html.node.IElementNode, java.lang.String) */ public virtual IList <CssDeclaration> Convert(IElementNode element, String value) { float?width = CssUtils.ParseFloat(value); if (width != null) { if (TagConstants.TABLE.Equals(element.Name()) && width != 0) { IList <CssDeclaration> declarations = new BorderShorthandResolver().ResolveShorthand("1px solid"); IDictionary <String, String> styles = new Dictionary <String, String>(declarations.Count); foreach (CssDeclaration declaration in declarations) { styles.Put(declaration.GetProperty(), declaration.GetExpression()); } ApplyBordersToTableCells(element, styles); } if (width >= 0) { return(JavaUtil.ArraysAsList(new CssDeclaration(CssConstants.BORDER, value + "px solid"))); } } return(JavaCollectionsUtil.EmptyList <CssDeclaration>()); }
/// <summary>Processes a pseudo element (before and after CSS).</summary> /// <param name="node">the node</param> /// <param name="pseudoElementName">the pseudo element name</param> private void VisitPseudoElement(IElementNode node, ITagWorker tagWorker, String pseudoElementName) { switch (pseudoElementName) { case CssConstants.BEFORE: case CssConstants.AFTER: if (!CssPseudoElementUtil.HasBeforeAfterElements(node)) { return; } break; case CssConstants.PLACEHOLDER: if (!(TagConstants.INPUT.Equals(node.Name()) || TagConstants.TEXTAREA.Equals(node.Name())) // TODO DEVSIX-1944: Resolve the issue and remove the line || null == tagWorker || !(tagWorker.GetElementResult() is IPlaceholderable) || null == ((IPlaceholderable) tagWorker.GetElementResult()).GetPlaceholder()) { return; } break; default: return; } Visit(new CssPseudoElementNode(node, pseudoElementName)); }
/* (non-Javadoc) * @see com.itextpdf.html2pdf.attach.impl.tags.DivTagWorker#processEnd(com.itextpdf.html2pdf.html.node.IElementNode, com.itextpdf.html2pdf.attach.ProcessorContext) */ public override void ProcessEnd(IElementNode element, ProcessorContext context) { base.ProcessEnd(element, context); String url = element.GetAttribute(AttributeConstants.HREF); if (url != null) { String @base = context.GetBaseUri(); if (@base != null) { UriResolver uriResolver = new UriResolver(@base); if (!(url.StartsWith("#") && uriResolver.IsLocalBaseUri())) { try { String resolvedUri = uriResolver.ResolveAgainstBaseUri(url).ToExternalForm(); if (!url.EndsWith("/") && resolvedUri.EndsWith("/")) { resolvedUri = resolvedUri.JSubstring(0, resolvedUri.Length - 1); } if (!resolvedUri.StartsWith("file:")) { url = resolvedUri; } } catch (UriFormatException) { } } } ((Div)GetElementResult()).GetAccessibilityProperties().SetRole(StandardRoles.LINK); LinkHelper.ApplyLinkAnnotation(GetElementResult(), url); } if (GetElementResult() != null) { String name = element.GetAttribute(AttributeConstants.NAME); GetElementResult().SetProperty(Property.DESTINATION, name); } }
/// <summary> /// Creates a new /// <see cref="ImgTagWorker"/> /// instance. /// </summary> /// <param name="element">the element</param> /// <param name="context">the context</param> public ObjectTagWorker(IElementNode element, ProcessorContext context) { this.processUtil = new SvgProcessingUtil(context.GetResourceResolver()); //Retrieve object type String type = element.GetAttribute(AttributeConstants.TYPE); if (IsSvgImage(type)) { String dataValue = element.GetAttribute(AttributeConstants.DATA); try { using (Stream svgStream = context.GetResourceResolver().RetrieveResourceAsInputStream(dataValue)) { if (svgStream != null) { SvgConverterProperties props = ContextMappingHelper.MapToSvgConverterProperties(context); if (!context.GetResourceResolver().IsDataSrc(dataValue)) { Uri fullURL = context.GetResourceResolver().ResolveAgainstBaseUri(dataValue); String dir = FileUtil.ParentDirectory(fullURL); props.SetBaseUri(dir); } res = SvgConverter.ParseAndProcess(svgStream, props); } } } catch (SvgProcessingException spe) { LOGGER.Error(spe.Message); } catch (System.IO.IOException ie) { LOGGER.Error(MessageFormatUtil.Format(iText.Html2pdf.LogMessageConstant.UNABLE_TO_RETRIEVE_STREAM_WITH_GIVEN_BASE_URI , context.GetBaseUri(), element.GetAttribute(AttributeConstants.DATA), ie)); } catch (UriFormatException ie) { LOGGER.Error(MessageFormatUtil.Format(iText.Html2pdf.LogMessageConstant.UNABLE_TO_RETRIEVE_STREAM_WITH_GIVEN_BASE_URI , context.GetBaseUri(), element.GetAttribute(AttributeConstants.DATA), ie)); } } }
public object[] CreateArgumentsArray(IElementNode enode) { if (!enode.Properties.ContainsKey(XmlName.xArguments)) return null; var node = enode.Properties[XmlName.xArguments]; var elementNode = node as ElementNode; if (elementNode != null) { var array = new object[1]; array[0] = Values[elementNode]; return array; } var listnode = node as ListNode; if (listnode != null) { var array = new object[listnode.CollectionItems.Count]; for (var i = 0; i < listnode.CollectionItems.Count; i++) array[i] = Values[(ElementNode)listnode.CollectionItems[i]]; return array; } return null; }
static void ParseXamlElementFor(IElementNode node, XmlReader reader) { Debug.Assert(reader.NodeType == XmlNodeType.Element); var elementName = reader.Name; var isEmpty = reader.IsEmptyElement; if (isEmpty) return; while (reader.Read()) { switch (reader.NodeType) { case XmlNodeType.EndElement: Debug.Assert(reader.Name == elementName); //make sure we close the right element return; case XmlNodeType.Element: // 1. Property Element. if (reader.Name.Contains(".")) { XmlName name; if (reader.Name.StartsWith(elementName + ".", StringComparison.Ordinal)) name = new XmlName(reader.NamespaceURI, reader.Name.Substring(elementName.Length + 1)); else //Attached DP name = new XmlName(reader.NamespaceURI, reader.LocalName); var prop = ReadNode(reader); if (prop != null) node.Properties.Add(name, prop); } // 2. Xaml2009 primitives, x:Arguments, ... else if (reader.NamespaceURI == "http://schemas.microsoft.com/winfx/2009/xaml" && reader.LocalName == "Arguments") { var prop = ReadNode(reader); if (prop != null) node.Properties.Add(XmlName.xArguments, prop); // 3. DataTemplate (should be handled by 4.) } else if (node.XmlType.NamespaceUri == "http://xamarin.com/schemas/2014/forms" && (node.XmlType.Name == "DataTemplate" || node.XmlType.Name == "ControlTemplate")) { var prop = ReadNode(reader, true); if (prop != null) node.Properties.Add(XmlName._CreateContent, prop); // 4. Implicit content, implicit collection, or collection syntax. Add to CollectionItems, resolve case later. } else { var item = ReadNode(reader, true); if (item != null) node.CollectionItems.Add(item); } break; case XmlNodeType.Whitespace: break; case XmlNodeType.Text: node.CollectionItems.Add(new ValueNode(reader.Value.Trim(), (IXmlNamespaceResolver)reader)); break; default: Debug.WriteLine("Unhandled node {0} {1} {2}", reader.NodeType, reader.Name, reader.Value); break; } } }
bool ValidateCtorArguments(Type nodeType, IElementNode node, out string missingArgName) { missingArgName = null; var ctorInfo = nodeType.GetTypeInfo() .DeclaredConstructors.FirstOrDefault( ci => ci.GetParameters().Length != 0 && ci.IsPublic && ci.GetParameters().All(pi => pi.CustomAttributes.Any(attr => attr.AttributeType == typeof (ParameterAttribute)))); if (ctorInfo == null) return true; foreach (var parameter in ctorInfo.GetParameters()) { var propname = parameter.CustomAttributes.First(ca => ca.AttributeType.FullName == "Xamarin.Forms.ParameterAttribute") .ConstructorArguments.First() .Value as string; if (!node.Properties.ContainsKey(new XmlName("", propname))) { missingArgName = propname; return false; } } return true; }
public object CreateFromParameterizedConstructor(Type nodeType, IElementNode node) { var ctorInfo = nodeType.GetTypeInfo() .DeclaredConstructors.FirstOrDefault( ci => ci.GetParameters().Length != 0 && ci.IsPublic && ci.GetParameters().All(pi => pi.CustomAttributes.Any(attr => attr.AttributeType == typeof (ParameterAttribute)))); object[] arguments = CreateArgumentsArray(node, ctorInfo); return ctorInfo.Invoke(arguments); }
public object CreateFromFactory(Type nodeType, IElementNode node) { object[] arguments = CreateArgumentsArray(node); if (!node.Properties.ContainsKey(XmlName.xFactoryMethod)) { //non-default ctor return Activator.CreateInstance(nodeType, arguments); } var factoryMethod = ((string)((ValueNode)node.Properties[XmlName.xFactoryMethod]).Value); Type[] types = arguments == null ? new Type[0] : arguments.Select(a => a.GetType()).ToArray(); var mi = nodeType.GetRuntimeMethod(factoryMethod, types); if (mi == null || !mi.IsStatic) { throw new MissingMemberException(String.Format("No static method found for {0}::{1} ({2})", nodeType.FullName, factoryMethod, string.Join(", ", types.Select(t => t.FullName)))); } return mi.Invoke(null, arguments); }
static void SetDataTemplate(IElementNode parentNode, ElementNode node, ILContext parentContext, IXmlLineInfo xmlLineInfo) { var parentVar = parentContext.Variables[parentNode]; //Push the DataTemplate to the stack, for setting the template parentContext.IL.Emit(OpCodes.Ldloc, parentVar); //Create nested class // .class nested private auto ansi sealed beforefieldinit '<Main>c__AnonStorey0' // extends [mscorlib]System.Object var module = parentContext.Body.Method.Module; var anonType = new TypeDefinition( null, "<" + parentContext.Body.Method.Name + ">_anonXamlCDataTemplate_" + dtcount++, TypeAttributes.BeforeFieldInit | TypeAttributes.Sealed | TypeAttributes.NestedPrivate) { BaseType = module.TypeSystem.Object }; parentContext.Body.Method.DeclaringType.NestedTypes.Add(anonType); var ctor = anonType.AddDefaultConstructor(); var loadTemplate = new MethodDefinition("LoadDataTemplate", MethodAttributes.Assembly | MethodAttributes.HideBySig, module.TypeSystem.Object); anonType.Methods.Add(loadTemplate); var parentValues = new FieldDefinition("parentValues", FieldAttributes.Assembly, module.Import(typeof (object[]))); anonType.Fields.Add(parentValues); TypeReference rootType = null; var vdefRoot = parentContext.Root as VariableDefinition; if (vdefRoot != null) rootType = vdefRoot.VariableType; var fdefRoot = parentContext.Root as FieldDefinition; if (fdefRoot != null) rootType = fdefRoot.FieldType; var root = new FieldDefinition("root", FieldAttributes.Assembly, rootType); anonType.Fields.Add(root); //Fill the loadTemplate Body var templateIl = loadTemplate.Body.GetILProcessor(); templateIl.Emit(OpCodes.Nop); var templateContext = new ILContext(templateIl, loadTemplate.Body, parentValues) { Root = root }; node.Accept(new CreateObjectVisitor(templateContext), null); node.Accept(new SetNamescopesAndRegisterNamesVisitor(templateContext), null); node.Accept(new SetFieldVisitor(templateContext), null); node.Accept(new SetResourcesVisitor(templateContext), null); node.Accept(new SetPropertiesVisitor(templateContext), null); templateIl.Emit(OpCodes.Ldloc, templateContext.Variables[node]); templateIl.Emit(OpCodes.Ret); //Instanciate nested class var parentIl = parentContext.IL; parentIl.Emit(OpCodes.Newobj, ctor); //Copy required local vars parentIl.Emit(OpCodes.Dup); //Duplicate the nestedclass instance parentIl.Append(node.PushParentObjectsArray(parentContext)); parentIl.Emit(OpCodes.Stfld, parentValues); parentIl.Emit(OpCodes.Dup); //Duplicate the nestedclass instance if (parentContext.Root is VariableDefinition) parentIl.Emit(OpCodes.Ldloc, parentContext.Root as VariableDefinition); else if (parentContext.Root is FieldDefinition) { parentIl.Emit(OpCodes.Ldarg_0); parentIl.Emit(OpCodes.Ldfld, parentContext.Root as FieldDefinition); } else throw new InvalidProgramException(); parentIl.Emit(OpCodes.Stfld, root); //SetDataTemplate parentIl.Emit(OpCodes.Ldftn, loadTemplate); var funcCtor = module.Import(typeof (Func<>)) .MakeGenericInstanceType(module.TypeSystem.Object) .Resolve() .Methods.First(md => md.IsConstructor && md.Parameters.Count == 2) .MakeGeneric(module.TypeSystem.Object); parentIl.Emit(OpCodes.Newobj, module.Import(funcCtor)); var propertySetter = module.Import(typeof (IDataTemplate)).Resolve().Properties.First(p => p.Name == "LoadTemplate").SetMethod; parentContext.IL.Emit(OpCodes.Callvirt, module.Import(propertySetter)); }
public object[] CreateArgumentsArray(IElementNode enode, ConstructorInfo ctorInfo) { var n = ctorInfo.GetParameters().Length; var array = new object[n]; for (var i = 0; i < n; i++) { var parameter = ctorInfo.GetParameters()[i]; var propname = parameter.CustomAttributes.First(attr => attr.AttributeType == typeof (ParameterAttribute)) .ConstructorArguments.First() .Value as string; var name = new XmlName("", propname); INode node; if (!enode.Properties.TryGetValue(name, out node)) { throw new XamlParseException( String.Format("The Property {0} is required to create a {1} object.", propname, ctorInfo.DeclaringType.FullName), enode as IXmlLineInfo); } if (!enode.SkipProperties.Contains(name)) enode.SkipProperties.Add(name); var value = Context.Values[node]; var serviceProvider = new XamlServiceProvider(enode, Context); var convertedValue = value.ConvertTo(parameter.ParameterType, () => parameter, serviceProvider); array[i] = convertedValue; } return array; }
static bool IsXaml2009LanguagePrimitive(IElementNode node) { return node.NamespaceURI == "http://schemas.microsoft.com/winfx/2009/xaml"; }
static object CreateLanguagePrimitive(Type nodeType, IElementNode node) { object value = null; if (nodeType == typeof (string)) value = String.Empty; else if (nodeType == typeof (Uri)) value = null; else value = Activator.CreateInstance(nodeType); if (node.CollectionItems.Count == 1 && node.CollectionItems[0] is ValueNode && ((ValueNode)node.CollectionItems[0]).Value is string) { var valuestring = ((ValueNode)node.CollectionItems[0]).Value as string; if (nodeType == typeof (bool)) { bool outbool; if (bool.TryParse(valuestring, out outbool)) value = outbool; } else if (nodeType == typeof (char)) { char retval; if (char.TryParse(valuestring, out retval)) value = retval; } else if (nodeType == typeof (string)) value = valuestring; else if (nodeType == typeof (decimal)) { decimal retval; if (decimal.TryParse(valuestring, NumberStyles.Number, CultureInfo.InvariantCulture, out retval)) value = retval; } else if (nodeType == typeof (float)) { float retval; if (float.TryParse(valuestring, NumberStyles.Number, CultureInfo.InvariantCulture, out retval)) value = retval; } else if (nodeType == typeof (double)) { double retval; if (double.TryParse(valuestring, NumberStyles.Number, CultureInfo.InvariantCulture, out retval)) value = retval; } else if (nodeType == typeof (byte)) { byte retval; if (byte.TryParse(valuestring, NumberStyles.Number, CultureInfo.InvariantCulture, out retval)) value = retval; } else if (nodeType == typeof (short)) { short retval; if (short.TryParse(valuestring, NumberStyles.Number, CultureInfo.InvariantCulture, out retval)) value = retval; } else if (nodeType == typeof (int)) { int retval; if (int.TryParse(valuestring, NumberStyles.Number, CultureInfo.InvariantCulture, out retval)) value = retval; } else if (nodeType == typeof (long)) { long retval; if (long.TryParse(valuestring, NumberStyles.Number, CultureInfo.InvariantCulture, out retval)) value = retval; } else if (nodeType == typeof (TimeSpan)) { TimeSpan retval; if (TimeSpan.TryParse(valuestring, CultureInfo.InvariantCulture, out retval)) value = retval; } else if (nodeType == typeof (Uri)) { Uri retval; if (Uri.TryCreate(valuestring, UriKind.RelativeOrAbsolute, out retval)) value = retval; } } return value; }