private void CreateTileNotification() { var text1 = new TextElement() { StringData = this.Group1Tbx.Text }; var text2 = new TextElement() { StringData = this.Group2Tbx.Text }; var defaultImgPath = "ms-appx:///Assets/Logo.png"; var imgPath1 = this.Group1ImgTbx.Text; if (String.IsNullOrEmpty(imgPath1) || String.IsNullOrWhiteSpace(imgPath1)) imgPath1 = defaultImgPath; var imgPath2 = this.Group2ImgTbx.Text; if (String.IsNullOrEmpty(imgPath2) || String.IsNullOrWhiteSpace(imgPath2)) imgPath2 = defaultImgPath; var image1 = new ImageElement() { ImageSource = imgPath1, IsRemoveMargin = true }; var image2 = new ImageElement() { ImageSource = imgPath2, IsRemoveMargin = true }; var subgroup1 = new SubGroupElement() { weight = 1, ChildElements = new IChildElement[] { text1, image1 } }; var subgroup2 = new SubGroupElement() { weight = 1, ChildElements = new IChildElement[] { text2, image2 } }; var group1 = new GroupElement() { Subgroups = new SubGroupElement[] { subgroup1, subgroup2 } }; var group2 = new GroupElement() { Subgroups = new SubGroupElement[] { subgroup1, subgroup2 } }; var visual = new TileVisualElement() { version = 3, BindingElements = new TileBindingElement[] { new TileBindingElement() { TileTemplate = AdaptiveTileSizeEnum.TileWide, Group = group1 }, new TileBindingElement() { TileTemplate = AdaptiveTileSizeEnum.TileMedium, Group = group2 } } }; var tile = new TileElement() { visual = visual }; var notification = new TileNotification(AdaptiveShellHelper.TrySerializeTileTemplateToXml(tile)); TileUpdateManager.CreateTileUpdaterForApplication().Update(notification); }
private void AddFooterElements(PdfConverter pdfConverter) { //write the page number TextElement footerText = new TextElement(0, pdfConverter.PdfFooterOptions.FooterHeight - 15, "This is page &p; of &P; ", new System.Drawing.Font(new System.Drawing.FontFamily("Times New Roman"), 10, System.Drawing.GraphicsUnit.Point)); footerText.EmbedSysFont = true; footerText.TextAlign = HorizontalTextAlign.Right; pdfConverter.PdfFooterOptions.AddElement(footerText); // set the footer HTML area HtmlToPdfElement footerHtml = new HtmlToPdfElement(0, 0, 0, pdfConverter.PdfFooterOptions.FooterHeight, "<i>HTML in Footer</i>", null, 1024, 0); footerHtml.FitHeight = true; footerHtml.EmbedFonts = cbEmbedFonts.Checked; pdfConverter.PdfFooterOptions.AddElement(footerHtml); if (cbDrawFooterLine.Checked) { // set the footer line float pdfPageWidth = 0; if (pdfConverter.PdfDocumentOptions.PdfPageOrientation == PdfPageOrientation.Portrait) pdfPageWidth = pdfConverter.PdfDocumentOptions.PdfPageSize.Width; else pdfPageWidth = pdfConverter.PdfDocumentOptions.PdfPageSize.Height; LineElement footerLine = new LineElement(0, 0, pdfPageWidth - pdfConverter.PdfDocumentOptions.LeftMargin - pdfConverter.PdfDocumentOptions.RightMargin, 0); footerLine.LineStyle.LineWidth = 0.5f; footerLine.ForeColor = Color.FromKnownColor((KnownColor)Enum.Parse(typeof(KnownColor), ddlFooterLineColor.SelectedItem.ToString())); pdfConverter.PdfFooterOptions.AddElement(footerLine); } }
public WindowsPhone7Page(string title1, string title2, bool fullscreen) : base(fullscreen) { this.Control.EntranceDuration = 300; this.title1 = new TextElement(title1) { Style = MetroTheme.PhoneTextPageTitle1Style, Location = new Point(24 - 3, 9) // -3 is a correction for Segoe fonts }; this.title2 = new TextElement(title2) { Style = MetroTheme.PhoneTextPageTitle2Style, Location = new Point(24 - 3, 30) // -3 is a correction for Segoe fonts }; this.Content = new Canvas { Size = new Size(this.Size.Width, this.Size.Height - 150), Location = new Point(0, 150) }; this.Background = new Canvas { Size = this.Size }; this.Control.AddElement(this.Background); this.Control.AddElement(this.Content); this.Control.AddElement(this.title1.AnimateVerticalEntrance(true)); this.Control.AddElement(this.title2.AnimateVerticalEntrance(true)); }
private void btnCreatePdf_Click(object sender, EventArgs e) { // create a PDF document Document document = new Document(); // set the license key document.LicenseKey = "B4mYiJubiJiInIaYiJuZhpmahpGRkZE="; // add a page to the PDF document PdfPage firstPage = document.AddPage(); string logoImagePath = System.IO.Path.Combine(Application.StartupPath, @"..\..\img\evologo-250.png"); string certificateFilePath = System.IO.Path.Combine(Application.StartupPath, @"..\..\certificates\evopdf.pfx"); PdfFont pdfFont = document.Fonts.Add(new Font("Arial", 10, FontStyle.Regular, GraphicsUnit.Point)); TextElement descriptionTextElement = new TextElement(0, 0, "A digital signature was applied on the logo image below. Click on the image to see the signature details", pdfFont); AddElementResult addResult = firstPage.AddElement(descriptionTextElement); // create the area where the digital signature will be displayed in the PDF document // in this sample the area is a logo image but it could be anything else ImageElement logoElement = new ImageElement(0, addResult.EndPageBounds.Bottom + 10, 100, logoImagePath); addResult = firstPage.AddElement(logoElement); //get the #PKCS 12 certificate from file DigitalCertificatesCollection certificates = DigitalCertificatesStore.GetCertificates(certificateFilePath, "evopdf"); DigitalCertificate certificate = certificates[0]; // create the digital signature over the logo image element DigitalSignatureElement signature = new DigitalSignatureElement(addResult.EndPageBounds, certificate); signature.Reason = "Protect the document from unwanted changes"; signature.ContactInfo = "The contact email is [email protected]"; signature.Location = "Development server"; firstPage.AddElement(signature); string outFilePath = System.IO.Path.Combine(Application.StartupPath, "DigitalSignature.pdf"); // save the PDF document to disk document.Save(outFilePath); // close the PDF document to release the resources document.Close(); DialogResult dr = MessageBox.Show("Open the saved file in an external viewer?", "Open Rendered File", MessageBoxButtons.YesNo); if (dr == DialogResult.Yes) { try { System.Diagnostics.Process.Start(outFilePath); } catch (Exception ex) { MessageBox.Show(ex.Message); return; } } }
private TitledGroup CreateItem(string name, string value) { var content = new TextElement(value) { Style = MetroTheme.PhoneTextSmallStyle, AutoSizeMode = TextElement.AutoSizeModeOptions.OneLineAutoHeight }; this.DelayInTransitions.Add(content); return new TitledGroup { TitleStyle = MetroTheme.PhoneTextNormalStyle, Title = name, Content = content }; }
private void AddReportFooter(PdfConverter pdfConverter) { //enable footer pdfConverter.PdfDocumentOptions.ShowFooter = true; // set the footer height in points pdfConverter.PdfFooterOptions.FooterHeight = 20; //write the page number var footerText = new TextElement(0, 0, "&p;", new System.Drawing.Font(new System.Drawing.FontFamily("Arial"), 10, System.Drawing.GraphicsUnit.Point)); footerText.EmbedSysFont = true; footerText.TextAlign = HorizontalTextAlign.Center; pdfConverter.PdfFooterOptions.AddElement(footerText); }
private void AddHtmlFooter(Document document, PdfFont footerPageNumberFont) { string headerAndFooterHtmlUrl = Path.Combine(Application.StartupPath, @"..\..\HeaderFooter\HeaderAndFooterHtml.htm"); //create a template to be added in the header and footer document.Footer = document.AddTemplate(document.Pages[0].ClientRectangle.Width, 60); // create a HTML to PDF converter element to be added to the header template HtmlToPdfElement footerHtmlToPdf = new HtmlToPdfElement(0, 0, document.Footer.ClientRectangle.Width, document.Footer.ClientRectangle.Height, headerAndFooterHtmlUrl); footerHtmlToPdf.FitHeight = true; document.Footer.AddElement(footerHtmlToPdf); // add page number to the footer TextElement pageNumberText = new TextElement(document.Footer.ClientRectangle.Width - 100, 30, "This is page &p; of &P; pages", footerPageNumberFont); document.Footer.AddElement(pageNumberText); }
public RenderConfigEditor(ContentRegister content) { //setup the text elements this.stateText = new List<TextElement>(); this.visibleElementGap = new List<bool>(); #if XBOX360 this.helpText = new TextElement("Use 'A' and the DPad to interact with the menu"); #else this.helpText = new TextElement("Use the Arrow Keys and 'Enter' to interact with the menu"); #endif this.helpText.HorizontalAlignment = HorizontalAlignment.Left; this.helpText.VerticalAlignment = VerticalAlignment.Bottom; this.helpText.Colour = Color.Black; this.backgroundContainer = new SolidColourElement(new Color(0, 0, 0, 200), new Vector2(0, 0)); this.backgroundContainer.AlphaBlendState = AlphaBlendState.Alpha; foreach (string name in ConfigProperties.Keys) { //create the text TextElement text = new TextElement(); //if it's a ediable value, then put a '[X]' infront if (ConfigProperties[name].CanRead) text.Text.SetText("[ ] " + name); else text.Text.SetText(name); text.VerticalAlignment = VerticalAlignment.Bottom; this.stateText.Add(text); bool gap = false; if (ConfigProperties[name].GetCustomAttributes(typeof(RenderConfiguration.GapAttribute), false).Length > 0) gap = true; this.visibleElementGap.Add(gap); } //select top instance this.editSelection = this.stateText.Count - 1; //sizes of the elements are setup in LoadContent() content.Add(this); }
private void AddHeader(PdfConverter pdfConverter, string headerText) { //enable header pdfConverter.PdfDocumentOptions.ShowHeader = true; // set the header height in points pdfConverter.PdfHeaderOptions.HeaderHeight = 20; var headerTextElement = new TextElement(0, 0, headerText, new System.Drawing.Font(new System.Drawing.FontFamily("Arial"), 10, System.Drawing.GraphicsUnit.Point)); headerTextElement.EmbedSysFont = true; headerTextElement.TextAlign = HorizontalTextAlign.Center; headerTextElement.VerticalTextAlign = VerticalTextAlign.Middle; pdfConverter.PdfHeaderOptions.AddElement(headerTextElement); }
private void AddFooter(PdfConverter pdfConverter) { string headerAndFooterHtmlUrl = System.IO.Path.Combine(Application.StartupPath, @"..\..\HeaderFooter\HeaderAndFooterHtml.htm"); //enable footer pdfConverter.PdfDocumentOptions.ShowFooter = true; // set the footer height in points pdfConverter.PdfFooterOptions.FooterHeight = 60; //write the page number TextElement footerText = new TextElement(0, 30, "This is page &p; of &P; ", new System.Drawing.Font(new System.Drawing.FontFamily("Times New Roman"), 10, System.Drawing.GraphicsUnit.Point)); footerText.EmbedSysFont = true; footerText.TextAlign = HorizontalTextAlign.Right; pdfConverter.PdfFooterOptions.AddElement(footerText); // set the footer HTML area HtmlToPdfElement footerHtml = new HtmlToPdfElement(0, 0, 0, pdfConverter.PdfFooterOptions.FooterHeight, headerAndFooterHtmlUrl, 1024, 0); footerHtml.FitHeight = true; pdfConverter.PdfFooterOptions.AddElement(footerHtml); }
protected override void Initialise() { //create the draw target. drawToScreen = new DrawTargetScreen(new Camera3D()); //this element will display some help text helpDisplay = new TextElement(); helpDisplay.Position = new Vector2(100, -100); #if XBOX360 helpDisplay.Text.SetText("Use a chatpad to input text!"); #else helpDisplay.Text.SetText("Use the keyboard to input text!"); #endif //add it to the screen drawToScreen.Add(helpDisplay); //create the text this.textElement = new TextElementRect(new Vector2(400, 200)); this.textElement.Colour = Color.Yellow; //align the element to the bottom centre of the screen this.textElement.VerticalAlignment = VerticalAlignment.Bottom; this.textElement.HorizontalAlignment = HorizontalAlignment.Centre; //centre align the text this.textElement.TextHorizontalAlignment = TextHorizontalAlignment.Centre; //centre the text in the middle of the 400x200 area of the element this.textElement.TextVerticalAlignment = VerticalAlignment.Centre; //add it to the screen drawToScreen.Add(textElement); }
private void AddFooter(PdfConverter pdfConverter) { string thisPageURL = HttpContext.Current.Request.Url.AbsoluteUri; string headerAndFooterHtmlUrl = thisPageURL.Substring(0, thisPageURL.LastIndexOf('/')) + "/HeaderFooter/HeaderAndFooterHtml.htm"; //enable footer pdfConverter.PdfDocumentOptions.ShowFooter = true; // set the footer height in points pdfConverter.PdfFooterOptions.FooterHeight = 60; //write the page number TextElement footerText = new TextElement(0, 30, "This is page &p; of &P; ", new System.Drawing.Font(new System.Drawing.FontFamily("Times New Roman"), 10, System.Drawing.GraphicsUnit.Point)); footerText.EmbedSysFont = true; footerText.TextAlign = HorizontalTextAlign.Right; pdfConverter.PdfFooterOptions.AddElement(footerText); // set the footer HTML area HtmlToPdfElement footerHtml = new HtmlToPdfElement(0, 0, 0, pdfConverter.PdfFooterOptions.FooterHeight, headerAndFooterHtmlUrl, 1024, 0); footerHtml.FitHeight = true; footerHtml.EmbedFonts = cbEmbedFonts.Checked; pdfConverter.PdfFooterOptions.AddElement(footerHtml); }
private static void AddFooterElements(PdfConverter pdfConverter) { //write the page number var footerText = new TextElement(0, pdfConverter.PdfFooterOptions.FooterHeight - 15, "Page &p; of &P; ", new Font(new FontFamily("Arial"), 10, GraphicsUnit.Point)) { EmbedSysFont = true, TextAlign = HorizontalTextAlign.Right }; pdfConverter.PdfFooterOptions.AddElement(footerText); // set the footer line float pdfPageWidth = pdfConverter.PdfDocumentOptions.PdfPageOrientation == PdfPageOrientation.Portrait ? pdfConverter.PdfDocumentOptions.PdfPageSize.Width : pdfConverter.PdfDocumentOptions.PdfPageSize.Height; var footerLine = new LineElement(0, 0, pdfPageWidth - pdfConverter.PdfDocumentOptions.LeftMargin - pdfConverter.PdfDocumentOptions.RightMargin, 0) { LineStyle = { LineWidth = 0.5f }, ForeColor = Color.Black }; pdfConverter.PdfFooterOptions.AddElement(footerLine); }
public void CreatePDf(string pageUrl, string saveDestination) { #region Create PDF try { PdfConverter pdfConverter = new PdfConverter(); pdfConverter.InternetSecurityZone = InternetSecurityZone.Trusted; //pdfConverter.AuthenticationOptions pdfConverter.AuthenticationOptions.Username = HttpContext.Current.User.Identity.Name; pdfConverter.HtmlElementsMappingOptions.HtmlTagNames = new string[] { "form" }; pdfConverter.PdfDocumentOptions.PdfPageSize = ExpertPdf.HtmlToPdf.PdfPageSize.A4; pdfConverter.PdfDocumentOptions.PdfCompressionLevel = PdfCompressionLevel.Normal; pdfConverter.PdfDocumentOptions.ShowHeader = true; pdfConverter.PdfDocumentOptions.ShowFooter = true; pdfConverter.PdfDocumentOptions.LeftMargin = 10; pdfConverter.PdfDocumentOptions.RightMargin = 10; pdfConverter.PdfDocumentOptions.TopMargin = 10; pdfConverter.PdfDocumentOptions.BottomMargin = 10; #region Header Part Commented // pdfConverter.PdfDocumentOptions.ShowHeader = true; // pdfConverter.PdfHeaderOptions.HeaderText = "sample header: " + "header data"; // pdfConverter.PdfHeaderOptions.HeaderTextColor = System.Drawing.Color.Blue; // pdfConverter.PdfHeaderOptions.header = string.empty; // pdfConverter.PdfHeaderOptions.DrawHeaderLine = false; // pdfConverter.PdfFooterOptions.FooterText = "Sample footer: " + "foooter Content" + // ". You can change color, font and other options"; // pdfConverter.PdfFooterOptions.FooterTextColor = System.Drawing.Color.Blue; // pdfConverter.PdfFooterOptions.DrawFooterLine = false; // pdfConverter.PdfFooterOptions.PageNumberText = "Page"; // pdfConverter.PdfFooterOptions.ShowPageNumber = true; //System.Web.HttpResponse response = System.Web.HttpContext.Current.Response; //response.Clear(); //response.AddHeader("Content-Type", "binary/octet-stream"); //response.AddHeader("Content-Disposition", // "attachment; filename=" + "ExpertPdf-Trail-" + DateTime.Now.ToShortDateString() + "; size=" + downloadBytes.Length.ToString()); //response.Flush(); //response.BinaryWrite(downloadBytes); //response.Flush(); //response.End(); #endregion ExpertPdf.HtmlToPdf.PdfDocument.Document pdfDocument = pdfConverter.GetPdfDocumentObjectFromUrl(pageUrl); PdfFont stdTimesFont = pdfDocument.AddFont(StdFontBaseFamily.TimesRoman); stdTimesFont.Size = 50; // byte[] downloadBytes = pdfConverter.GetPdfFromUrlBytes(pageUrl); foreach (HtmlElementMapping elementMapping in pdfConverter.HtmlElementsMappingOptions.HtmlElementsMappingResult) { foreach (HtmlElementPdfRectangle elementLocationInPdf in elementMapping.PdfRectangles) { // get the PDF page ExpertPdf.HtmlToPdf.PdfDocument.PdfPage pdfPage = pdfDocument.Pages[elementLocationInPdf.PageIndex]; { float xPos = -5; float yPos = 370; float rotateAngle = -45; for (int i = 0; i < 2; i++) { TextElement watermarkTextElement = new TextElement(xPos, yPos, PDFReportConstants.WaterMarkText, stdTimesFont); watermarkTextElement.ForeColor = System.Drawing.Color.LightGray; watermarkTextElement.Transparency = 85; watermarkTextElement.Rotate(rotateAngle); // watermarkTemplate.AddElement(watermarkTextElement); pdfPage.AddElement(watermarkTextElement); xPos = 0; rotateAngle = rotateAngle + 5; // xPos = xPos + 100; yPos = yPos + 200; } } } } string outFile = saveDestination; //string filepath =HttpContext.Current.Server.MapPath("~/Templates/Risk Rating Template/Risk_Rating_Template.xlsx"); pdfDocument.Save(saveDestination); #region Commented Part // the code below can be replaced by pdfMerger.SaveMergedPDFToFile(outFile); //System.IO.FileStream fs = null; //fs = new System.IO.FileStream(outFile, System.IO.FileMode.Create, System.IO.FileAccess.ReadWrite, System.IO.FileShare.Read); //fs.Write(downloadBytes, 0, downloadBytes.Length); //fs.Close(); #endregion System.Diagnostics.Process.Start(outFile); } catch (Exception ex) { //LogManager.GetLogger(LogCategory.Error).Log(ex, LoginextLogUtility.EXP_LOG_AND_RETHROW); } #endregion }
public override TextEvulateResult Render(TextElement tag, object vars) { var varname = tag.GetAttribute("var"); var start = tag.GetAttribute("start"); var step = tag.GetAttribute("step"); if (string.IsNullOrEmpty(start)) { start = "0"; } if (step == null || step == "0") { step = "1"; } var to = tag.GetAttribute("to"); if (string.IsNullOrEmpty(varname) && string.IsNullOrEmpty(step) && string.IsNullOrEmpty(to)) { return(null); } var startres = this.EvulateText(start); var stepres = this.EvulateText(step); int startnum = 0; int stepnum = 0; int tonum = 0; if (!TypeUtil.IsNumericType(startres)) { stepnum = 1; } else { stepnum = (int)Convert.ChangeType(stepres, TypeCode.Int32); } if (TypeUtil.IsNumericType(startres)) { startnum = (int)Convert.ChangeType(startres, TypeCode.Int32);; } var tores = this.EvulateText(to); if (!TypeUtil.IsNumericType(tores)) { return(null); } tonum = (int)Convert.ChangeType(tores, TypeCode.Int32); var result = new TextEvulateResult(); var svar = new KeyValues <object>(); this.Evulator.LocalVariables.Add(svar); for (int i = startnum; i < tonum; i += stepnum) { svar[varname] = i; var cresult = tag.EvulateValue(0, 0, vars); if (cresult == null) { continue; } result.TextContent += cresult.TextContent; if (cresult.Result == TextEvulateResultEnum.EVULATE_RETURN) { result.Result = TextEvulateResultEnum.EVULATE_RETURN; this.Evulator.LocalVariables.Remove(svar); return(result); } else if (cresult.Result == TextEvulateResultEnum.EVULATE_BREAK) { break; } } this.Evulator.LocalVariables.Remove(svar); result.Result = TextEvulateResultEnum.EVULATE_TEXT; return(result); }
public static void Bind(Entity entity, Main main, ListContainer commandQueueContainer) { PCInput input = entity.Get <PCInput>(); Editor editor = entity.Get <Editor>(); EditorGeeUI gui = entity.Get <EditorGeeUI>(); Property <bool> analyticsEnable = new Property <bool>(); ListProperty <SessionEntry> analyticsSessions = new ListProperty <SessionEntry>(); ListProperty <SessionEntry> analyticsActiveSessions = new ListProperty <SessionEntry>(); ListProperty <EventEntry> analyticsEvents = new ListProperty <EventEntry>(); ListProperty <EventEntry> analyticsActiveEvents = new ListProperty <EventEntry>(); ListProperty <PropertyEntry> analyticsProperties = new ListProperty <PropertyEntry>(); ListProperty <PropertyEntry> analyticsActiveProperties = new ListProperty <PropertyEntry>(); Dictionary <Session, ModelInstance> sessionPositionModels = new Dictionary <Session, ModelInstance>(); Dictionary <Session.EventList, List <ModelInstance> > eventPositionModels = new Dictionary <Session.EventList, List <ModelInstance> >(); Property <bool> analyticsPlaying = new Property <bool>(); Property <float> playbackSpeed = new Property <float> { Value = 1.0f }; Property <float> playbackLocation = new Property <float>(); const float timelineHeight = 32.0f; Scroller timelineScroller = new Scroller(); timelineScroller.ScrollAmount.Value = 60.0f; timelineScroller.EnableScissor.Value = false; timelineScroller.DefaultScrollHorizontal.Value = true; timelineScroller.AnchorPoint.Value = new Vector2(0, 1); timelineScroller.ResizeVertical.Value = true; timelineScroller.Add(new Binding <Vector2, Point>(timelineScroller.Position, x => new Vector2(0, x.Y), main.ScreenSize)); timelineScroller.Add(new Binding <Vector2, Point>(timelineScroller.Size, x => new Vector2(x.X, timelineHeight), main.ScreenSize)); timelineScroller.Add(new Binding <bool>(timelineScroller.Visible, () => analyticsEnable && Editor.EditorModelsVisible, analyticsEnable, Editor.EditorModelsVisible)); timelineScroller.Add(new Binding <bool>(timelineScroller.EnableScroll, x => !x, input.GetKey(Keys.LeftAlt))); entity.Add(new CommandBinding(entity.Delete, timelineScroller.Delete)); main.UI.Root.Children.Add(timelineScroller); timelineScroller.Add(new Binding <bool>(editor.EnableCameraDistanceScroll, () => !timelineScroller.Highlighted || editor.VoxelEditMode, timelineScroller.Highlighted, editor.VoxelEditMode)); timelineScroller.Add(new CommandBinding(timelineScroller.Delete, delegate() { editor.EnableCameraDistanceScroll.Value = true; })); ListContainer timelines = new ListContainer(); timelines.Alignment.Value = ListContainer.ListAlignment.Min; timelines.Orientation.Value = ListContainer.ListOrientation.Vertical; timelines.Reversed.Value = true; timelineScroller.Children.Add(timelines); input.Add(new CommandBinding <int>(input.MouseScrolled, () => input.GetKey(Keys.LeftAlt) && timelineScroller.Highlighted && !editor.VoxelEditMode, delegate(int delta) { float newScale = Math.Max(timelines.Scale.Value.X + delta * 6.0f, timelineScroller.Size.Value.X / timelines.Size.Value.X); Matrix absoluteTransform = timelines.GetAbsoluteTransform(); float x = input.Mouse.Value.X + ((absoluteTransform.Translation.X - input.Mouse.Value.X) * (newScale / timelines.Scale.Value.X)); timelines.Position.Value = new Vector2(x, 0.0f); timelines.Scale.Value = new Vector2(newScale, 1.0f); })); Container timeline = new Container(); timeline.Size.Value = new Vector2(0, timelineHeight); timeline.Tint.Value = Microsoft.Xna.Framework.Color.Black; timeline.ResizeHorizontal.Value = false; timeline.ResizeVertical.Value = false; timelines.Children.Add(timeline); EditorFactory.AddCommand ( entity, main, commandQueueContainer, "Load analytics data", new PCInput.Chord(), new Command { Action = delegate() { if (main.MapFile.Value != null) { List <Session> sessions = main.LoadAnalytics(main.MapFile); if (sessions.Count > 0) { analyticsEnable.Value = true; Dictionary <string, bool> distinctEventNames = new Dictionary <string, bool>(); Dictionary <string, bool> distinctPropertyNames = new Dictionary <string, bool>(); foreach (Session s in sessions) { foreach (Session.EventList el in s.Events) { distinctEventNames[el.Name] = true; s.TotalTime = Math.Max(s.TotalTime, el.Events[el.Events.Count - 1].Time); } foreach (Session.ContinuousProperty p in s.ContinuousProperties) { if (p.Independent) { distinctPropertyNames[p.Name] = true; } } analyticsSessions.Add(new SessionEntry { Session = s }); } analyticsEvents.AddAll(distinctEventNames.Keys.Select(x => new EventEntry { Name = x })); analyticsProperties.AddAll(distinctPropertyNames.Keys.Select(x => new PropertyEntry { Name = x })); timeline.Size.Value = new Vector2(analyticsSessions.Max(x => x.Session.TotalTime), timelineScroller.Size.Value.Y); timelines.Scale.Value = new Vector2(timelineScroller.Size.Value.X / timeline.Size.Value.X, 1.0f); } } } }, gui.MapCommands, () => !analyticsEnable && !string.IsNullOrEmpty(main.MapFile) && !gui.PickNextEntity, analyticsEnable, main.MapFile, gui.PickNextEntity ); ListContainer sessionsSidebar = new ListContainer(); sessionsSidebar.AnchorPoint.Value = new Vector2(1, 1); sessionsSidebar.Add(new Binding <Vector2>(sessionsSidebar.Position, () => new Vector2(main.ScreenSize.Value.X - 10, main.ScreenSize.Value.Y - timelineScroller.ScaledSize.Value.Y - 10), main.ScreenSize, timelineScroller.ScaledSize)); sessionsSidebar.Add(new Binding <bool>(sessionsSidebar.Visible, () => analyticsEnable && Editor.EditorModelsVisible, analyticsEnable, Editor.EditorModelsVisible)); sessionsSidebar.Alignment.Value = ListContainer.ListAlignment.Max; sessionsSidebar.Reversed.Value = true; main.UI.Root.Children.Add(sessionsSidebar); entity.Add(new CommandBinding(entity.Delete, sessionsSidebar.Delete)); Func <string, ListContainer> createCheckboxListItem = delegate(string text) { ListContainer layout = new ListContainer(); layout.Orientation.Value = ListContainer.ListOrientation.Horizontal; TextElement label = new TextElement(); label.FontFile.Value = main.Font; label.Text.Value = text; label.Name.Value = "Label"; layout.Children.Add(label); Container checkboxContainer = new Container(); checkboxContainer.PaddingBottom.Value = checkboxContainer.PaddingLeft.Value = checkboxContainer.PaddingRight.Value = checkboxContainer.PaddingTop.Value = 1.0f; layout.Children.Add(checkboxContainer); Container checkbox = new Container(); checkbox.Name.Value = "Checkbox"; checkbox.ResizeHorizontal.Value = checkbox.ResizeVertical.Value = false; checkbox.Size.Value = new Vector2(16.0f, 16.0f); checkboxContainer.Children.Add(checkbox); return(layout); }; Container sessionsContainer = new Container(); sessionsContainer.Tint.Value = Microsoft.Xna.Framework.Color.Black; sessionsContainer.Opacity.Value = UIFactory.Opacity; sessionsContainer.AnchorPoint.Value = new Vector2(1, 1); sessionsSidebar.Children.Add(sessionsContainer); Scroller sessionsScroller = new Scroller(); sessionsScroller.ResizeHorizontal.Value = true; sessionsScroller.ResizeVertical.Value = true; sessionsScroller.MaxVerticalSize.Value = 256; sessionsContainer.Children.Add(sessionsScroller); ListContainer sessionList = new ListContainer(); sessionList.Orientation.Value = ListContainer.ListOrientation.Vertical; sessionList.Alignment.Value = ListContainer.ListAlignment.Max; sessionsScroller.Children.Add(sessionList); Property <bool> allSessions = new Property <bool>(); sessionList.Add(new ListBinding <UIComponent, SessionEntry>(sessionList.Children, analyticsSessions, delegate(SessionEntry entry) { ListContainer item = createCheckboxListItem(string.Format("{0} {1:d} ({2})", entry.Session.UUID.Substring(0, 8), entry.Session.Date, new TimeSpan(0, 0, (int)entry.Session.TotalTime))); Container checkbox = (Container)item.GetChildByName("Checkbox"); checkbox.Add(new Binding <Microsoft.Xna.Framework.Color, bool>(checkbox.Tint, x => x ? Microsoft.Xna.Framework.Color.White : Microsoft.Xna.Framework.Color.Black, entry.Active)); item.Add(new CommandBinding(item.MouseLeftDown, delegate() { if (entry.Active) { allSessions.Value = false; analyticsActiveSessions.Remove(entry); } else { analyticsActiveSessions.Add(entry); } })); return(item); })); ListContainer allSessionsButton = createCheckboxListItem("[All]"); allSessionsButton.Add(new CommandBinding(allSessionsButton.MouseLeftDown, delegate() { if (allSessions) { allSessions.Value = false; foreach (SessionEntry s in analyticsActiveSessions.ToList()) { analyticsActiveSessions.Remove(s); } } else { allSessions.Value = true; foreach (SessionEntry s in analyticsSessions) { if (!s.Active) { analyticsActiveSessions.Add(s); } } } })); Container allSessionsCheckbox = (Container)allSessionsButton.GetChildByName("Checkbox"); allSessionsCheckbox.Add(new Binding <Microsoft.Xna.Framework.Color, bool>(allSessionsCheckbox.Tint, x => x ? Microsoft.Xna.Framework.Color.White : Microsoft.Xna.Framework.Color.Black, allSessions)); sessionList.Children.Add(allSessionsButton); Container eventsContainer = new Container(); eventsContainer.Tint.Value = Microsoft.Xna.Framework.Color.Black; eventsContainer.Opacity.Value = UIFactory.Opacity; eventsContainer.AnchorPoint.Value = new Vector2(1, 1); sessionsSidebar.Children.Add(eventsContainer); Scroller eventsScroller = new Scroller(); eventsScroller.ResizeHorizontal.Value = true; eventsScroller.ResizeVertical.Value = true; eventsScroller.MaxVerticalSize.Value = 256; eventsContainer.Children.Add(eventsScroller); ListContainer eventList = new ListContainer(); eventList.Orientation.Value = ListContainer.ListOrientation.Vertical; eventList.Alignment.Value = ListContainer.ListAlignment.Max; eventsScroller.Children.Add(eventList); Property <bool> allEvents = new Property <bool>(); eventList.Add(new ListBinding <UIComponent, EventEntry>(eventList.Children, analyticsEvents, delegate(EventEntry e) { ListContainer item = createCheckboxListItem(e.Name); Container checkbox = (Container)item.GetChildByName("Checkbox"); checkbox.Add(new Binding <Microsoft.Xna.Framework.Color, bool>(checkbox.Tint, x => x ? Microsoft.Xna.Framework.Color.White : Microsoft.Xna.Framework.Color.Black, e.Active)); TextElement label = (TextElement)item.GetChildByName("Label"); label.Tint.Value = new Microsoft.Xna.Framework.Color(colorHash(e.Name)); item.Add(new CommandBinding(item.MouseLeftDown, delegate() { if (e.Active) { allEvents.Value = false; analyticsActiveEvents.Remove(e); } else { analyticsActiveEvents.Add(e); } })); return(item); })); ListContainer allEventsButton = createCheckboxListItem("[All]"); allEventsButton.Add(new CommandBinding(allEventsButton.MouseLeftDown, delegate() { if (allEvents) { allEvents.Value = false; foreach (EventEntry e in analyticsActiveEvents.ToList()) { analyticsActiveEvents.Remove(e); } } else { allEvents.Value = true; foreach (EventEntry e in analyticsEvents) { if (!e.Active) { analyticsActiveEvents.Add(e); } } } })); Container allEventsCheckbox = (Container)allEventsButton.GetChildByName("Checkbox"); allEventsCheckbox.Add(new Binding <Microsoft.Xna.Framework.Color, bool>(allEventsCheckbox.Tint, x => x ? Microsoft.Xna.Framework.Color.White : Microsoft.Xna.Framework.Color.Black, allEvents)); eventList.Children.Add(allEventsButton); Container propertiesContainer = new Container(); propertiesContainer.Tint.Value = Microsoft.Xna.Framework.Color.Black; propertiesContainer.Opacity.Value = UIFactory.Opacity; propertiesContainer.AnchorPoint.Value = new Vector2(1, 1); sessionsSidebar.Children.Add(propertiesContainer); Scroller propertiesScroller = new Scroller(); propertiesScroller.ResizeHorizontal.Value = true; propertiesScroller.ResizeVertical.Value = true; propertiesScroller.MaxVerticalSize.Value = 256; propertiesContainer.Children.Add(propertiesScroller); ListContainer propertiesList = new ListContainer(); propertiesList.Orientation.Value = ListContainer.ListOrientation.Vertical; propertiesList.Alignment.Value = ListContainer.ListAlignment.Max; propertiesScroller.Children.Add(propertiesList); Property <bool> allProperties = new Property <bool>(); propertiesList.Add(new ListBinding <UIComponent, PropertyEntry>(propertiesList.Children, analyticsProperties, delegate(PropertyEntry e) { ListContainer item = createCheckboxListItem(e.Name); Container checkbox = (Container)item.GetChildByName("Checkbox"); checkbox.Add(new Binding <Microsoft.Xna.Framework.Color, bool>(checkbox.Tint, x => x ? Microsoft.Xna.Framework.Color.White : Microsoft.Xna.Framework.Color.Black, e.Active)); TextElement label = (TextElement)item.GetChildByName("Label"); label.Tint.Value = new Microsoft.Xna.Framework.Color(colorHash(e.Name)); item.Add(new CommandBinding(item.MouseLeftDown, delegate() { if (e.Active) { allProperties.Value = false; analyticsActiveProperties.Remove(e); } else { analyticsActiveProperties.Add(e); } })); return(item); })); ListContainer allPropertiesButton = createCheckboxListItem("[All]"); allPropertiesButton.Add(new CommandBinding(allPropertiesButton.MouseLeftDown, delegate() { if (allProperties) { allProperties.Value = false; foreach (PropertyEntry e in analyticsActiveProperties.ToList()) { analyticsActiveProperties.Remove(e); } } else { allProperties.Value = true; foreach (PropertyEntry e in analyticsProperties) { if (!e.Active) { analyticsActiveProperties.Add(e); } } } })); Container allPropertiesCheckbox = (Container)allPropertiesButton.GetChildByName("Checkbox"); allPropertiesCheckbox.Add(new Binding <Microsoft.Xna.Framework.Color, bool>(allPropertiesCheckbox.Tint, x => x ? Microsoft.Xna.Framework.Color.White : Microsoft.Xna.Framework.Color.Black, allProperties)); propertiesList.Children.Add(allPropertiesButton); Func <Session.EventList, LineDrawer2D> createEventLines = delegate(Session.EventList el) { LineDrawer2D line = new LineDrawer2D(); line.Color.Value = colorHash(el.Name); line.UserData.Value = el; foreach (Session.Event e in el.Events) { line.Lines.Add(new LineDrawer2D.Line { A = new Microsoft.Xna.Framework.Graphics.VertexPositionColor(new Vector3(e.Time, 0.0f, 0.0f), Microsoft.Xna.Framework.Color.White), B = new Microsoft.Xna.Framework.Graphics.VertexPositionColor(new Vector3(e.Time, timeline.Size.Value.Y, 0.0f), Microsoft.Xna.Framework.Color.White), }); } return(line); }; analyticsActiveEvents.ItemAdded += delegate(int index, EventEntry ee) { ee.Active.Value = true; foreach (SessionEntry s in analyticsActiveSessions) { Session.PositionProperty positionProperty = s.Session.PositionProperties[0]; foreach (Session.EventList el in s.Session.Events) { if (el.Name == ee.Name) { List <ModelInstance> models = new List <ModelInstance>(); Vector4 color = colorHash(el.Name); int hash = (int)(new Color(color).PackedValue); foreach (Session.Event e in el.Events) { ModelInstance i = new ModelInstance(); i.Serialize = false; i.Setup("InstancedModels\\position-model", hash); if (i.IsFirstInstance) { i.Model.Color.Value = new Vector3(color.X, color.Y, color.Z); } i.Transform.Value = Matrix.CreateTranslation(positionProperty.GetLastRecordedPosition(e.Time)); models.Add(i); entity.Add(i); } eventPositionModels[el] = models; } } timeline.Children.AddAll(s.Session.Events.Where(x => x.Name == ee.Name).Select(createEventLines)); } }; analyticsActiveEvents.ItemRemoved += delegate(int index, EventEntry e) { e.Active.Value = false; foreach (KeyValuePair <Session.EventList, List <ModelInstance> > pair in eventPositionModels.ToList()) { if (pair.Key.Name == e.Name) { foreach (ModelInstance instance in pair.Value) { instance.Delete.Execute(); } eventPositionModels.Remove(pair.Key); } } timeline.Children.RemoveAll(timeline.Children.Where(x => x.UserData.Value != null && ((Session.EventList)x.UserData.Value).Name == e.Name).ToList()); }; analyticsActiveProperties.ItemAdded += delegate(int index, PropertyEntry e) { e.Active.Value = true; }; analyticsActiveProperties.ItemRemoved += delegate(int index, PropertyEntry e) { e.Active.Value = false; }; ListContainer propertyTimelines = new ListContainer(); propertyTimelines.Alignment.Value = ListContainer.ListAlignment.Min; propertyTimelines.Orientation.Value = ListContainer.ListOrientation.Vertical; timelines.Children.Add(propertyTimelines); Action <Container> refreshPropertyGraph = delegate(Container container) { TextElement label = (TextElement)container.GetChildByName("Label"); LineDrawer2D lines = (LineDrawer2D)container.GetChildByName("Graph"); string propertyName = ((PropertyEntry)lines.UserData.Value).Name; lines.Lines.Clear(); float time = 0.0f, lastTime = 0.0f; float lastValue = 0.0f; bool firstLine = true; float max = float.MinValue, min = float.MaxValue; while (true) { bool stop = true; // Calculate average int count = 0; float sum = 0.0f; foreach (SessionEntry s in analyticsActiveSessions) { if (time < s.Session.TotalTime) { Session.ContinuousProperty prop = s.Session.GetContinuousProperty(propertyName); if (prop != null) { stop = false; sum += prop[time]; count++; } } } if (stop) { break; } else { float value = sum / (float)count; if (firstLine) { firstLine = false; } else { lines.Lines.Add(new LineDrawer2D.Line { A = new Microsoft.Xna.Framework.Graphics.VertexPositionColor { Color = Microsoft.Xna.Framework.Color.White, Position = new Vector3(lastTime, lastValue, 0.0f), }, B = new Microsoft.Xna.Framework.Graphics.VertexPositionColor { Color = Microsoft.Xna.Framework.Color.White, Position = new Vector3(time, value, 0.0f), }, }); } min = Math.Min(min, value); max = Math.Max(max, value); lastValue = value; lastTime = time; time += Session.Recorder.Interval; } if (min < max) { float scale = -timelineHeight / (max - min); lines.Scale.Value = new Vector2(1, scale); lines.Position.Value = new Vector2(0, max * -scale); } else { lines.AnchorPoint.Value = Vector2.Zero; if (min <= 0.0f) { lines.Position.Value = new Vector2(0, timelineHeight); } else { lines.Position.Value = new Vector2(0, timelineHeight * 0.5f); } } label.Text.Value = max.ToString("F"); } }; Action refreshPropertyGraphs = delegate() { foreach (Container propertyTimeline in propertyTimelines.Children) { refreshPropertyGraph(propertyTimeline); } }; propertyTimelines.Add(new ListBinding <UIComponent, PropertyEntry>(propertyTimelines.Children, analyticsActiveProperties, delegate(PropertyEntry e) { Container propertyTimeline = new Container(); propertyTimeline.Add(new Binding <Vector2>(propertyTimeline.Size, timeline.Size)); propertyTimeline.Tint.Value = Microsoft.Xna.Framework.Color.Black; propertyTimeline.Opacity.Value = UIFactory.Opacity; propertyTimeline.ResizeHorizontal.Value = false; propertyTimeline.ResizeVertical.Value = false; LineDrawer2D line = new LineDrawer2D(); line.Name.Value = "Graph"; line.Color.Value = colorHash(e.Name); line.UserData.Value = e; propertyTimeline.Children.Add(line); TextElement label = new TextElement(); label.FontFile.Value = main.Font; label.Name.Value = "Label"; label.Add(new Binding <Vector2>(label.Scale, x => new Vector2(1.0f / x.X, 1.0f / x.Y), timelines.Scale)); label.AnchorPoint.Value = new Vector2(0, 0); label.Position.Value = new Vector2(0, 0); propertyTimeline.Children.Add(label); refreshPropertyGraph(propertyTimeline); return(propertyTimeline); })); analyticsActiveSessions.ItemAdded += delegate(int index, SessionEntry s) { Session.PositionProperty positionProperty = s.Session.PositionProperties[0]; foreach (Session.EventList el in s.Session.Events) { if (analyticsActiveEvents.FirstOrDefault(x => x.Name == el.Name) != null) { List <ModelInstance> models = new List <ModelInstance>(); Vector4 color = colorHash(el.Name); int hash = (int)(new Color(color).PackedValue); foreach (Session.Event e in el.Events) { ModelInstance i = new ModelInstance(); i.Serialize = false; i.Setup("InstancedModels\\position-model", hash); if (i.IsFirstInstance) { i.Model.Color.Value = new Vector3(color.X, color.Y, color.Z); } i.Transform.Value = Matrix.CreateTranslation(positionProperty.GetLastRecordedPosition(e.Time)); entity.Add(i); models.Add(i); } eventPositionModels[el] = models; } } ModelInstance instance = new ModelInstance(); instance.Setup("InstancedModels\\position-model", 0); instance.Serialize = false; entity.Add(instance); sessionPositionModels.Add(s.Session, instance); s.Active.Value = true; timeline.Children.AddAll(s.Session.Events.Where(x => analyticsActiveEvents.FirstOrDefault(y => y.Name == x.Name) != null).Select(createEventLines)); playbackLocation.Reset(); refreshPropertyGraphs(); }; analyticsActiveSessions.ItemRemoved += delegate(int index, SessionEntry s) { ModelInstance instance = sessionPositionModels[s.Session]; instance.Delete.Execute(); foreach (KeyValuePair <Session.EventList, List <ModelInstance> > pair in eventPositionModels.ToList()) { if (pair.Key.Session == s.Session) { foreach (ModelInstance i in pair.Value) { i.Delete.Execute(); } eventPositionModels.Remove(pair.Key); } } sessionPositionModels.Remove(s.Session); s.Active.Value = false; timeline.Children.RemoveAll(timeline.Children.Where(x => x.UserData.Value != null && ((Session.EventList)x.UserData.Value).Session == s.Session).ToList()); refreshPropertyGraphs(); }; entity.Add(new SetBinding <float>(playbackLocation, delegate(float value) { if (analyticsActiveSessions.Length == 0) { return; } if (value < 0.0f) { playbackLocation.Value = 0.0f; } float end = analyticsActiveSessions.Max(x => x.Session.TotalTime); if (value > end) { playbackLocation.Value = end; analyticsPlaying.Value = false; } foreach (KeyValuePair <Session, ModelInstance> pair in sessionPositionModels) { pair.Value.Transform.Value = Matrix.CreateTranslation(pair.Key.PositionProperties[0][playbackLocation]); } })); LineDrawer2D playbackLine = new LineDrawer2D(); playbackLine.Color.Value = Vector4.One; playbackLine.Lines.Add(new LineDrawer2D.Line { A = new Microsoft.Xna.Framework.Graphics.VertexPositionColor { Color = Microsoft.Xna.Framework.Color.White, Position = new Vector3(0.0f, -10.0f, 0.0f), }, B = new Microsoft.Xna.Framework.Graphics.VertexPositionColor { Color = Microsoft.Xna.Framework.Color.White, Position = new Vector3(0.0f, timeline.Size.Value.Y, 0.0f), }, }); playbackLine.Add(new Binding <Vector2, float>(playbackLine.Position, x => new Vector2(x, 0.0f), playbackLocation)); timeline.Children.Add(playbackLine); entity.Add(new NotifyBinding(delegate() { allEventsButton.Detach(); allSessionsButton.Detach(); allPropertiesButton.Detach(); analyticsSessions.Clear(); analyticsEvents.Clear(); analyticsProperties.Clear(); eventList.Children.Add(allEventsButton); sessionList.Children.Add(allSessionsButton); propertiesList.Children.Add(allPropertiesButton); foreach (ModelInstance instance in sessionPositionModels.Values) { instance.Delete.Execute(); } sessionPositionModels.Clear(); foreach (ModelInstance instance in eventPositionModels.Values.SelectMany(x => x)) { instance.Delete.Execute(); } eventPositionModels.Clear(); allEvents.Value = false; allSessions.Value = false; allProperties.Value = false; analyticsEnable.Value = false; analyticsActiveEvents.Clear(); analyticsActiveSessions.Clear(); analyticsActiveProperties.Clear(); propertyTimelines.Children.Clear(); playbackLine.Detach(); timeline.Children.Clear(); timeline.Children.Add(playbackLine); analyticsPlaying.Value = false; playbackLocation.Value = 0.0f; }, main.MapFile)); EditorFactory.AddCommand ( entity, main, commandQueueContainer, "Toggle analytics playback", new PCInput.Chord { Modifier = Keys.LeftAlt, Key = Keys.A }, new Command { Action = delegate() { analyticsPlaying.Value = !analyticsPlaying; } }, gui.MapCommands, () => analyticsEnable && !editor.MovementEnabled && analyticsActiveSessions.Length > 0, analyticsEnable, editor.MovementEnabled, analyticsActiveSessions.Length ); EditorFactory.AddCommand ( entity, main, commandQueueContainer, "Stop analytics playback", new PCInput.Chord { Key = Keys.Escape }, new Command { Action = delegate() { analyticsPlaying.Value = false; } }, gui.MapCommands, () => analyticsPlaying, analyticsPlaying ); Container playbackContainer = new Container(); playbackContainer.Tint.Value = Microsoft.Xna.Framework.Color.Black; playbackContainer.Opacity.Value = UIFactory.Opacity; sessionsSidebar.Children.Add(playbackContainer); playbackContainer.Add(new CommandBinding <int>(playbackContainer.MouseScrolled, delegate(int delta) { playbackSpeed.Value = Math.Max(1.0f, Math.Min(10.0f, playbackSpeed.Value + delta)); })); TextElement playbackLabel = new TextElement(); playbackLabel.FontFile.Value = main.Font; playbackLabel.Add(new Binding <string>(playbackLabel.Text, delegate() { return(string.Format("{0} {1} {2:F}x", TimeTrialUI.SecondsToTimeString(playbackLocation), (analyticsPlaying ? "Playing" : "Stopped"), playbackSpeed)); }, playbackLocation, playbackSpeed, analyticsPlaying)); playbackContainer.Children.Add(playbackLabel); Container descriptionContainer = null; Updater timelineUpdate = new Updater ( delegate(float dt) { bool setTimelinePosition = false; if (timelines.Highlighted || descriptionContainer != null) { if (input.LeftMouseButton) { setTimelinePosition = true; playbackLocation.Value = Vector3.Transform(new Vector3(input.Mouse.Value.X, 0.0f, 0.0f), Matrix.Invert(timeline.GetAbsoluteTransform())).X; } float threshold = 3.0f / timelines.Scale.Value.X; float mouseRelative = Vector3.Transform(new Vector3(input.Mouse, 0.0f), Matrix.Invert(timelines.GetAbsoluteTransform())).X; if (descriptionContainer != null) { if (!timelines.Highlighted || (float)Math.Abs(descriptionContainer.Position.Value.X - mouseRelative) > threshold) { descriptionContainer.Delete.Execute(); descriptionContainer = null; } } if (descriptionContainer == null && timeline.Highlighted) { foreach (UIComponent component in timeline.Children) { LineDrawer2D lines = component as LineDrawer2D; if (lines == null) { continue; } Session.EventList el = lines.UserData.Value as Session.EventList; if (el != null) { bool stop = false; foreach (Session.Event e in el.Events) { if (el != null && (float)Math.Abs(e.Time - mouseRelative) < threshold) { descriptionContainer = new Container(); descriptionContainer.AnchorPoint.Value = new Vector2(0.5f, 1.0f); descriptionContainer.Position.Value = new Vector2(e.Time, 0.0f); descriptionContainer.Opacity.Value = 1.0f; descriptionContainer.Tint.Value = Microsoft.Xna.Framework.Color.Black; descriptionContainer.Add(new Binding <Vector2>(descriptionContainer.Scale, x => new Vector2(1.0f / x.X, 1.0f / x.Y), timelines.Scale)); timeline.Children.Add(descriptionContainer); TextElement description = new TextElement(); description.WrapWidth.Value = 256; if (string.IsNullOrEmpty(e.Data)) { description.Text.Value = el.Name; } else { description.Text.Value = string.Format("{0}\n{1}", el.Name, e.Data); } description.FontFile.Value = main.Font; descriptionContainer.Children.Add(description); stop = true; break; } } if (stop) { break; } } } } } if (analyticsPlaying && !setTimelinePosition) { if (analyticsActiveSessions.Length == 0) { analyticsPlaying.Value = false; } else { playbackLocation.Value += dt * playbackSpeed; } } } ); entity.Add(timelineUpdate); timelineUpdate.EnabledInEditMode = true; }
private void button_Import_Click(object sender, EventArgs e) { OpenFileDialog dialog = new OpenFileDialog(); dialog.Filter = "bin files (*.txt)|*.txt"; dialog.FileName = ""; dialog.Title = "导入文本"; DialogResult dr = dialog.ShowDialog(); bool bImport = (dr == DialogResult.OK); dialog.Dispose(); FileStream fs = null; if (bImport) { String fileName = dialog.FileName; try { if (File.Exists(fileName)) { fs = File.Open(fileName, FileMode.Open); } else { return; } ArrayList texts = IOUtil.readTextLinesGBK(fs); for (int i = 0; i < textsManager.getElementCount(); i++) { if (i >= texts.Count) { break; } String text = (String)texts[i]; TextElement element = textsManager.getElement(i); element.setValue(text); } textsManager.refreshUI(); textsManager.refreshUIAide(); } catch (Exception ex1) { Console.WriteLine(ex1.StackTrace); } finally { if (fs != null) { try { fs.Close(); fs = null; } catch (Exception ex) { Console.WriteLine(ex.Message); } } } } textsManager.refreshUI(listBox_Texts); }
internal TextRegion(int start, TextElement el) : this() { this.Element = el; this.Start = start; }
protected void btnCreatePDF_Click(object sender, EventArgs e) { string pdfToModify = textBoxPdfFilePath.Text.Trim(); // create a PDF document Document document = new Document(pdfToModify); // set the license key document.LicenseKey = "B4mYiJubiJiInIaYiJuZhpmahpGRkZE="; // get the first page the PDF document PdfPage firstPage = document.Pages[0]; string logoTransImagePath = System.IO.Path.Combine(Server.MapPath("~"), @"images\evologo-100-trans.png"); string logoOpaqueImagePath = System.IO.Path.Combine(Server.MapPath("~"), @"images\evologo-100.jpg"); // add an opaque image stamp in the top left corner of the first page // and make it semitransparent when rendered in PDF ImageElement imageStamp = new ImageElement(1, 1, logoOpaqueImagePath); imageStamp.Opacity = 50; AddElementResult addResult = firstPage.AddElement(imageStamp); // add a border for the image stamp RectangleElement imageBorderRectangleElement = new RectangleElement(1, 1, addResult.EndPageBounds.Width, addResult.EndPageBounds.Height); firstPage.AddElement(imageBorderRectangleElement); // add a template stamp to the document repeated on each document page // the template contains an image and a text System.Drawing.Image logoImg = System.Drawing.Image.FromFile(logoTransImagePath); // calculate the template stamp location and size System.Drawing.SizeF imageSizePx = logoImg.PhysicalDimension; float imageWidthPoints = UnitsConverter.PixelsToPoints(imageSizePx.Width); float imageHeightPoints = UnitsConverter.PixelsToPoints(imageSizePx.Height); float templateStampXLocation = (firstPage.ClientRectangle.Width - imageWidthPoints) / 2; float templateStampYLocation = firstPage.ClientRectangle.Height / 4; // the stamp size is equal to image size in points Template templateStamp = document.AddTemplate(new System.Drawing.RectangleF(templateStampXLocation, templateStampYLocation, imageWidthPoints, imageHeightPoints + 20)); // set a semitransparent background color for template RectangleElement background = new RectangleElement(0, 0, templateStamp.ClientRectangle.Width, templateStamp.ClientRectangle.Height); background.BackColor = Color.White; background.Opacity = 25; templateStamp.AddElement(background); // add a true type font to the document System.Drawing.Font ttfFontBoldItalic = new System.Drawing.Font("Times New Roman", 10, System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic, System.Drawing.GraphicsUnit.Point); PdfFont templateStampTextFont = document.AddFont(ttfFontBoldItalic, true); // Add a text element to the template. You can add any other types of elements to a template like a HtmlToPdfElement. TextElement templateStampTextElement = new TextElement(3, 0, "This is the Stamp Text", templateStampTextFont); templateStampTextElement.ForeColor = System.Drawing.Color.DarkBlue; templateStamp.AddElement(templateStampTextElement); // Add an image with transparency to the template. You can add any other types of elements to a template like a HtmlToPdfElement. ImageElement templateStampImageElement = new ImageElement(0, 20, logoImg); // instruct the library to use transparency information templateStampImageElement.RenderTransparentImage = true; templateStamp.AddElement(templateStampImageElement); // add a border to template RectangleElement templateStampRectangleElement = new RectangleElement(0, 0, templateStamp.ClientRectangle.Width, templateStamp.ClientRectangle.Height); templateStamp.AddElement(templateStampRectangleElement); // dispose the image logoImg.Dispose(); // save the document on http response stream try { // get the PDF document bytes byte[] pdfBytes = document.Save(); // send the generated PDF document to client browser // get the object representing the HTTP response to browser HttpResponse httpResponse = HttpContext.Current.Response; // add the Content-Type and Content-Disposition HTTP headers httpResponse.AddHeader("Content-Type", "application/pdf"); httpResponse.AddHeader("Content-Disposition", String.Format("attachment; filename=PdfStamps.pdf; size={0}", pdfBytes.Length.ToString())); // write the PDF document bytes as attachment to HTTP response httpResponse.BinaryWrite(pdfBytes); // Note: it is important to end the response, otherwise the ASP.NET // web page will render its content to PDF document stream httpResponse.End(); } finally { document.Close(); } }
/// <summary> /// Метод выполняет печать информации на метке /// </summary> private async void Print() { if (_client == null || !_client.IsConnected) { MessageBox.Show("Нет установленного соединения с шиной RFID"); return; } try { //кодировщик var encoder = new EpcSgtin96Encoder(CompanyPrefix, ProductId, StartSerial); //баркод var barcode = new Code128BarCodeElement(5, 35, 45, 5, codeFontSize: 14) { Value = CompanyPrefix.ToString(CultureInfo.InvariantCulture) + ProductId }; for (var i = 0; i < TagsCount; i++) { var label = new RfidPrintLabel { Width = 50, Height = 50 }; //текстовый элемент epc var epcElement = new TextElement(5, 20, 45, 25, "Arial", 35, BaseTools.GetStringFromBinary(encoder.Epc)); label.Elements.Add(epcElement); label.Elements.Add(barcode); if (IsWriteEpcData) { //элемент записи rfid данных var writeEpcElement = new WriteDataLabelElement(encoder.Epc, retries: 1); label.Elements.Add(writeEpcElement); } var printResult = await _client.SendRequestAsync(new EnqueuePrintLabelTask(SelectedPrinter.Id, label)); if (printResult.Status != ResponseStatus.Ok) { MessageBox.Show(String.Format("Не удалось добавить задачу в очередь на печать. Код статуса: {0}", printResult.Status)); } encoder++; } } catch (Exception ex) { MessageBox.Show(String.Format("Не удалось добавить задачу на печать. Описание: {0}", ex.Message)); } }
public static void OpenEditor(VisualElement element, Vector2 pos) { BuilderViewport viewport = element.GetFirstAncestorOfType <BuilderViewport>(); var editorLayer = viewport.editorLayer; var textEditor = viewport.textEditor; GetAttributeToEdit(element, pos, out var textElement, out var attributeName); if (textElement == null || string.IsNullOrEmpty(attributeName)) { return; } var attributeList = element.GetAttributeDescriptions(); foreach (var attribute in attributeList) { if (attribute?.name != null && attribute.name.Equals(attributeName)) { s_EditedTextAttribute = attribute; break; } } if (s_EditedTextAttribute == null) { return; } s_Viewport = viewport; s_EditedElement = element; s_EditedTextElement = textElement; var value = s_EditedElement.GetValueByReflection(s_EditedTextAttribute.name) as string; // To ensure the text element is visible if (string.IsNullOrEmpty(value)) { s_EditedElement.SetValueByReflection(s_EditedTextAttribute.name, s_DummyText); } editorLayer.RemoveFromClassList(BuilderConstants.HiddenStyleClassName); var textInput = textEditor.Q(TextField.textInputUssName); textEditor.value = value; textInput.style.unityTextAlign = textElement.resolvedStyle.unityTextAlign; textInput.style.fontSize = textElement.resolvedStyle.fontSize; textInput.style.unityFontStyleAndWeight = textElement.resolvedStyle.unityFontStyleAndWeight; textInput.style.whiteSpace = s_EditedTextElement.resolvedStyle.whiteSpace; textInput.style.width = s_EditedTextElement.resolvedStyle.width; textInput.style.height = s_EditedTextElement.resolvedStyle.height; textEditor.multiline = true; GetAlignmentFromTextAnchor(textElement.resolvedStyle.unityTextAlign, out var alignItems, out var justifyContent); var textEditorContainer = textEditor.parent; textEditorContainer.style.paddingLeft = s_EditedTextElement.resolvedStyle.paddingLeft; textEditorContainer.style.paddingTop = s_EditedTextElement.resolvedStyle.paddingTop; textEditorContainer.style.paddingRight = s_EditedTextElement.resolvedStyle.paddingRight; textEditorContainer.style.paddingBottom = s_EditedTextElement.resolvedStyle.paddingBottom; textEditorContainer.style.alignItems = alignItems; textEditorContainer.style.justifyContent = justifyContent; UpdateTextEditorGeometry(); textElement.RegisterCallback <GeometryChangedEvent>(OnTextElementGeometryChanged); textEditor.schedule.Execute(a => textInput.Focus()); textEditor.SelectAll(); textInput.RegisterCallback <FocusOutEvent>(OnFocusOutEvent, TrickleDown.TrickleDown); textEditor.RegisterCallback <ChangeEvent <string> >(OnTextChanged); }
/// <summary> /// This is used to flatten a flow document element hierarchy for searching /// </summary> /// <param name="element">The starting element to flatten</param> /// <returns>A flattened enumerable list containing the element and all child elements and /// their children recursively.</returns> public static IEnumerable <TextElement> Flatten(this TextElement element) { var table = element as Table; if (table != null) { return((new[] { table }).Concat(table.RowGroups.SelectMany(g => g.Rows).SelectMany( r => r.Cells).SelectMany(c => c.Flatten()))); } var tableCell = element as TableCell; if (tableCell != null) { return((new[] { tableCell }).Concat(tableCell.Blocks.SelectMany(b => b.Flatten()))); } var section = element as Section; if (section != null) { return((new[] { section }).Concat(section.Blocks.SelectMany(b => b.Flatten()))); } var list = element as List; if (list != null) { return((new[] { list }).Concat(list.ListItems.Concat(list.ListItems.SelectMany(i => i.Flatten())))); } var listItem = element as ListItem; if (listItem != null) { return((new[] { listItem }).Concat(listItem.Blocks.SelectMany(b => b.Flatten()))); } var para = element as Paragraph; if (para != null) { return((new[] { element }).Concat(para.Inlines.SelectMany(i => i.Flatten()))); } var anchoredBlock = element as AnchoredBlock; if (anchoredBlock != null) { return((new[] { anchoredBlock }).Concat(anchoredBlock.Blocks.SelectMany(b => b.Flatten()))); } var span = element as Span; if (span != null) { return((new[] { span }).Concat(span.Inlines.SelectMany(i => i.Flatten()))); } return(new[] { element }); }
// Token: 0x06006B5A RID: 27482 RVA: 0x001D4B5F File Offset: 0x001D2D5F internal UIElementParagraph(TextElement element, StructuralCache structuralCache) : base(element, structuralCache) { }
protected virtual string GetText(TextElement textElement) { return(GetTranslation(textElement.Translations)); }
void AddBuildTarget(VisualElement targetsContainer, Dictionary <string, JSONValue> buildEntry) { if (buildEntry[k_JsonNodeNameEnabled].AsBool()) { ServicesConfiguration.instance.RequestCloudBuildApiUrl(cloudBuildApiUrl => { var buildTargetName = buildEntry[k_JsonNodeNameName].AsString(); var buildTargetId = buildEntry[k_JsonNodeNameBuildTargetId].AsString(); var buildTargetUrls = buildEntry[k_JsonNodeNameLinks].AsDict(); var startBuildUrl = cloudBuildApiUrl + buildTargetUrls[k_JsonNodeNameStartBuilds].AsDict()[k_JsonNodeNameHref].AsString(); var targetContainer = new VisualElement(); targetContainer.AddToClassList(k_ClassNameTargetEntry); var buildNameTextElement = new TextElement(); buildNameTextElement.AddToClassList(k_ClassNameTitle); buildNameTextElement.text = buildTargetName; targetContainer.Add(buildNameTextElement); var buildButton = new Button(); buildButton.name = k_BuildButtonNamePrefix + buildTargetId; buildButton.AddToClassList(k_ClassNameBuildButton); if (m_BillingPlanLabel.ToLower() == k_SubscriptionPersonal || k_SubscriptionTeamsBasic.ToLower() == k_SubscriptionPersonal) { buildButton.SetEnabled(false); } buildButton.text = L10n.Tr(k_LabelBuildButton); buildButton.clicked += () => { var uploadHandler = new UploadHandlerRaw(Encoding.UTF8.GetBytes(k_LaunchBuildPayload)); var launchBuildPostRequest = new UnityWebRequest(startBuildUrl, UnityWebRequest.kHttpVerbPOST) { downloadHandler = new DownloadHandlerBuffer(), uploadHandler = uploadHandler }; launchBuildPostRequest.suppressErrorsToConsole = true; launchBuildPostRequest.SetRequestHeader("AUTHORIZATION", $"Bearer {UnityConnect.instance.GetUserInfo().accessToken}"); launchBuildPostRequest.SetRequestHeader("Content-Type", "application/json;charset=utf-8"); m_Provider.m_BuildRequests.Add(launchBuildPostRequest); var launchingMessage = string.Format(L10n.Tr(k_MessageLaunchingBuild), buildTargetName); Debug.Log(launchingMessage); NotificationManager.instance.Publish( Notification.Topic.BuildService, Notification.Severity.Info, launchingMessage); EditorAnalytics.SendLaunchCloudBuildEvent(new BuildPostInfo() { targetName = buildTargetName }); var operation = launchBuildPostRequest.SendWebRequest(); operation.completed += asyncOperation => { try { if (ServicesUtils.IsUnityWebRequestReadyForJsonExtract(launchBuildPostRequest)) { try { if (launchBuildPostRequest.responseCode == k_HttpResponseCodeAccepted) { var jsonLaunchedBuildParser = new JSONParser(launchBuildPostRequest.downloadHandler.text); var launchedBuildJson = jsonLaunchedBuildParser.Parse(); var launchedBuilds = launchedBuildJson.AsList(); foreach (var rawLaunchedBuild in launchedBuilds) { var launchedBuild = rawLaunchedBuild.AsDict(); if (launchedBuild.ContainsKey(k_JsonNodeNameBuild)) { var buildNumber = launchedBuild[k_JsonNodeNameBuild].AsFloat().ToString(); var message = string.Format(L10n.Tr(k_MessageLaunchedBuildSuccess), buildNumber, buildTargetName); Debug.Log(message); NotificationManager.instance.Publish( Notification.Topic.BuildService, Notification.Severity.Info, message); } else if (launchedBuild.ContainsKey(k_JsonNodeNameError)) { var message = string.Format(L10n.Tr(k_MessageLaunchedBuildFailedWithMsg), buildTargetName, launchedBuild[k_JsonNodeNameError].ToString()); Debug.LogError(message); NotificationManager.instance.Publish( Notification.Topic.BuildService, Notification.Severity.Error, message); } } } else { var message = L10n.Tr(k_MessageLaunchedBuildFailure); Debug.LogError(message); NotificationManager.instance.Publish( Notification.Topic.BuildService, Notification.Severity.Error, message); } } catch (Exception ex) { NotificationManager.instance.Publish( Notification.Topic.BuildService, Notification.Severity.Error, L10n.Tr(k_MessageErrorForBuildLaunch)); Debug.LogException(ex); } } } finally { m_Provider.m_BuildRequests.Remove(launchBuildPostRequest); launchBuildPostRequest.Dispose(); launchBuildPostRequest = null; } }; }; targetContainer.Add(buildButton); targetsContainer.Add(targetContainer); var separator = new VisualElement(); separator.AddToClassList(k_ClassNameSeparator); targetsContainer.Add(separator); }); } }
public NewMediumLevelRecordEditor(Plugin p, Record r, SubRecord sr, SubrecordStructure ss) { this.InitializeComponent(); Icon = Resources.tesv_ico; SuspendLayout(); this.sr = sr; this.ss = ss; this.p = p; this.r = r; // walk each element in standard fashion int panelOffset = 0; try { foreach (var elem in ss.elements) { Control c = null; if (elem.options != null && elem.options.Length > 1) { c = new OptionsElement(); } else if (elem.flags != null && elem.flags.Length > 1) { c = new FlagsElement(); } else { switch (elem.type) { case ElementValueType.LString: c = new LStringElement(); break; case ElementValueType.FormID: c = new FormIDElement(); break; case ElementValueType.Blob: c = new HexElement(); break; default: c = new TextElement(); break; } } if (c is IElementControl) { var ec = c as IElementControl; ec.formIDLookup = p.GetRecordByID; ec.formIDScan = p.EnumerateRecords; ec.strIDLookup = p.LookupFormStrings; ec.Element = elem; if (elem.repeat > 0) { var ge = new RepeatingElement(); c = ge; c.Left = 8; c.Width = this.fpanel1.Width - 16; c.Top = panelOffset; c.Anchor = c.Anchor | AnchorStyles.Left | AnchorStyles.Right; ge.InnerControl = ec; ge.Element = elem; ec = ge; } else if (elem.optional) { var re = new OptionalElement(); c = re; c.Left = 8; c.Width = this.fpanel1.Width - 16; c.Top = panelOffset; c.Anchor = c.Anchor | AnchorStyles.Left | AnchorStyles.Right; re.InnerControl = ec; re.Element = elem; ec = re; c = re; } else { c.Left = 8; c.Width = this.fpanel1.Width - 16; c.Top = panelOffset; c.Anchor = c.Anchor | AnchorStyles.Left | AnchorStyles.Right; } c.MinimumSize = c.Size; this.controlMap.Add(elem, ec); this.fpanel1.Controls.Add(c); panelOffset = c.Bottom; } } foreach (Element elem in r.EnumerateElements(sr, true)) { var es = elem.Structure; IElementControl c; if (this.controlMap.TryGetValue(es, out c)) { if (c is IGroupedElementControl) { var gc = c as IGroupedElementControl; gc.Elements.Add(elem.Data); } else { c.Data = elem.Data; } } } } catch { this.strWarnOnSave = "The subrecord doesn't appear to conform to the expected structure.\nThe formatted information may be incorrect."; this.Error.SetError(this.bSave, this.strWarnOnSave); this.Error.SetIconAlignment(this.bSave, ErrorIconAlignment.MiddleLeft); AcceptButton = this.bCancel; // remove save as default button when exception occurs CancelButton = this.bCancel; UpdateDefaultButton(); } ResumeLayout(); }
public PauseMenuState(GameWindow owner, GameFiniteStateMachine parent) : base(owner, parent) { var uiElementBehavior = new Behaviour <UiElementBase>(o => { var floatPos = BehaviorHelpers.EaseMouse(o.MousePosition); o.PositionAdd = floatPos / ((float)o.AttachedProperties["floatiness"]); }); var resumeButton = new TextElement(owner, "resume", ".\\fonts\\toxica.ttf", 40f) { NormalColor = Color4.Gray, Position = new Vector2(0f, -0.4f), Behaviours = { { GameTriggers.MouseMove, uiElementBehavior } }, AttachedProperties = { { "floatiness", 50f } }, MouseOverColor = Color4.White }; resumeButton.Clicked += args => TransitionOut("return"); var settingsButton = new TextElement(owner, "settings", ".\\fonts\\toxica.ttf", 40f) { NormalColor = Color4.Gray, Position = new Vector2(0f, -0.15f), Behaviours = { { GameTriggers.MouseMove, uiElementBehavior } }, AttachedProperties = { { "floatiness", 50f } }, MouseOverColor = Color4.White, }; settingsButton.Clicked += args => TransitionOut("settings"); var mainMenuButton = new TextElement(owner, "main menu", ".\\fonts\\toxica.ttf", 40f) { NormalColor = Color4.Gray, Position = new Vector2(0f, 0.1f), Behaviours = { { GameTriggers.MouseMove, uiElementBehavior } }, AttachedProperties = { { "floatiness", 50f } }, MouseOverColor = Color4.White, }; mainMenuButton.Clicked += args => TransitionOut("main menu"); var exitButton = new TextElement(owner, "exit", ".\\fonts\\toxica.ttf", 40f) { NormalColor = Color4.Gray, Position = new Vector2(0f, 0.35f), Behaviours = { { GameTriggers.MouseMove, uiElementBehavior } }, AttachedProperties = { { "floatiness", 50f } }, MouseOverColor = Color4.White, }; exitButton.Clicked += args => StateMachine.Transition("exit"); GameElements.Add(new TextElement(owner, "Game Paused", ".\\fonts\\toxica.ttf", 72f) { NormalColor = Color4.DarkRed, Behaviours = { { GameTriggers.MouseMove, uiElementBehavior } }, AttachedProperties = { { "floatiness", 25f } }, Position = new Vector2(0f, -0.75f) }); GameElements.Add(resumeButton); GameElements.Add(exitButton); GameElements.Add(settingsButton); GameElements.Add(mainMenuButton); }
public TxtTextElement(TextElement element) { this.element = element; }
private void AddHtmlFooter(Document document, PdfFont footerPageNumberFont) { string thisPageURL = HttpContext.Current.Request.Url.AbsoluteUri; string headerAndFooterHtmlUrl = thisPageURL.Substring(0, thisPageURL.LastIndexOf('/')) + "/HeaderFooter/HeaderAndFooterHtml.htm"; //create a template to be added in the header and footer document.Footer = document.AddTemplate(document.Pages[0].ClientRectangle.Width, 60); // create a HTML to PDF converter element to be added to the header template HtmlToPdfElement footerHtmlToPdf = new HtmlToPdfElement(0, 0, document.Footer.ClientRectangle.Width, document.Footer.ClientRectangle.Height, headerAndFooterHtmlUrl); footerHtmlToPdf.FitHeight = true; document.Footer.AddElement(footerHtmlToPdf); // add page number to the footer TextElement pageNumberText = new TextElement(document.Footer.ClientRectangle.Width - 100, 30, "This is page &p; of &P; pages", footerPageNumberFont); document.Footer.AddElement(pageNumberText); }
/// <summary> /// Extracts the tables in the page. /// </summary> /// <param name="page">The page where to extract the tables.</param> public List <Table> Extract(PageArea page) { List <TextElement> textElements = page.GetText(); if (textElements.Count == 0) { return(new Table[] { Table.EMPTY }.ToList()); } List <TextChunk> textChunks = this.verticalRulings == null?TextElement.MergeWords(page.GetText()) : TextElement.MergeWords(page.GetText(), this.verticalRulings); List <TableLine> lines = TextChunk.GroupByLines(textChunks); List <double> columns; if (this.verticalRulings != null) { // added by bobld: clipping verticalRulings because testExtractColumnsCorrectly2() fails var clippedVerticalRulings = Ruling.CropRulingsToArea(this.verticalRulings, page.BoundingBox); clippedVerticalRulings.Sort(new VerticalRulingComparer()); columns = new List <double>(clippedVerticalRulings.Count); foreach (Ruling vr in clippedVerticalRulings) { columns.Add(vr.Left); } /* * this.verticalRulings.Sort(new VerticalRulingComparer()); * columns = new List<double>(this.verticalRulings.Count); * foreach (Ruling vr in this.verticalRulings) * { * columns.Add(vr.getLeft()); * } */ } else { columns = ColumnPositions(lines); } // added by bobld: remove duplicates because testExtractColumnsCorrectly2() fails, // why do we need it here and not in the java version?? columns = columns.Distinct().ToList(); Table table = new Table(this); table.SetRect(page.BoundingBox); for (int i = 0; i < lines.Count; i++) { TableLine line = lines[i]; List <TextChunk> elements = line.TextElements.ToList(); elements.Sort(new TextChunkComparer()); foreach (TextChunk tc in elements) { if (tc.IsSameChar(TableLine.WHITE_SPACE_CHARS)) { continue; } int j = 0; bool found = false; for (; j < columns.Count; j++) { if (tc.Left <= columns[j]) { found = true; break; } } table.Add(new Cell(tc), i, found ? j : columns.Count); } } return(new Table[] { table }.ToList()); }
private Element _GetCreoleElementFrom(TokenRange <CreoleTokenCode> tokens, CreoleRichTextElementNodeData nodeData) { Element result = null; switch (nodeData.ElementType) { case CreoleRichTextElementType.Code: result = new CodeElement( _GetContentFrom(tokens, nodeData) ); break; case CreoleRichTextElementType.Hyperlink: result = new HyperlinkElement( _GetUrlFrom(tokens, nodeData), _GetCreoleElements(tokens, nodeData.ContentStartIndex, nodeData.ContentEndIndex, nodeData.ChildNodes) ); break; case CreoleRichTextElementType.Image: if (nodeData.UrlEndIndex < nodeData.ContentStartIndex) { result = new ImageElement( _GetUrlFrom(tokens, nodeData), _GetContentFrom(tokens, nodeData) ); } else { result = new ImageElement( _GetUrlFrom(tokens, nodeData) ); } break; case CreoleRichTextElementType.Plugin: result = new PluginElement( _GetContentFrom(tokens, nodeData) ); break; case CreoleRichTextElementType.LineBreak: result = _creoleLineBreakElement; break; case CreoleRichTextElementType.InlineHyperlink: var url = _GetUrlFrom(tokens, nodeData); result = new HyperlinkElement(url, new[] { new TextElement(url) }); break; case CreoleRichTextElementType.EscapedInlineHyperlink: result = new TextElement( _GetUrlFrom(tokens, nodeData) ); break; case CreoleRichTextElementType.Emphasis: result = new EmphasisElement( _GetCreoleElements(tokens, nodeData.ContentStartIndex, nodeData.ContentEndIndex, nodeData.ChildNodes) ); break; case CreoleRichTextElementType.Strong: result = new StrongElement( _GetCreoleElements(tokens, nodeData.ContentStartIndex, nodeData.ContentEndIndex, nodeData.ChildNodes) ); break; } return(result); }
public static void Draw(Context grw, TextElement text) { double dY = 0; if (text.Foregraund != null) { grw.SetSourceRGB( text.Foregraund.Red, text.Foregraund.Green, text.Foregraund.Blue); } grw.SelectFontFace( text.FontFamily, FontSlant.Normal, (FontWeight)text.Weight); grw.SetFontSize(text.ScaledFontSize); var te = grw.TextExtents(text.Text); double dX = 0; if (text.Align != null) { switch (text.Align.ToLowerInvariant()) { case AlignType.Center: dX = 0.5 * te.Width; break; case AlignType.Right: dX = te.Width; break; case AlignType.Left: dX = 0; break; default: return; } } if (text.VAlign != null) { switch (text.VAlign.ToLowerInvariant()) { case VAlignType.Top: dY = te.YBearing; break; case VAlignType.Center: dY = 0.5 * te.YBearing; break; case VAlignType.Bottom: dY = 0; break; default: return; } } grw.MoveTo( text.Start.GeometryX - dX, text.Start.GeometryY - dY); grw.ShowText(text.FormattedText); grw.Stroke(); }
private void Stream( ArrayList data, TextElement textElem ) { data.Add( new Snoop.Data.ClassSeparator( typeof( TextElement ) ) ); data.Add( new Snoop.Data.Object( "Symbol", textElem.Symbol ) ); data.Add( new Snoop.Data.String( "Text", textElem.Text ) ); TextNote textNote = textElem as TextNote; if( textNote != null ) { Stream( data, textNote ); return; } }
public override VisualElement Build() { var root = Resources.TypeInspector.Clone(); var label = root.Q <Label>("label"); label.text = DisplayName; var input = root.Q <VisualElement>("input"); input.RegisterCallback <MouseDownEvent>(e => { var items = new List <SearchView.Item>(); var types = TypeCache.GetTypesDerivedFrom <T>(); foreach (var type in types) { if (type.IsAbstract || type.IsInterface || type.HasAttribute <HideInInspector>() || type.HasAttribute <ObsoleteAttribute>()) { continue; } if (!TypeConstruction.CanBeConstructed(type)) { continue; } if (TypeFilter != null && !TypeFilter(type)) { continue; } var name = GetName(type); var category = GetCategory(type); items.Add(new SearchView.Item { Path = !string.IsNullOrEmpty(category) ? $"{category}/{name}" : name, Icon = GetIcon(type), Data = type }); } items = items.OrderBy(item => item.Path).ToList(); SearchWindow searchWindow = SearchWindow.Create(); searchWindow.Title = Title; searchWindow.Items = items; searchWindow.OnSelection += item => { var type = (Type)item.Data; if (TypeConstruction.TryConstruct <T>(type, out var instance)) { Target = instance; m_TextElement.text = GetName(type); } }; var rect = EditorWindow.focusedWindow.position; var button = input.worldBound; searchWindow.position = new Rect(rect.x + button.x, rect.y + button.y + button.height, 230, 315); searchWindow.ShowPopup(); e.StopPropagation(); }); m_TextElement = input.Q <TextElement>("text"); m_TextElement.text = GetName(Target?.GetType()); return(root); }
private void AddHtmlFooter(Document document, PdfFont footerPageNumberFont) { string headerAndFooterHtmlUrl = @"HeaderAndFooterHtml.htm"; //create a template to be added in the header and footer document.FooterTemplate = document.AddTemplate(document.Pages[0].ClientRectangle.Width, 100); // create a HTML to PDF converter element to be added to the header template HtmlToPdfElement footerHtmlToPdf = new HtmlToPdfElement(headerAndFooterHtmlUrl); document.FooterTemplate.AddElement(footerHtmlToPdf); // add page number to the footer TextElement pageNumberText = new TextElement(document.FooterTemplate.ClientRectangle.Width - 100, 30, "This is page &p; of &P; pages", footerPageNumberFont); document.FooterTemplate.AddElement(pageNumberText); }
void UpdateColorPalette(int newIndex) { PanelElement panel = (PanelElement)mapImgTemplate.Elements[0]; ImageElement imageElem = (ImageElement)panel.Children[0]; imageElem.ColumnIndex = newIndex; Color backColor = Color.Empty; Color checkBackColor = Color.Empty; Color hotBackColor = Color.Empty; Color hotCheckBackColor = Color.Empty; Color subgroupLineColor = Color.Empty; Color subgroupTitleColor = Color.Empty; switch (newIndex) { case 0: backColor = Color.FromArgb(29, 29, 29); checkBackColor = Color.FromArgb(244, 179, 0); hotBackColor = Color.FromArgb(58, 58, 58); hotCheckBackColor = Color.FromArgb(246, 188, 35); subgroupLineColor = Color.FromArgb(38, 38, 38); subgroupTitleColor = Color.FromArgb(255, 200, 63); break; case 1: backColor = Color.FromArgb(29, 29, 29); checkBackColor = Color.FromArgb(118, 182, 0); hotBackColor = Color.FromArgb(58, 58, 58); hotCheckBackColor = Color.FromArgb(137, 192, 35); subgroupLineColor = Color.FromArgb(38, 38, 38); subgroupTitleColor = Color.FromArgb(139, 216, 0); break; case 2: backColor = Color.FromArgb(29, 29, 29); checkBackColor = Color.FromArgb(38, 115, 236); hotBackColor = Color.FromArgb(58, 58, 58); hotCheckBackColor = Color.FromArgb(68, 133, 239); subgroupLineColor = Color.FromArgb(38, 38, 38); subgroupTitleColor = Color.FromArgb(54, 158, 255); break; case 3: backColor = Color.FromArgb(29, 29, 29); checkBackColor = Color.FromArgb(174, 17, 61); hotBackColor = Color.FromArgb(58, 58, 58); hotCheckBackColor = Color.FromArgb(185, 50, 88); subgroupLineColor = Color.FromArgb(38, 38, 38); subgroupTitleColor = Color.FromArgb(240, 0, 67); break; case 4: backColor = Color.FromArgb(38, 19, 0); checkBackColor = Color.FromArgb(99, 47, 0); hotBackColor = Color.FromArgb(66, 50, 33); hotCheckBackColor = Color.FromArgb(120, 76, 35); subgroupLineColor = Color.FromArgb(51, 26, 0); subgroupTitleColor = Color.FromArgb(209, 105, 22); break; case 5: backColor = Color.FromArgb(56, 0, 0); checkBackColor = Color.FromArgb(176, 30, 0); hotBackColor = Color.FromArgb(82, 33, 33); hotCheckBackColor = Color.FromArgb(187, 61, 35); subgroupLineColor = Color.FromArgb(74, 0, 0); subgroupTitleColor = Color.FromArgb(255, 42, 0); break; case 6: backColor = Color.FromArgb(64, 0, 46); checkBackColor = Color.FromArgb(193, 0, 79); hotBackColor = Color.FromArgb(88, 32, 72); hotCheckBackColor = Color.FromArgb(202, 35, 103); subgroupLineColor = Color.FromArgb(78, 0, 56); subgroupTitleColor = Color.FromArgb(244, 0, 133); break; case 7: backColor = Color.FromArgb(37, 0, 64); checkBackColor = Color.FromArgb(114, 0, 172); hotBackColor = Color.FromArgb(65, 33, 89); hotCheckBackColor = Color.FromArgb(133, 35, 183); subgroupLineColor = Color.FromArgb(51, 0, 87); subgroupTitleColor = Color.FromArgb(196, 80, 255); break; case 8: backColor = Color.FromArgb(24, 0, 82); checkBackColor = Color.FromArgb(70, 23, 180); hotBackColor = Color.FromArgb(54, 33, 104); hotCheckBackColor = Color.FromArgb(95, 55, 190); subgroupLineColor = Color.FromArgb(33, 0, 110); subgroupTitleColor = Color.FromArgb(146, 92, 255); break; case 9: backColor = Color.FromArgb(0, 25, 64); checkBackColor = Color.FromArgb(0, 106, 193); hotBackColor = Color.FromArgb(33, 55, 89); hotCheckBackColor = Color.FromArgb(35, 126, 202); subgroupLineColor = Color.FromArgb(0, 31, 82); subgroupTitleColor = Color.FromArgb(50, 163, 255); break; case 10: backColor = Color.FromArgb(0, 64, 80); checkBackColor = Color.FromArgb(0, 130, 135); hotBackColor = Color.FromArgb(33, 89, 103); hotCheckBackColor = Color.FromArgb(35, 146, 151); subgroupLineColor = Color.FromArgb(0, 73, 92); subgroupTitleColor = Color.FromArgb(82, 238, 255); break; case 11: backColor = Color.FromArgb(0, 62, 0); checkBackColor = Color.FromArgb(25, 153, 0); hotBackColor = Color.FromArgb(33, 87, 33); hotCheckBackColor = Color.FromArgb(57, 167, 35); subgroupLineColor = Color.FromArgb(0, 71, 0); subgroupTitleColor = Color.FromArgb(38, 236, 0); break; case 12: backColor = Color.FromArgb(18, 128, 35); checkBackColor = Color.FromArgb(0, 193, 63); hotBackColor = Color.FromArgb(49, 144, 63); hotCheckBackColor = Color.FromArgb(35, 202, 88); subgroupLineColor = Color.FromArgb(20, 140, 40); subgroupTitleColor = Color.FromArgb(0, 255, 83); break; case 13: backColor = Color.FromArgb(191, 90, 21); checkBackColor = Color.FromArgb(255, 152, 29); hotBackColor = Color.FromArgb(199, 111, 51); hotCheckBackColor = Color.FromArgb(255, 166, 60); subgroupLineColor = Color.FromArgb(201, 99, 30); subgroupTitleColor = Color.FromArgb(255, 202, 96); break; case 14: backColor = Color.FromArgb(154, 22, 22); checkBackColor = Color.FromArgb(255, 46, 18); hotBackColor = Color.FromArgb(167, 52, 52); hotCheckBackColor = Color.FromArgb(255, 75, 51); subgroupLineColor = Color.FromArgb(171, 26, 26); subgroupTitleColor = Color.FromArgb(255, 120, 67); break; case 15: backColor = Color.FromArgb(154, 22, 90); checkBackColor = Color.FromArgb(255, 29, 119); hotBackColor = Color.FromArgb(167, 52, 111); hotCheckBackColor = Color.FromArgb(255, 60, 138); subgroupLineColor = Color.FromArgb(168, 25, 99); subgroupTitleColor = Color.FromArgb(255, 93, 192); break; case 16: backColor = Color.FromArgb(87, 22, 154); checkBackColor = Color.FromArgb(170, 64, 255); hotBackColor = Color.FromArgb(109, 52, 167); hotCheckBackColor = Color.FromArgb(182, 90, 255); subgroupLineColor = Color.FromArgb(101, 26, 176); subgroupTitleColor = Color.FromArgb(82, 238, 255); break; case 17: backColor = Color.FromArgb(22, 73, 154); checkBackColor = Color.FromArgb(31, 174, 255); hotBackColor = Color.FromArgb(52, 97, 167); hotCheckBackColor = Color.FromArgb(62, 185, 255); subgroupLineColor = Color.FromArgb(25, 80, 168); subgroupTitleColor = Color.FromArgb(0, 198, 255); break; case 18: backColor = Color.FromArgb(67, 144, 223); checkBackColor = Color.FromArgb(86, 197, 255); hotBackColor = Color.FromArgb(91, 158, 227); hotCheckBackColor = Color.FromArgb(109, 205, 255); subgroupLineColor = Color.FromArgb(88, 154, 219); subgroupTitleColor = Color.FromArgb(65, 255, 255); break; case 19: backColor = Color.FromArgb(0, 142, 142); checkBackColor = Color.FromArgb(0, 216, 204); hotBackColor = Color.FromArgb(33, 157, 157); hotCheckBackColor = Color.FromArgb(35, 221, 210); subgroupLineColor = Color.FromArgb(0, 153, 153); subgroupTitleColor = Color.FromArgb(0, 255, 241); break; case 20: backColor = Color.FromArgb(120, 170, 28); checkBackColor = Color.FromArgb(145, 209, 0); hotBackColor = Color.FromArgb(137, 181, 57); hotCheckBackColor = Color.FromArgb(159, 215, 35); subgroupLineColor = Color.FromArgb(128, 181, 29); subgroupTitleColor = Color.FromArgb(185, 255, 20); break; case 21: backColor = Color.FromArgb(194, 144, 8); checkBackColor = Color.FromArgb(225, 183, 0); hotBackColor = Color.FromArgb(202, 158, 40); hotCheckBackColor = Color.FromArgb(229, 193, 35); subgroupLineColor = Color.FromArgb(199, 154, 30); subgroupTitleColor = Color.FromArgb(255, 243, 47); break; case 22: backColor = Color.FromArgb(220, 79, 173); checkBackColor = Color.FromArgb(255, 118, 188); hotBackColor = Color.FromArgb(225, 102, 184); hotCheckBackColor = Color.FromArgb(255, 137, 197); subgroupLineColor = Color.FromArgb(229, 90, 183); subgroupTitleColor = Color.FromArgb(255, 166, 198); break; case 23: backColor = Color.FromArgb(88, 88, 88); checkBackColor = Color.FromArgb(0, 164, 164); hotBackColor = Color.FromArgb(110, 110, 110); hotCheckBackColor = Color.FromArgb(35, 175, 176); subgroupLineColor = Color.FromArgb(97, 97, 97); subgroupTitleColor = Color.FromArgb(0, 212, 212); break; case 24: backColor = Color.FromArgb(88, 88, 88); checkBackColor = Color.FromArgb(255, 125, 35); hotBackColor = Color.FromArgb(110, 110, 110); hotCheckBackColor = Color.FromArgb(255, 143, 65); subgroupLineColor = Color.FromArgb(97, 97, 97); subgroupTitleColor = Color.FromArgb(255, 158, 56); break; } c1TileControl1.BackColor = backColor; c1TileControl1.TileBackColor = backColor; c1TileControl1.CheckBackColor = checkBackColor; c1TileControl1.HotBackColor = hotBackColor; c1TileControl1.HotCheckBackColor = hotCheckBackColor; panel = (PanelElement)subgroupTemplate.Elements[0]; TextElement textElem = (TextElement)panel.Children[1]; textElem.ForeColor = subgroupTitleColor; panel = (PanelElement)panel.Children[0]; panel.BackColor = subgroupLineColor; _currentIndex = newIndex; panel1.Invalidate(); }
private void btnConvert_Click(object sender, EventArgs e) { this.Cursor = Cursors.WaitCursor; string outFilePath = Path.Combine(Application.StartupPath, "HtmlToPdfElement.pdf"); // the PDF document Document document = null; try { //create a PDF document document = new Document(); // set the license key document.LicenseKey = "B4mYiJubiJiInIaYiJuZhpmahpGRkZE="; //optional settings for the PDF document like margins, compression level, //security options, viewer preferences, document information, etc document.CompressionLevel = PdfCompressionLevel.Normal; document.Margins = new Margins(10, 10, 0, 0); //document.Security.CanPrint = true; //document.Security.UserPassword = ""; document.DocumentInformation.Author = "HTML to PDF Converter"; document.ViewerPreferences.HideToolbar = false; // set if the JPEG compression is enabled for the images in PDF - default is true document.JpegCompressionEnabled = cbJpegCompression.Checked; //Add a first page to the document. The next pages will inherit the settings from this page PdfPage page = document.Pages.AddNewPage(PdfPageSize.A4, new Margins(10, 10, 0, 0), PdfPageOrientation.Portrait); // the code below can be used to create a page with default settings A4, document margins inherited, portrait orientation //PdfPage page = document.Pages.AddNewPage(); // add a font to the document that can be used for the texts elements PdfFont font = document.Fonts.Add(new Font(new FontFamily("Times New Roman"), 10, GraphicsUnit.Point)); // add header and footer before renderng the content if (cbAddHeader.Checked) AddHtmlHeader(document); if (cbAddFooter.Checked) AddHtmlFooter(document, font); // the result of adding an element to a PDF page AddElementResult addResult; // Get the specified location and size of the rendered content // A negative value for width and height means to auto determine // The auto determined width is the available width in the PDF page // and the auto determined height is the height necessary to render all the content float xLocation = float.Parse(textBoxXLocation.Text.Trim()); float yLocation = float.Parse(textBoxYLocation.Text.Trim()); float width = float.Parse(textBoxWidth.Text.Trim()); float height = float.Parse(textBoxHeight.Text.Trim()); if (radioConvertToSelectablePDF.Checked) { // convert HTML to PDF HtmlToPdfElement htmlToPdfElement; // convert a URL to PDF string urlToConvert = textBoxWebPageURL.Text.Trim(); htmlToPdfElement = new HtmlToPdfElement(xLocation, yLocation, width, height, urlToConvert); //optional settings for the HTML to PDF converter htmlToPdfElement.FitWidth = cbFitWidth.Checked; htmlToPdfElement.EmbedFonts = cbEmbedFonts.Checked; htmlToPdfElement.LiveUrlsEnabled = cbLiveLinks.Checked; htmlToPdfElement.JavaScriptEnabled = cbScriptsEnabled.Checked; htmlToPdfElement.PdfBookmarkOptions.HtmlElementSelectors = cbBookmarks.Checked ? new string[] { "H1", "H2" } : null; // add theHTML to PDF converter element to page addResult = page.AddElement(htmlToPdfElement); } else { HtmlToImageElement htmlToImageElement; // convert HTML to image and add image to PDF document // convert a URL to PDF string urlToConvert = textBoxWebPageURL.Text.Trim(); htmlToImageElement = new HtmlToImageElement(xLocation, yLocation, width, height, urlToConvert); //optional settings for the HTML to PDF converter htmlToImageElement.FitWidth = cbFitWidth.Checked; htmlToImageElement.LiveUrlsEnabled = cbLiveLinks.Checked; htmlToImageElement.JavaScriptEnabled = cbScriptsEnabled.Checked; htmlToImageElement.PdfBookmarkOptions.HtmlElementSelectors = cbBookmarks.Checked ? new string[] { "H1", "H2" } : null; addResult = page.AddElement(htmlToImageElement); } if (cbAdditionalContent.Checked) { // The code below can be used add some other elements right under the conversion result // like texts or another HTML to PDF conversion // add a text element right under the HTML to PDF document PdfPage endPage = document.Pages[addResult.EndPageIndex]; TextElement nextTextElement = new TextElement(0, addResult.EndPageBounds.Bottom + 10, "Below there is another HTML to PDF Element", font); nextTextElement.ForeColor = Color.Green; addResult = endPage.AddElement(nextTextElement); // add another HTML to PDF converter element right under the text element endPage = document.Pages[addResult.EndPageIndex]; HtmlToPdfElement nextHtmlToPdfElement = new HtmlToPdfElement(0, addResult.EndPageBounds.Bottom + 10, "http://www.google.com"); addResult = endPage.AddElement(nextHtmlToPdfElement); } // save the PDF document to disk document.Save(outFilePath); } catch (Exception ex) { MessageBox.Show(ex.Message); return; } finally { // close the PDF document to release the resources if (document != null) document.Close(); this.Cursor = Cursors.Arrow; } DialogResult dr = MessageBox.Show("Open the saved file in an external viewer?", "Open Rendered File", MessageBoxButtons.YesNo); if (dr == DialogResult.Yes) { try { System.Diagnostics.Process.Start(outFilePath); } catch (Exception ex) { MessageBox.Show(ex.Message); return; } } }
// ------------------------------------------------------------------ // Fetch the next run at element open edge position. // // position - current position in the text array // ------------------------------------------------------------------ private TextRun HandleElementStartEdge(StaticTextPointer position) { Debug.Assert(position.GetPointerContext(LogicalDirection.Forward) == TextPointerContext.ElementStart, "TextPointer does not point to element start edge."); // TextRun run = null; TextElement element = (TextElement)position.GetAdjacentElement(LogicalDirection.Forward); Debug.Assert(element != null, "Cannot use ITextContainer that does not provide TextElement instances."); if (element is LineBreak) { run = new TextEndOfLine(_elementEdgeCharacterLength * 2); } else if (element.IsEmpty) { // Empty TextElement should affect line metrics. // TextFormatter does not support this feature right now, so as workaround // TextRun with ZERO WIDTH SPACE is used. TextRunProperties textProps = new TextProperties(element, position, false /* inline objects */, true /* get background */); char[] textBuffer = new char[_elementEdgeCharacterLength * 2]; textBuffer[0] = (char)0x200B; textBuffer[1] = (char)0x200B; run = new TextCharacters(textBuffer, 0, textBuffer.Length, textProps); } else { Inline inline = element as Inline; if (inline == null) { run = new TextHidden(_elementEdgeCharacterLength); } else { DependencyObject parent = inline.Parent; FlowDirection inlineFlowDirection = inline.FlowDirection; FlowDirection parentFlowDirection = inlineFlowDirection; if (parent != null) { parentFlowDirection = (FlowDirection)parent.GetValue(FrameworkElement.FlowDirectionProperty); } TextDecorationCollection inlineTextDecorations = DynamicPropertyReader.GetTextDecorations(inline); if (inlineFlowDirection != parentFlowDirection) { // Inline's flow direction is different from its parent. Need to create new TextSpanModifier with flow direction if (inlineTextDecorations == null || inlineTextDecorations.Count == 0) { run = new TextSpanModifier( _elementEdgeCharacterLength, null, null, inlineFlowDirection ); } else { run = new TextSpanModifier( _elementEdgeCharacterLength, inlineTextDecorations, inline.Foreground, inlineFlowDirection ); } } else { if (inlineTextDecorations == null || inlineTextDecorations.Count == 0) { run = new TextHidden(_elementEdgeCharacterLength); } else { run = new TextSpanModifier( _elementEdgeCharacterLength, inlineTextDecorations, inline.Foreground ); } } } } return(run); }
public ActionResult CreatePdf(IFormCollection collection) { // Create a PDF document Document pdfDocument = new Document(); // Set license key received after purchase to use the converter in licensed mode // Leave it not set to use the converter in demo mode pdfDocument.LicenseKey = "4W9+bn19bn5ue2B+bn1/YH98YHd3d3c="; try { // The result of adding elements to PDF document AddElementResult addElementResult = null; // The titles font used to mark various sections of the PDF document PdfFont titleFont = pdfDocument.AddFont(new Font("Times New Roman", 12, FontStyle.Bold, GraphicsUnit.Point)); PdfFont subtitleFont = pdfDocument.AddFont(new Font("Times New Roman", 8, FontStyle.Bold, GraphicsUnit.Point)); // The position on X anf Y axes where to add the next element float yLocation = 5; float xLocation = 5; // Create a PDF page in PDF document PdfPage pdfPage = pdfDocument.AddPage(); // Add section title TextElement titleTextElement = new TextElement(xLocation, yLocation, "Images Scaling", titleFont); titleTextElement.ForeColor = Color.Black; addElementResult = pdfPage.AddElement(titleTextElement); yLocation = addElementResult.EndPageBounds.Bottom + 10; pdfPage = addElementResult.EndPdfPage; float titlesYLocation = yLocation; // Add an unscaled image // Add section title TextElement subtitleTextElement = new TextElement(xLocation, titlesYLocation, "Unscaled small image with normal resolution", subtitleFont); subtitleTextElement.ForeColor = Color.Navy; addElementResult = pdfPage.AddElement(subtitleTextElement); pdfPage = addElementResult.EndPdfPage; float imagesYLocation = addElementResult.EndPageBounds.Bottom + 10; string imagePath = m_hostingEnvironment.ContentRootPath + "/wwwroot" + "/DemoAppFiles/Input/Images/picture_small.jpg"; ImageElement unscaledImageElement = new ImageElement(xLocation, imagesYLocation, imagePath); addElementResult = pdfPage.AddElement(unscaledImageElement); RectangleF scaledDownImageRectangle = new RectangleF(addElementResult.EndPageBounds.Right + 30, addElementResult.EndPageBounds.Y, addElementResult.EndPageBounds.Width, addElementResult.EndPageBounds.Height); // Add a large image scaled down to same size in PDF // Add section title subtitleTextElement = new TextElement(scaledDownImageRectangle.X, titlesYLocation, "Scaled down large image has higher resolution", subtitleFont); subtitleTextElement.ForeColor = Color.Navy; pdfPage.AddElement(subtitleTextElement); imagePath = m_hostingEnvironment.ContentRootPath + "/wwwroot" + "/DemoAppFiles/Input/Images/picture_large.jpg"; ImageElement scaledDownImageElement = new ImageElement(scaledDownImageRectangle.X, scaledDownImageRectangle.Y, scaledDownImageRectangle.Width, imagePath); AddElementResult scaledDownImageResult = pdfPage.AddElement(scaledDownImageElement); // Add a border around the scaled down image RectangleElement borderElement = new RectangleElement(scaledDownImageRectangle); pdfPage.AddElement(borderElement); // Add an unscaled small image float columnX = scaledDownImageResult.EndPageBounds.Right + 30; // Add section title subtitleTextElement = new TextElement(columnX, titlesYLocation, "Unscaled small image", subtitleFont); subtitleTextElement.ForeColor = Color.Navy; pdfPage.AddElement(subtitleTextElement); imagePath = m_hostingEnvironment.ContentRootPath + "/wwwroot" + "/DemoAppFiles/Input/Images/picture_smaller.jpg"; unscaledImageElement = new ImageElement(columnX, imagesYLocation, imagePath); AddElementResult unscaledImageResult = pdfPage.AddElement(unscaledImageElement); RectangleF unscaledImageRectangle = unscaledImageResult.EndPageBounds; // Add an enlarged image // Add section title subtitleTextElement = new TextElement(columnX, unscaledImageRectangle.Bottom + 10, "Enlarged small image has lower resolution", subtitleFont); subtitleTextElement.ForeColor = Color.Navy; AddElementResult enlargedImageTitle = pdfPage.AddElement(subtitleTextElement); float enlargedImageWidth = unscaledImageRectangle.Width + 35; imagePath = m_hostingEnvironment.ContentRootPath + "/wwwroot" + "/DemoAppFiles/Input/Images/picture_smaller.jpg"; ImageElement enlargedImageElement = new ImageElement(columnX, enlargedImageTitle.EndPageBounds.Bottom + 10, enlargedImageWidth, imagePath); // Allow the image to be enlarged enlargedImageElement.EnlargeEnabled = true; AddElementResult enalargedImageResult = pdfPage.AddElement(enlargedImageElement); yLocation = addElementResult.EndPageBounds.Bottom + 10; // Scale an image preserving the aspect ratio titlesYLocation = yLocation; // Add section title subtitleTextElement = new TextElement(xLocation, titlesYLocation, "Scaled down image preserving aspect ratio", subtitleFont); subtitleTextElement.ForeColor = Color.Navy; addElementResult = pdfPage.AddElement(subtitleTextElement); pdfPage = addElementResult.EndPdfPage; yLocation = addElementResult.EndPageBounds.Bottom + 10; RectangleF boundingRectangle = new RectangleF(xLocation, yLocation, scaledDownImageRectangle.Width, scaledDownImageRectangle.Width); imagesYLocation = boundingRectangle.Y; imagePath = m_hostingEnvironment.ContentRootPath + "/wwwroot" + "/DemoAppFiles/Input/Images/landscape.jpg"; ImageElement keepAspectImageElement = new ImageElement(boundingRectangle.X, imagesYLocation, boundingRectangle.Width, boundingRectangle.Width, true, imagePath); addElementResult = pdfPage.AddElement(keepAspectImageElement); borderElement = new RectangleElement(boundingRectangle); borderElement.ForeColor = Color.Black; pdfPage.AddElement(borderElement); // Scale an image without preserving aspect ratio // This can produce a distorted image boundingRectangle = new RectangleF(addElementResult.EndPageBounds.Right + 30, addElementResult.EndPageBounds.Y, scaledDownImageRectangle.Width, scaledDownImageRectangle.Width); // Add section title subtitleTextElement = new TextElement(boundingRectangle.X, titlesYLocation, "Scaled down image without preserving aspect ratio", subtitleFont); subtitleTextElement.ForeColor = Color.Navy; pdfPage.AddElement(subtitleTextElement); imagePath = m_hostingEnvironment.ContentRootPath + "/wwwroot" + "/DemoAppFiles/Input/Images/landscape.jpg"; ImageElement notKeepAspectImageElement = new ImageElement(boundingRectangle.X, imagesYLocation, boundingRectangle.Width, boundingRectangle.Width, false, imagePath); addElementResult = pdfPage.AddElement(notKeepAspectImageElement); borderElement = new RectangleElement(boundingRectangle); borderElement.ForeColor = Color.Black; pdfPage.AddElement(borderElement); pdfPage = addElementResult.EndPdfPage; yLocation = addElementResult.EndPageBounds.Bottom + 20; // Add transparent images // Add section title titleTextElement = new TextElement(xLocation, yLocation, "Transparent Images", titleFont); titleTextElement.ForeColor = Color.Black; addElementResult = pdfPage.AddElement(titleTextElement); yLocation = addElementResult.EndPageBounds.Bottom + 10; pdfPage = addElementResult.EndPdfPage; imagePath = m_hostingEnvironment.ContentRootPath + "/wwwroot" + "/DemoAppFiles/Input/Images/transparent.png"; ImageElement trasparentImageElement = new ImageElement(xLocation, yLocation, 150, imagePath); addElementResult = pdfPage.AddElement(trasparentImageElement); imagePath = m_hostingEnvironment.ContentRootPath + "/wwwroot" + "/DemoAppFiles/Input/Images/rose.png"; trasparentImageElement = new ImageElement(addElementResult.EndPageBounds.Right + 60, yLocation + 20, 150, imagePath); pdfPage.AddElement(trasparentImageElement); pdfPage = addElementResult.EndPdfPage; yLocation = addElementResult.EndPageBounds.Bottom + 20; // Rotate images // Add section title titleTextElement = new TextElement(xLocation, yLocation, "Rotated Images", titleFont); titleTextElement.ForeColor = Color.Black; addElementResult = pdfPage.AddElement(titleTextElement); yLocation = addElementResult.EndPageBounds.Bottom + 10; pdfPage = addElementResult.EndPdfPage; // Add a not rotated image imagePath = m_hostingEnvironment.ContentRootPath + "/wwwroot" + "/DemoAppFiles/Input/Images/compass.png"; ImageElement noRotationImageElement = new ImageElement(xLocation, yLocation, 125, imagePath); addElementResult = pdfPage.AddElement(noRotationImageElement); float imageXLocation = addElementResult.EndPageBounds.X; float imageYLocation = addElementResult.EndPageBounds.Y; float imageWidth = addElementResult.EndPageBounds.Width; float imageHeight = addElementResult.EndPageBounds.Height; // The rotated coordinates system location float rotatedImageXLocation = imageXLocation + imageWidth + 20 + imageHeight; float rotatedImageYLocation = imageYLocation; // Add the image rotated 90 degrees ImageElement rotate90ImageElement = new ImageElement(0, 0, 125, imagePath); rotate90ImageElement.Translate(rotatedImageXLocation, rotatedImageYLocation); rotate90ImageElement.Rotate(90); pdfPage.AddElement(rotate90ImageElement); rotatedImageXLocation += 20 + imageWidth; rotatedImageYLocation = imageYLocation + imageHeight; // Add the image rotated 180 degrees ImageElement rotate180ImageElement = new ImageElement(0, 0, 125, imagePath); rotate180ImageElement.Translate(rotatedImageXLocation, rotatedImageYLocation); rotate180ImageElement.Rotate(180); pdfPage.AddElement(rotate180ImageElement); rotatedImageXLocation += 20; rotatedImageYLocation = imageYLocation + imageWidth; // Add the image rotated 270 degrees ImageElement rotate270ImageElement = new ImageElement(0, 0, 125, imagePath); rotate270ImageElement.Translate(rotatedImageXLocation, rotatedImageYLocation); rotate270ImageElement.Rotate(270); pdfPage.AddElement(rotate270ImageElement); pdfPage = addElementResult.EndPdfPage; yLocation = addElementResult.EndPageBounds.Bottom + 20; // Save the PDF document in a memory buffer byte[] outPdfBuffer = pdfDocument.Save(); // Send the PDF file to browser FileResult fileResult = new FileContentResult(outPdfBuffer, "application/pdf"); fileResult.FileDownloadName = "Image_Elements.pdf"; return(fileResult); } finally { // Close the PDF document pdfDocument.Close(); } }
private void btnCreatePdf_Click(object sender, EventArgs e) { // create a PDF document Document document = new Document(); // set the license key document.LicenseKey = "B4mYiJubiJiInIaYiJuZhpmahpGRkZE="; // add a page to the PDF document PdfPage firstPage = document.AddPage(); // Create a Times New Roman .NET font of 10 points System.Drawing.Font ttfFont = new System.Drawing.Font("Times New Roman", 10, System.Drawing.GraphicsUnit.Point); // Create a Times New Roman Italic .NET font of 10 points System.Drawing.Font ttfFontItalic = new System.Drawing.Font("Times New Roman", 10, System.Drawing.FontStyle.Italic, System.Drawing.GraphicsUnit.Point); // Create a Times New Roman Bold .NET font of 10 points System.Drawing.Font ttfFontBold = new System.Drawing.Font("Times New Roman", 10, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point); // Create a Times New Roman Bold .NET font of 10 points System.Drawing.Font ttfFontBoldItalic = new System.Drawing.Font("Times New Roman", 10, System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic, System.Drawing.GraphicsUnit.Point); // Create a Sim Sun .NET font of 10 points System.Drawing.Font ttfCJKFont = new System.Drawing.Font("SimSun", 10, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point); // Create the PDF fonts based on the .NET true type fonts PdfFont newTimesFont = document.AddFont(ttfFont); PdfFont newTimesFontItalic = document.AddFont(ttfFontItalic); PdfFont newTimesFontBold = document.AddFont(ttfFontBold); PdfFont newTimesFontBoldItalic = document.AddFont(ttfFontBoldItalic); // Create the embedded PDF fonts based on the .NET true type fonts PdfFont newTimesEmbeddedFont = document.AddFont(ttfFont, true); PdfFont newTimesItalicEmbeddedFont = document.AddFont(ttfFontItalic, true); PdfFont newTimesBoldEmbeddedFont = document.AddFont(ttfFontBold, true); PdfFont newTimesBoldItalicEmbeddedFont = document.AddFont(ttfFontBoldItalic, true); PdfFont cjkEmbeddedFont = document.AddFont(ttfCJKFont, true); // Create a standard Times New Roman Type 1 Font PdfFont stdTimesFont = document.AddFont(StdFontBaseFamily.TimesRoman); PdfFont stdTimesFontItalic = document.AddFont(StdFontBaseFamily.TimesItalic); PdfFont stdTimesFontBold = document.AddFont(StdFontBaseFamily.TimesBold); PdfFont stdTimesFontBoldItalic = document.AddFont(StdFontBaseFamily.TimesBoldItalic); // Create CJK standard Type 1 fonts PdfFont cjkJapaneseStandardFont = document.AddFont(StandardCJKFont.HeiseiKakuGothicW5); PdfFont cjkChineseTraditionalStandardFont = document.AddFont(StandardCJKFont.MonotypeHeiMedium); // Add text elements to the document TextElement trueTypeText = new TextElement(0, 10, "True Type Fonts Demo:", newTimesFontBold); AddElementResult addResult = firstPage.AddElement(trueTypeText); // Create the text element TextElement textElement1 = new TextElement(20, addResult.EndPageBounds.Bottom + 10, "Hello World !!!!", newTimesFont); // Add element to page. The result of adding the text element is stored into the addResult object // which can be used to get information about the rendered size in PDF page. addResult = firstPage.AddElement(textElement1); // Add another element 5 points below the text above. The bottom of the text above is taken from the AddElementResult object // set the font size newTimesFontItalic.Size = 15; TextElement textElement2 = new TextElement(20, addResult.EndPageBounds.Bottom + 5, "Hello World !!!!", newTimesFontItalic); textElement2.ForeColor = System.Drawing.Color.Green; addResult = firstPage.AddElement(textElement2); newTimesFontBoldItalic.Size = 20; TextElement textElement3 = new TextElement(20, addResult.EndPageBounds.Bottom + 5, "Hello World !!!!", newTimesFontBoldItalic); textElement3.ForeColor = System.Drawing.Color.Blue; addResult = firstPage.AddElement(textElement3); TextElement stdTypeText = new TextElement(0, addResult.EndPageBounds.Bottom + 10, "Standard PDF Fonts Demo:", newTimesFontBold); addResult = firstPage.AddElement(stdTypeText); TextElement textElement4 = new TextElement(20, addResult.EndPageBounds.Bottom + 10, "Hello World !!!!", stdTimesFont); addResult = firstPage.AddElement(textElement4); stdTimesFontItalic.Size = 15; TextElement textElement5 = new TextElement(20, addResult.EndPageBounds.Bottom + 5, "Hello World !!!!", stdTimesFontItalic); textElement5.ForeColor = System.Drawing.Color.Green; addResult = firstPage.AddElement(textElement5); stdTimesFontBoldItalic.Size = 20; TextElement textElement6 = new TextElement(20, addResult.EndPageBounds.Bottom + 5, "Hello World !!!!", stdTimesFontBoldItalic); textElement6.ForeColor = System.Drawing.Color.Blue; addResult = firstPage.AddElement(textElement6); // embedded true type fonts TextElement embeddedTtfText = new TextElement(0, addResult.EndPageBounds.Bottom + 10, "Embedded True Type Fonts Demo:", newTimesFontBold); addResult = firstPage.AddElement(embeddedTtfText); // russian text TextElement textElement8 = new TextElement(20, addResult.EndPageBounds.Bottom + 5, "Появление на свет!!", newTimesEmbeddedFont); addResult = firstPage.AddElement(textElement8); string outFilePath = System.IO.Path.Combine(Application.StartupPath, "TextsAndFontsDemo.pdf"); // save the PDF document to disk document.Save(outFilePath); // close the PDF document to release the resources document.Close(); DialogResult dr = MessageBox.Show("Open the saved file in an external viewer?", "Open Rendered File", MessageBoxButtons.YesNo); if (dr == DialogResult.Yes) { try { System.Diagnostics.Process.Start(outFilePath); } catch (Exception ex) { MessageBox.Show(ex.Message); return; } } }
public override TextEvulateResult Render(TextElement tag, object vars) { ColoredInfo info = this.Evulator.CustomDataSingle as ColoredInfo; //Karakter boyutunu hesaplayacağımız sınıfı kuruyorruz. StringFormat sf = new StringFormat(StringFormat.GenericTypographic); //Hesaplamada kırpmalar olmayacak. sf.Trimming = StringTrimming.None; //Boşluk karakteride hesaplamaya dâhil edilecek. sf.FormatFlags = StringFormatFlags.MeasureTrailingSpaces; //1. karakteerden başlayıp 1 karakterin uzunluğunu heesaplayacak. sf.SetMeasurableCharacterRanges(new CharacterRange[] { new CharacterRange() { First = 1, Length = 1 } }); PointF point = new PointF(info.PointX, info.PointY); RectangleF rect = info.DrawRectangle; //Karakte karakter hesaplatmamızın sebebi, metin sarma işleminin hesaplanması ve bazı karakterler arasında oluşan boşluk //sebebini düzeltmek içindir. for (int i = 0; i < tag.Value.Length; i++) { //mevcut karakter. char cur = tag.Value[i]; bool istab = false; //tab karakterini boşluk karakteri gibi hesaplayıp 7 ile çarapacak. if (cur == '\t') { cur = ' '; istab = true; } //Karakter iki + içerisinde hesaplatmamızın sebebi, bazı karakterleri doğrudan hesapladığında belirli boşluk problemlerinin //ortaya çıkmasıdır. RectangleF size = info.Graphics.MeasureCharacterRanges("+" + cur.ToString() + "+", info.Font, rect, sf)[0].GetBounds(info.Graphics); if (istab) { //Tab karakteri ise sadece width verecek, herhangi bir çizim işlemi uygulamayacak. size.Width *= 7; point.X += size.Width; continue; } //Mevcut satır üzerinde maximum büyüklüğü belirtiyoruz. if (size.Height > info.MaxH) { info.MaxH = size.Height; } //Mevcut uzunluk, metin alanını genişliğini geçiyorsa, otomatik olarak bir alt satıra geçiş yapacak. if (!istab && (cur == '\n' || point.X + size.Width > rect.Width)) { point.Y += info.MaxH; point.X = rect.X; info.MaxH = (cur == '\n') ? 0 : size.Height; info.TotalLines++; if (!info.IsOverlayed && cur != '\n') { info.IsOverlayed = true; } //Mevcut Y konumu çizim alanından büyük ise diğer kısımlar çizilmeyecek işlem burda sonlanacak. if (!info.NoDraw && point.Y + size.Height > rect.Height) { info.PointX = point.X; info.PointY = point.Y; return(new TextEvulateResult() { Result = TextEvulateResultEnum.EVULATE_RETURN }); } } //satır karateri için çizim yapmaz. if (cur == '\n') { continue; } //Boşluklar underline gibi özellikleri çizmesi için görünmeyen bir karaktere denk getirdik. if (cur == ' ') { cur = '\u007F'; } //Mevcut karakteri son konuma göre ekrana çizdiriyoruz. if (!info.NoDraw) { info.Graphics.DrawString(cur.ToString(), info.Font, new SolidBrush(info.ForeGroundColor), point, sf); } //Son konuma mevcut karakter boyutunu dâhil ettiriyoruz. point.X += size.Width; } //Diğer evulatörlerin bu değişiklikleri görebilmesi için son konumların atamasını yapıyoruz. info.PointX = point.X; info.PointY = point.Y; //Geriye bir dönüş yapmıyor. return(null); }
public void ApplyStrikeThroughStyle(TextElement element) { element.SetResourceReference(FrameworkContentElement.StyleProperty, StrikeThroughStyleKey); }
public void EscapesHtmlSpecialCharactersForPlainText(string text, string expectedHtml) { var actualHtml = new TextElement(text).Accept(new HtmlWriterVisitor()); Assert.Equal(expectedHtml, actualHtml); }
protected void btnConvert_Click(object sender, EventArgs e) { PdfConverter pdfConverter = new PdfConverter(); // set the license key pdfConverter.LicenseKey = "B4mYiJubiJiInIaYiJuZhpmahpGRkZE="; // show header and footer in the rendered PDF pdfConverter.PdfDocumentOptions.ShowHeader = true; pdfConverter.PdfDocumentOptions.ShowFooter = true; // set the header height in points pdfConverter.PdfHeaderOptions.HeaderHeight = 60; string thisPageURL = HttpContext.Current.Request.Url.AbsoluteUri; string headerAndFooterHtmlUrl = thisPageURL.Substring(0, thisPageURL.LastIndexOf('/')) + "/HeaderFooter/HeaderAndFooterHtml.htm"; // set the header HTML area HtmlToPdfElement headerHtml = new HtmlToPdfElement(0, 0, 0, pdfConverter.PdfHeaderOptions.HeaderHeight, headerAndFooterHtmlUrl, 1024, 0); headerHtml.FitHeight = true; pdfConverter.PdfHeaderOptions.AddElement(headerHtml); // set the footer height in points pdfConverter.PdfFooterOptions.FooterHeight = 60; //write the page number TextElement footerTextElement = new TextElement(0, 30, "This is page &p; of &P; ", new Font(new FontFamily("Times New Roman"), 10, GraphicsUnit.Point)); footerTextElement.TextAlign = HorizontalTextAlign.Right; pdfConverter.PdfFooterOptions.AddElement(footerTextElement); // set the footer HTML area HtmlToPdfElement footerHtml = new HtmlToPdfElement(0, 0, 0, pdfConverter.PdfFooterOptions.FooterHeight, headerAndFooterHtmlUrl, 1024, 0); footerHtml.FitHeight = true; pdfConverter.PdfFooterOptions.AddElement(footerHtml); if (!cbAlternateHeaderAndFooter.Checked) { // Performs the conversion and get the pdf document bytes that can // be saved to a file or sent as a browser response byte[] pdfBytes = pdfConverter.GetPdfBytesFromUrl(textBoxWebPageURL.Text); // send the generated PDF document to client browser // get the object representing the HTTP response to browser HttpResponse httpResponse = HttpContext.Current.Response; // add the Content-Type and Content-Disposition HTTP headers httpResponse.AddHeader("Content-Type", "application/pdf"); httpResponse.AddHeader("Content-Disposition", String.Format("attachment; filename=HtmlInHeaderAndFooter.pdf; size={0}", pdfBytes.Length.ToString())); // write the PDF document bytes as attachment to HTTP response httpResponse.BinaryWrite(pdfBytes); // Note: it is important to end the response, otherwise the ASP.NET // web page will render its content to PDF document stream httpResponse.End(); } else { // set an alternate header and footer on the even pages // call the converter and get a Document object from URL Document pdfDocument = pdfConverter.GetPdfDocumentObjectFromUrl(textBoxWebPageURL.Text); if (pdfDocument.Pages.Count >= 2) { // get the alternate header and footer width and height // the width is given by the PDF page width float altHeaderFooterWidth = pdfDocument.Pages[0].ClientRectangle.Width; // the height is the same with the document header height from the PdfConverter object float altHeaderHeight = pdfConverter.PdfHeaderOptions.HeaderHeight; float altFooterHeight = pdfConverter.PdfFooterOptions.FooterHeight; // create the alternate header template Template altHeaderTemplate = pdfDocument.Templates.AddNewTemplate(altHeaderFooterWidth, altHeaderHeight); string alternateHeaderAndFooterHtmlUrl = thisPageURL.Substring(0, thisPageURL.LastIndexOf('/')) + "/HeaderFooter/HeaderAndFooterHtml2.htm"; // add html to the header HtmlToPdfElement altHeaderHtml = new HtmlToPdfElement(0, 0, 0, pdfConverter.PdfHeaderOptions.HeaderHeight, alternateHeaderAndFooterHtmlUrl, 1024, 0); altHeaderHtml.FitHeight = true; altHeaderTemplate.AddElement(altHeaderHtml); // add a horizontal line to the bottom of the header LineElement headerLine = new LineElement(0, altHeaderHeight, altHeaderFooterWidth, altHeaderHeight); altHeaderTemplate.AddElement(headerLine); // add page numbering to the left of the header PdfFont pageNumberFont = pdfDocument.Fonts.Add(new Font(new FontFamily("Times New Roman"), 10, GraphicsUnit.Point)); TextElement pageNumbering = new TextElement(10, 10, "Page &p; of &P;", pageNumberFont, Color.Blue); altHeaderTemplate.AddElement(pageNumbering); // create the alternate footer template Template altFooterTemplate = pdfDocument.Templates.AddNewTemplate(altHeaderFooterWidth, altFooterHeight); // add html to the footer HtmlToPdfElement altFooterHtml = new HtmlToPdfElement(0, 0, 0, pdfConverter.PdfHeaderOptions.HeaderHeight, alternateHeaderAndFooterHtmlUrl, 1024, 0); altFooterHtml.FitHeight = true; altFooterTemplate.AddElement(altFooterHtml); for (int pageIndex = 1; pageIndex < pdfDocument.Pages.Count; pageIndex += 2) { PdfPage pdfPage = pdfDocument.Pages[pageIndex]; pdfPage.Header = altHeaderTemplate; pdfPage.Footer = altFooterTemplate; } } byte[] pdfBytes = null; try { pdfBytes = pdfDocument.Save(); } finally { // close the Document to realease all the resources pdfDocument.Close(); } // send the generated PDF document to client browser // get the object representing the HTTP response to browser HttpResponse httpResponse = HttpContext.Current.Response; // add the Content-Type and Content-Disposition HTTP headers httpResponse.AddHeader("Content-Type", "application/pdf"); httpResponse.AddHeader("Content-Disposition", String.Format("attachment; filename=HtmlInHeaderAndFooter.pdf; size={0}", pdfBytes.Length.ToString())); // write the PDF document bytes as attachment to HTTP response httpResponse.BinaryWrite(pdfBytes); // Note: it is important to end the response, otherwise the ASP.NET // web page will render its content to PDF document stream httpResponse.End(); } }
//------------------------------------------------------------------- // // Constructors // //------------------------------------------------------------------- #region Constructors // ------------------------------------------------------------------ // Constructor. // // element - Element associated with paragraph. // structuralCache - Content's structural cache // ------------------------------------------------------------------ protected FloaterBaseParagraph(TextElement element, StructuralCache structuralCache) : base(element, structuralCache) { }
public override TextRun GetTextRun(int textSourceCharacterIndex) { var index = textSourceCharacterIndex; if (runs.ContainsKey(index)) { var run = runs[index]; runs.Remove(index); return(run); } if (index >= text.Length) { return(new TextEndOfParagraph(1)); } char c = text[index]; if (c == '\r' || c == '\n' || c == '\u0085' || c == '\u2028' || c == '\u2029') { int nlLen = c == '\r' && index + 1 < text.Length && text[index + 1] == '\n' ? 2 : 1; return(new TextEndOfParagraph(nlLen)); } int defaultTextLength, tokenLength; object color; if (!cachedTextColorsCollection.Find(index, out defaultTextLength, out color, out tokenLength)) { Debug.Fail("Could not find token info"); return(new TextCharacters(" ", GetDefaultTextRunProperties())); } TextCharacters defaultRun = null, tokenRun = null; if (defaultTextLength != 0) { var defaultText = text.Substring(index, defaultTextLength); defaultRun = new TextCharacters(defaultText, GetDefaultTextRunProperties()); } index += defaultTextLength; if (tokenLength != 0) { var tc = GetTextColor(themeManager.Theme, color); var tokenText = text.Substring(index, tokenLength); var textProps = new TextProps(); textProps.fontSize = TextElement.GetFontSize(parent); textProps.foreground = tc.Foreground ?? TextElement.GetForeground(parent); textProps.background = tc.Background ?? (Brush)parent.GetValue(TextElement.BackgroundProperty); textProps.typeface = new Typeface( TextElement.GetFontFamily(parent), tc.FontStyle ?? TextElement.GetFontStyle(parent), tc.FontWeight ?? TextElement.GetFontWeight(parent), TextElement.GetFontStretch(parent) ); tokenRun = new TextCharacters(tokenText.Length == 0 ? " " : tokenText, textProps); } Debug.Assert(defaultRun != null || tokenRun != null); if ((defaultRun != null) ^ (tokenRun != null)) { return(defaultRun ?? tokenRun); } else { runs[index] = tokenRun; return(defaultRun); } }
protected void btnConvert_Click(object sender, EventArgs e) { //create a PDF document Document document = new Document(); // set the license key document.LicenseKey = "B4mYiJubiJiInIaYiJuZhpmahpGRkZE="; //optional settings for the PDF document like margins, compression level, //security options, viewer preferences, document information, etc document.CompressionLevel = PdfCompressionLevel.Normal; document.Margins = new Margins(10, 10, 0, 0); //document.Security.CanPrint = true; //document.Security.UserPassword = ""; document.ViewerPreferences.HideToolbar = false; // set if the images are compressed in PDF with JPEG to reduce the PDF document size document.JpegCompressionEnabled = cbJpegCompression.Checked; //Add a first page to the document. The next pages will inherit the settings from this page PdfPage page = document.Pages.AddNewPage(PdfPageSize.A4, new Margins(10, 10, 0, 0), PdfPageOrientation.Portrait); // the code below can be used to create a page with default settings A4, document margins inherited, portrait orientation //PdfPage page = document.Pages.AddNewPage(); // add a font to the document that can be used for the texts elements PdfFont font = document.Fonts.Add(new System.Drawing.Font(new System.Drawing.FontFamily("Times New Roman"), 10, System.Drawing.GraphicsUnit.Point)); // add header and footer before renderng the content if (cbAddHeader.Checked) AddHtmlHeader(document); if (cbAddFooter.Checked) AddHtmlFooter(document, font); // the result of adding an element to a PDF page AddElementResult addResult; // Get the specified location and size of the rendered content // A negative value for width and height means to auto determine // The auto determined width is the available width in the PDF page // and the auto determined height is the height necessary to render all the content float xLocation = float.Parse(textBoxXLocation.Text.Trim()); float yLocation = float.Parse(textBoxYLocation.Text.Trim()); float width = float.Parse(textBoxWidth.Text.Trim()); float height = float.Parse(textBoxHeight.Text.Trim()); if (radioConvertToSelectablePDF.Checked) { // convert HTML to PDF HtmlToPdfElement htmlToPdfElement; if (radioConvertURL.Checked) { // convert a URL to PDF string urlToConvert = textBoxWebPageURL.Text.Trim(); htmlToPdfElement = new HtmlToPdfElement(xLocation, yLocation, width, height, urlToConvert); } else { // convert a HTML string to PDF string htmlStringToConvert = textBoxHTMLCode.Text; string baseURL = textBoxBaseURL.Text.Trim(); htmlToPdfElement = new HtmlToPdfElement(xLocation, yLocation, width, height, htmlStringToConvert, baseURL); } //optional settings for the HTML to PDF converter htmlToPdfElement.FitWidth = cbFitWidth.Checked; htmlToPdfElement.EmbedFonts = cbEmbedFonts.Checked; htmlToPdfElement.LiveUrlsEnabled = cbLiveLinks.Checked; htmlToPdfElement.JavaScriptEnabled = cbClientScripts.Checked; htmlToPdfElement.PdfBookmarkOptions.HtmlElementSelectors = cbBookmarks.Checked ? new string[] { "H1", "H2" } : null; // add theHTML to PDF converter element to page addResult = page.AddElement(htmlToPdfElement); } else { HtmlToImageElement htmlToImageElement; // convert HTML to image and add image to PDF document if (radioConvertURL.Checked) { // convert a URL to PDF string urlToConvert = textBoxWebPageURL.Text.Trim(); htmlToImageElement = new HtmlToImageElement(xLocation, yLocation, width, height, urlToConvert); } else { // convert a HTML string to PDF string htmlStringToConvert = textBoxHTMLCode.Text; string baseURL = textBoxBaseURL.Text.Trim(); htmlToImageElement = new HtmlToImageElement(xLocation, yLocation, width, height, htmlStringToConvert, baseURL); } //optional settings for the HTML to PDF converter htmlToImageElement.FitWidth = cbFitWidth.Checked; htmlToImageElement.LiveUrlsEnabled = cbLiveLinks.Checked; htmlToImageElement.JavaScriptEnabled = cbClientScripts.Checked; htmlToImageElement.PdfBookmarkOptions.HtmlElementSelectors = cbBookmarks.Checked ? new string[] { "H1", "H2" } : null; addResult = page.AddElement(htmlToImageElement); } if (cbAdditionalContent.Checked) { // The code below can be used add some other elements right under the conversion result // like texts or another HTML to PDF conversion // add a text element right under the HTML to PDF document PdfPage endPage = document.Pages[addResult.EndPageIndex]; TextElement nextTextElement = new TextElement(0, addResult.EndPageBounds.Bottom + 10, "Below there is another HTML to PDF Element", font); nextTextElement.ForeColor = System.Drawing.Color.Green; addResult = endPage.AddElement(nextTextElement); // add another HTML to PDF converter element right under the text element endPage = document.Pages[addResult.EndPageIndex]; HtmlToPdfElement nextHtmlToPdfElement = new HtmlToPdfElement(0, addResult.EndPageBounds.Bottom + 10, "http://www.google.com"); addResult = endPage.AddElement(nextHtmlToPdfElement); } try { // get the PDF document bytes byte[] pdfBytes = document.Save(); // send the generated PDF document to client browser // get the object representing the HTTP response to browser HttpResponse httpResponse = HttpContext.Current.Response; // add the Content-Type and Content-Disposition HTTP headers httpResponse.AddHeader("Content-Type", "application/pdf"); httpResponse.AddHeader("Content-Disposition", String.Format("attachment; filename=HtmlToPdfElement.pdf; size={0}", pdfBytes.Length.ToString())); // write the PDF document bytes as attachment to HTTP response httpResponse.BinaryWrite(pdfBytes); // Note: it is important to end the response, otherwise the ASP.NET // web page will render its content to PDF document stream httpResponse.End(); } finally { // close the PDF document to release the resources document.Close(); } }
public void ApplyCodeBlockStyle(TextElement element) { element.SetResourceReference(FrameworkContentElement.StyleProperty, CodeBlockStyleKey); }
public TextConstruct(TextElement type) { this.type = type; }
public void ApplyMarkedStyle(TextElement element) { element.SetResourceReference(FrameworkContentElement.StyleProperty, MarkedStyleKey); }
protected override void Initialise() { //draw targets usually need a camera. var camera = new Xen.Camera.FirstPersonControlledCamera3D(this.UpdateManager, Vector3.Zero, false); //don't allow the camera to move too fast camera.MovementSensitivity *= 0.1f; camera.LookAt(new Vector3(0,3,0), new Vector3(1, 5, 10), new Vector3(0, 1, 0)); //create the draw target. drawToScreen = new DrawTargetScreen(camera); drawToScreen.ClearBuffer.ClearColour = new Color(45,50,60); //create the fire and smoke particle system this.fireParticleSystem = new ParticleSystem(this.UpdateManager); this.smokeParticleSystem = new ParticleSystem(this.UpdateManager); //IMPORTANT //The following flags are FALSE by default. //For looping effects, such as the fire and smoke, it's highly //recommended to enable this flag. Otherwise, while the effect //is offscreen, the particle system will continue to process. this.fireParticleSystem.PauseUpdatingWhileCulled = true; this.smokeParticleSystem.PauseUpdatingWhileCulled = true; this.drawSorted = new Xen.Ex.Scene.DepthDrawSorter(Xen.Ex.Scene.DepthSortMode.BackToFront); this.drawUnsorted = new DrawList(); var fireDrawer = new Xen.Ex.Graphics.Display.VelocityBillboardParticles3D(this.fireParticleSystem, true); var smokeDrawer = new Xen.Ex.Graphics.Display.BillboardParticles3D(this.smokeParticleSystem); for (int i = 0; i < 10; i++) { Vector3 position = new Vector3((float)Math.Cos(i * Math.PI / 5.0) * 6.0f, 0, (float)Math.Sin(i * Math.PI / 5.0) * 6.0f); CullableParticleWrapper fireEffect, smokeEffect; fireEffect = new CullableParticleWrapper(fireDrawer, position, new Vector3(0, 2, 0), 4); smokeEffect = new CullableParticleWrapper(smokeDrawer, position, new Vector3(0, 6, 0), 5); this.drawSorted.Add(fireEffect); this.drawSorted.Add(smokeEffect); this.drawUnsorted.Add(fireEffect); this.drawUnsorted.Add(smokeEffect); var light = new GroundLightDisk(position); this.drawSorted.Add(light); this.drawUnsorted.Add(light); } //setup the burst effect this.burstParticleSystem = new ParticleSystem(this.UpdateManager); //for this case, PauseUpdatingWhileCulled is not set to true. //The particle emitting is culled when offscreen. If set to true, //Any particles left offscreen could 'pause', when they naturally //wouldn't be emitted anyway. //(The particle system will use very few resources when it has no //active particles) this.burstSources = new BurstSource[20]; Random rand = new Random(); for (int i = 0; i < this.burstSources.Length; i++) { //create the bursts out in the distance Vector3 position = new Vector3((float)i * 5.0f - this.burstSources.Length * 2.5f, 0, -20); float radius = 10; // with a decent radius //give them a random starting time this.burstSources[i] = new BurstSource(position, radius, (float)rand.NextDouble() * 2); this.drawSorted.Add(this.burstSources[i]); this.drawUnsorted.Add(this.burstSources[i]); } //the bursts need to be drawn as a group.. var burstDrawer = new Xen.Ex.Graphics.Display.VelocityBillboardParticles3D(this.burstParticleSystem,false,0.5f); this.drawSorted.Add(burstDrawer); this.drawUnsorted.Add(burstDrawer); //Use all the burst sources to cull the drawer (may not be ideal if there were many sources...) //Use the particle drawer CullProxy to do it burstDrawer.CullProxy = new BurstCullProxy(this.burstSources); //add a ground plane to show the horizon drawToScreen.Add(new Tutorial_22.DarkGroundPlane(new Vector4(0.125f,0.15f,0.135f,1))); //add the sorted and unsorted lists drawToScreen.Add(drawSorted); drawToScreen.Add(drawUnsorted); //finally, create a CullTestVisualizer, which will visually show the cull tests performed cullTestVisualizer = new Xen.Ex.Scene.CullTestVisualizer(); //the visualizer is added as a draw modifier this.drawToScreen.AddModifier(cullTestVisualizer); //add help text this.text = new TextElement(); this.text.VerticalAlignment = VerticalAlignment.Bottom; this.text.Position = new Vector2(50, 100); drawToScreen.Add(this.text); //add draw stats stats = new Xen.Ex.Graphics2D.Statistics.DrawStatisticsDisplay(this.UpdateManager); drawToScreen.Add(stats); }
public void ApplyParagraphStyle(TextElement element) { element.SetResourceReference(FrameworkContentElement.StyleProperty, ParagraphStyleKey); }
public static void Draw (Context grw, TextElement text) { double dY = 0; if (text.Foregraund != null) { grw.SetSourceRGB ( text.Foregraund.Red, text.Foregraund.Green, text.Foregraund.Blue); } grw.SelectFontFace ( text.FontFamily, FontSlant.Normal, (FontWeight)text.Weight); grw.SetFontSize (text.ScaledFontSize); var te = grw.TextExtents (text.Text); double dX = 0; if (text.Align != null) { switch (text.Align.ToLowerInvariant()) { case AlignType.Center: dX = 0.5 * te.Width; break; case AlignType.Right: dX = te.Width; break; case AlignType.Left: dX = 0; break; default: return; } } if (text.VAlign != null) { switch (text.VAlign.ToLowerInvariant ()) { case VAlignType.Top: dY = te.YBearing; break; case VAlignType.Center: dY = 0.5 * te.YBearing; break; case VAlignType.Bottom: dY = 0; break; default: return; } } grw.MoveTo ( text.Start.GeometryX - dX, text.Start.GeometryY - dY); grw.ShowText (text.FormattedText); grw.Stroke (); }
/// <summary> /// Returns the SvgElement object converted from given XElement /// </summary> /// <param name="element"></param> /// <returns></returns> public static ISvgElement GetSvgElement(XElement element) { switch (element.Name.LocalName) { case "path": { var pathElement = new PathElement(element); AddAttributesToElement(pathElement, element); return(pathElement); } case "text": { var textElement = new TextElement(element); AddAttributesToElement(textElement, element); return(textElement); } case "circle": case "ellipse": { var ellipseElement = new EllipseElement(element); AddAttributesToElement(ellipseElement, element); return(ellipseElement); } case "rect": { var rectElement = new RectElement(element); AddAttributesToElement(rectElement, element); return(rectElement); } case "line": { var lineElement = new LineElement(element); AddAttributesToElement(lineElement, element); return(lineElement); } case "polyline": { var polyLineElement = new PolyLineElement(element, false); AddAttributesToElement(polyLineElement, element); return(polyLineElement); } case "polygon": { var polyLineElement = new PolyLineElement(element, true); AddAttributesToElement(polyLineElement, element); return(polyLineElement); } case "g": { var gElement = new GElement(element); AddAttributesToElement(gElement, element); return(gElement); } case "defs": { AddDefinitions(element); return(null); } default: return(null); } }
protected void btnCreatePDF_Click(object sender, EventArgs e) { // create a PDF document Document document = new Document(); // set the license key document.LicenseKey = "B4mYiJubiJiInIaYiJuZhpmahpGRkZE="; // add a page to the PDF document PdfPage firstPage = document.AddPage(); // Create a Times New Roman .NET font of 10 points System.Drawing.Font ttfFont = new System.Drawing.Font("Times New Roman", 10, System.Drawing.GraphicsUnit.Point); // Create a Times New Roman Italic .NET font of 10 points System.Drawing.Font ttfFontItalic = new System.Drawing.Font("Times New Roman", 10, System.Drawing.FontStyle.Italic, System.Drawing.GraphicsUnit.Point); // Create a Times New Roman Bold .NET font of 10 points System.Drawing.Font ttfFontBold = new System.Drawing.Font("Times New Roman", 10, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point); // Create a Times New Roman Bold .NET font of 10 points System.Drawing.Font ttfFontBoldItalic = new System.Drawing.Font("Times New Roman", 10, System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic, System.Drawing.GraphicsUnit.Point); // Create a Sim Sun .NET font of 10 points System.Drawing.Font ttfCJKFont = new System.Drawing.Font("SimSun", 10, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point); // Create the PDF fonts based on the .NET true type fonts PdfFont newTimesFont = document.AddFont(ttfFont); PdfFont newTimesFontItalic = document.AddFont(ttfFontItalic); PdfFont newTimesFontBold = document.AddFont(ttfFontBold); PdfFont newTimesFontBoldItalic = document.AddFont(ttfFontBoldItalic); // Create the embedded PDF fonts based on the .NET true type fonts PdfFont newTimesEmbeddedFont = document.AddFont(ttfFont, true); PdfFont newTimesItalicEmbeddedFont = document.AddFont(ttfFontItalic, true); PdfFont newTimesBoldEmbeddedFont = document.AddFont(ttfFontBold, true); PdfFont newTimesBoldItalicEmbeddedFont = document.AddFont(ttfFontBoldItalic, true); PdfFont cjkEmbeddedFont = document.AddFont(ttfCJKFont, true); // Create a standard Times New Roman Type 1 Font PdfFont stdTimesFont = document.AddFont(StdFontBaseFamily.TimesRoman); PdfFont stdTimesFontItalic = document.AddFont(StdFontBaseFamily.TimesItalic); PdfFont stdTimesFontBold = document.AddFont(StdFontBaseFamily.TimesBold); PdfFont stdTimesFontBoldItalic = document.AddFont(StdFontBaseFamily.TimesBoldItalic); // Create CJK standard Type 1 fonts PdfFont cjkJapaneseStandardFont = document.AddFont(StandardCJKFont.HeiseiKakuGothicW5); PdfFont cjkChineseTraditionalStandardFont = document.AddFont(StandardCJKFont.MonotypeHeiMedium); // Add text elements to the document TextElement trueTypeText = new TextElement(0, 10, "True Type Fonts Demo:", newTimesFontBold); AddElementResult addResult = firstPage.AddElement(trueTypeText); // Create the text element TextElement textElement1 = new TextElement(20, addResult.EndPageBounds.Bottom + 10, "Hello World !!!!", newTimesFont); // Add element to page. The result of adding the text element is stored into the addResult object // which can be used to get information about the rendered size in PDF page. addResult = firstPage.AddElement(textElement1); // Add another element 5 points below the text above. The bottom of the text above is taken from the AddElementResult object // set the font size newTimesFontItalic.Size = 15; TextElement textElement2 = new TextElement(20, addResult.EndPageBounds.Bottom + 5, "Hello World !!!!", newTimesFontItalic); textElement2.ForeColor = System.Drawing.Color.Green; addResult = firstPage.AddElement(textElement2); newTimesFontBoldItalic.Size = 20; TextElement textElement3 = new TextElement(20, addResult.EndPageBounds.Bottom + 5, "Hello World !!!!", newTimesFontBoldItalic); textElement3.ForeColor = System.Drawing.Color.Blue; addResult = firstPage.AddElement(textElement3); TextElement stdTypeText = new TextElement(0, addResult.EndPageBounds.Bottom + 10, "Standard PDF Fonts Demo:", newTimesFontBold); addResult = firstPage.AddElement(stdTypeText); TextElement textElement4 = new TextElement(20, addResult.EndPageBounds.Bottom + 10, "Hello World !!!!", stdTimesFont); addResult = firstPage.AddElement(textElement4); stdTimesFontItalic.Size = 15; TextElement textElement5 = new TextElement(20, addResult.EndPageBounds.Bottom + 5, "Hello World !!!!", stdTimesFontItalic); textElement5.ForeColor = System.Drawing.Color.Green; addResult = firstPage.AddElement(textElement5); stdTimesFontBoldItalic.Size = 20; TextElement textElement6 = new TextElement(20, addResult.EndPageBounds.Bottom + 5, "Hello World !!!!", stdTimesFontBoldItalic); textElement6.ForeColor = System.Drawing.Color.Blue; addResult = firstPage.AddElement(textElement6); // embedded true type fonts TextElement embeddedTtfText = new TextElement(0, addResult.EndPageBounds.Bottom + 10, "Embedded True Type Fonts Demo:", newTimesFontBold); addResult = firstPage.AddElement(embeddedTtfText); // russian text TextElement textElement8 = new TextElement(20, addResult.EndPageBounds.Bottom + 5, "Появление на свет!!", newTimesEmbeddedFont); addResult = firstPage.AddElement(textElement8); try { // get the PDF document bytes byte[] pdfBytes = document.Save(); // send the generated PDF document to client browser // get the object representing the HTTP response to browser HttpResponse httpResponse = HttpContext.Current.Response; // add the Content-Type and Content-Disposition HTTP headers httpResponse.AddHeader("Content-Type", "application/pdf"); httpResponse.AddHeader("Content-Disposition", String.Format("attachment; filename=TextAndFonts.pdf; size={0}", pdfBytes.Length.ToString())); // write the PDF document bytes as attachment to HTTP response httpResponse.BinaryWrite(pdfBytes); // Note: it is important to end the response, otherwise the ASP.NET // web page will render its content to PDF document stream httpResponse.End(); } finally { // close the PDF document to release the resources document.Close(); } }
public IElementRenderer CreateTextElementRender(TextElement element) { return(new TxtTextElement((TextElement)element)); }
public void ApplySuperscriptStyle(TextElement element) { element.SetResourceReference(FrameworkContentElement.StyleProperty, SuperscriptStyleKey); }
////Send executed command to output window. So, user will know what he executed //protected override void SendToOutputWindow(string command, string title)//13Dec2013 //{ // #region Get Active output Window // //////// Active output window /////// // OutputWindowContainer owc = (LifetimeService.Instance.Container.Resolve<IOutputWindowContainer>()) as OutputWindowContainer; // OutputWindow ow = owc.ActiveOutputWindow as OutputWindow; //get currently active window // #endregion // ow.AddMessage(command, title); //} #region Save HTML as PDF private void HTML2PDF(string htmlFilename, string outFilePath) //outFilePath is full path filename of PDF to be generated { bool addHeader = false, addFooter = false; bool createSelecteablePDF = true; //this.Cursor = Cursors.WaitCursor; //string outFilePath = Path.Combine(Application.StartupPath, "htmltopdf.pdf"); try { //set the license key //LicensingManager.LicenseKey = "put your license key here"; //create a PDF document Document document = new Document(); //optional settings for the PDF document like margins, compression level, //security options, viewer preferences, document information, etc document.CompressionLevel = CompressionLevel.NormalCompression; document.Margins = new Margins(10, 10, 0, 0); document.Security.CanPrint = true; document.Security.UserPassword = ""; document.DocumentInformation.Author = "HTML to PDF Converter"; document.ViewerPreferences.HideToolbar = false; //Add a first page to the document. The next pages will inherit the settings from this page PdfPage page = document.Pages.AddNewPage(PageSize.A4, new Margins(10, 10, 0, 0), PageOrientation.Portrait); // the code below can be used to create a page with default settings A4, document margins inherited, portrait orientation //PdfPage page = document.Pages.AddNewPage(); // add a font to the document that can be used for the texts elements PdfFont font = document.Fonts.Add(new Font(new FontFamily("Times New Roman"), 10, GraphicsUnit.Point)); // add header and footer before renderng the content //if (addHeader) // AddHtmlHeader(document); //if (addFooter) // AddHtmlFooter(document, font); // the result of adding an element to a PDF page AddElementResult addResult; // Get the specified location and size of the rendered content // A negative value for width and height means to auto determine // The auto determined width is the available width in the PDF page // and the auto determined height is the height necessary to render all the content float xLocation = 0;// float.Parse(textBoxXLocation.Text.Trim()); float yLocation = 0;// float.Parse(textBoxYLocation.Text.Trim()); float width = -1;// float.Parse(textBoxWidth.Text.Trim()); float height = -1;// float.Parse(textBoxHeight.Text.Trim()); if (createSelecteablePDF) { // convert HTML to PDF HtmlToPdfElement htmlToPdfElement; // convert a URL to PDF string urlToConvert = htmlFilename;// textBoxWebPageURL.Text.Trim(); htmlToPdfElement = new HtmlToPdfElement(xLocation, yLocation, width, height, urlToConvert); //optional settings for the HTML to PDF converter htmlToPdfElement.FitWidth = true;// cbFitWidth.Checked; htmlToPdfElement.EmbedFonts = false;// cbEmbedFonts.Checked; htmlToPdfElement.LiveUrlsEnabled = false;// cbLiveLinks.Checked; htmlToPdfElement.RightToLeftEnabled = false;// cbRTLEnabled.Checked; htmlToPdfElement.ScriptsEnabled = false;// cbScriptsEnabled.Checked; htmlToPdfElement.ActiveXEnabled = false;// cbActiveXEnabled.Checked; // add theHTML to PDF converter element to page addResult = page.AddElement(htmlToPdfElement); } else { HtmlToImageElement htmlToImageElement; // convert HTML to image and add image to PDF document // convert a URL to PDF string urlToConvert = htmlFilename;// textBoxWebPageURL.Text.Trim(); htmlToImageElement = new HtmlToImageElement(xLocation, yLocation, width, height, urlToConvert); //optional settings for the HTML to PDF converter htmlToImageElement.FitWidth = true;// cbFitWidth.Checked; htmlToImageElement.ScriptsEnabled = false;// cbScriptsEnabled.Checked; htmlToImageElement.ActiveXEnabled = false;// cbActiveXEnabled.Checked; addResult = page.AddElement(htmlToImageElement); } if (false)//cbAdditionalContent.Checked) { // The code below can be used add some other elements right under the conversion result // like texts or another HTML to PDF conversion // add a text element right under the HTML to PDF document PdfPage endPage = document.Pages[addResult.EndPageIndex]; TextElement nextTextElement = new TextElement(0, addResult.EndPageBounds.Bottom + 10, "Below there is another HTML to PDF Element", font); nextTextElement.ForeColor = Color.Green; addResult = endPage.AddElement(nextTextElement); // add another HTML to PDF converter element right under the text element endPage = document.Pages[addResult.EndPageIndex]; HtmlToPdfElement nextHtmlToPdfElement = new HtmlToPdfElement(0, addResult.EndPageBounds.Bottom + 10, "http://www.google.com"); addResult = endPage.AddElement(nextHtmlToPdfElement); } // save the PDF document to disk document.Save(outFilePath); } finally { //this.Cursor = Cursors.Arrow; } //DialogResult dr = MessageBox.Show("Open the saved file in an external viewer?", "Open Rendered File", MessageBoxButtons.YesNo, MessageBoxIcon.Information); //if (dr == DialogResult.Yes) //{ // try // { // System.Diagnostics.Process.Start(outFilePath); // } // catch (Exception ex) // { // MessageBox.Show(ex.Message); // return; // } //} }
private void AddHeader(PdfConverter pdfConverter, string headerText, string clientLogoFilename) { //enable header pdfConverter.PdfDocumentOptions.ShowHeader = true; // set the header height in points pdfConverter.PdfHeaderOptions.HeaderHeight = 40; var headerTextElement = new TextElement(0, 0, headerText, new System.Drawing.Font(new System.Drawing.FontFamily("Arial"), 10, System.Drawing.GraphicsUnit.Point)); headerTextElement.EmbedSysFont = true; headerTextElement.TextAlign = HorizontalTextAlign.Center; headerTextElement.VerticalTextAlign = VerticalTextAlign.Middle; pdfConverter.PdfHeaderOptions.AddElement(headerTextElement); // Add logo string imgFilepath = HttpContext.Current.Server.MapPath("/Content/Images/BSOHeaderLogo.png"); ImageElement headerLogoElement = new ImageElement(PdfPageSize.A4.Height - 180, 0, imgFilepath); pdfConverter.PdfHeaderOptions.AddElement(headerLogoElement); // Add client logo if (!String.IsNullOrEmpty(clientLogoFilename)) { string clientLogoFilepath = HttpContext.Current.Server.MapPath("/Content/Images/Client/" + clientLogoFilename); ImageElement clientLogoElement = new ImageElement(0, 0, clientLogoFilepath); pdfConverter.PdfHeaderOptions.AddElement(clientLogoElement); } }
public void ApplyTableHeaderStyle(TextElement element) { element.SetResourceReference(FrameworkContentElement.StyleProperty, TableHeaderStyleKey); }