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); } }
private void AddHeaderElements(PdfConverter pdfConverter) { // set the header HTML area HtmlToPdfElement headerHtml = new HtmlToPdfElement(0, 0, 0, pdfConverter.PdfHeaderOptions.HeaderHeight, "<b>HTML in Header</b>", null, 1024, 0); headerHtml.FitHeight = true; headerHtml.EmbedFonts = cbEmbedFonts.Checked; pdfConverter.PdfHeaderOptions.AddElement(headerHtml); if (cbDrawHeaderLine.Checked) { // set the header line float pdfPageWidth = 0; if (pdfConverter.PdfDocumentOptions.PdfPageOrientation == PdfPageOrientation.Portrait) pdfPageWidth = pdfConverter.PdfDocumentOptions.PdfPageSize.Width; else pdfPageWidth = pdfConverter.PdfDocumentOptions.PdfPageSize.Height; LineElement headerLine = new LineElement(0, pdfConverter.PdfHeaderOptions.HeaderHeight, pdfPageWidth - pdfConverter.PdfDocumentOptions.LeftMargin - pdfConverter.PdfDocumentOptions.RightMargin, pdfConverter.PdfHeaderOptions.HeaderHeight); headerLine.LineStyle.LineWidth = 0.5f; headerLine.ForeColor = Color.FromKnownColor((KnownColor)Enum.Parse(typeof(KnownColor), ddlHeaderLineColor.SelectedItem.ToString())); pdfConverter.PdfHeaderOptions.AddElement(headerLine); } }
public static void Draw(Context grw, LineElement line) { if (line.Foregraund != null) { grw.SetSourceRGB ( line.Foregraund.Red, line.Foregraund.Green, line.Foregraund.Blue); } grw.MoveTo( line.Start.GeometryX, line.Start.GeometryY); grw.LineTo( line.End.GeometryX, line.End.GeometryY); grw.Stroke(); }
/// <summary> /// Splits a line element and it's loads with an intermediate joint. /// </summary> /// <param name="line">The line element to split</param> /// <param name="joint">The joint, which should be located inside the line element</param> /// <param name="model">The Model object</param> /// <returns>The new line element, added to the model</returns> internal static void Split(LineElement line, IList <Joint> joints, Canguro.Model.Model model) { //float intersect = getIntersection(line, joint); //Commands.View.Selection. List <Utility.DistancedItem.dItem> dJoints = new List <Canguro.Utility.DistancedItem.dItem>(joints.Count); foreach (Joint j in joints) { if (line.I != j && line.J != j) { dJoints.Add(new Canguro.Utility.DistancedItem.dItem(getIntersection(line, j), j)); } } dJoints.Sort(Utility.DistancedItem.ReverseComparer.Instance); foreach (Utility.DistancedItem.dItem dItem in dJoints) { Split(line, (Joint)dItem.item, dItem.distance, model); } }
/// <summary> /// Draw the header elements /// </summary> /// <param name="htmlToPdfConverter">The HTML to PDF Converter object</param> /// <param name="drawHeaderLine">A flag indicating if a line should be drawn at the bottom of the header</param> private void DrawHeader(HtmlToPdfConverter htmlToPdfConverter, bool drawHeaderLine) { string headerHtmlString = System.IO.File.ReadAllText(Server.MapPath("~/DemoAppFiles/Input/HTML_Files/Header_HTML.html")); string headerBaseUrl = "http://www.evopdf.com/demo/DemoAppFiles/Input/HTML_Files/"; // Set the header height in points htmlToPdfConverter.PdfHeaderOptions.HeaderHeight = 60; // Set header background color htmlToPdfConverter.PdfHeaderOptions.HeaderBackColor = RgbColor.White; // Create a HTML element to be added in header HtmlToPdfElement headerHtml = new HtmlToPdfElement(headerHtmlString, headerBaseUrl); // Set the HTML element to fit the container height headerHtml.FitHeight = true; // Add HTML element to header htmlToPdfConverter.PdfHeaderOptions.AddElement(headerHtml); if (drawHeaderLine) { // Calculate the header width based on PDF page size and margins float headerWidth = htmlToPdfConverter.PdfDocumentOptions.PdfPageSize.Width - htmlToPdfConverter.PdfDocumentOptions.LeftMargin - htmlToPdfConverter.PdfDocumentOptions.RightMargin; // Calculate header height float headerHeight = htmlToPdfConverter.PdfHeaderOptions.HeaderHeight; // Create a line element for the bottom of the header LineElement headerLine = new LineElement(0, headerHeight - 1, headerWidth, headerHeight - 1); // Set line color headerLine.ForeColor = RgbColor.Gray; // Add line element to the bottom of the header htmlToPdfConverter.PdfHeaderOptions.AddElement(headerLine); } }
public static void LineAndLineString() { Application app = Utilities.ComApp; Point3d startPnt = app.Point3dZero(); Point3d endPnt = startPnt; startPnt.X = 10; LineElement oLine = app.CreateLineElement2(null, ref startPnt, ref endPnt);//直线 oLine.Color = 0; oLine.LineWeight = 2; app.ActiveModelReference.AddElement(oLine); Point3d[] pntArray = new Point3d[5]; pntArray[0] = app.Point3dZero(); pntArray[1] = app.Point3dFromXY(1, 2); pntArray[2] = app.Point3dFromXY(3, -2); pntArray[3] = app.Point3dFromXY(5, 2); pntArray[4] = app.Point3dFromXY(6, 0); oLine = app.CreateLineElement1(null, ref pntArray);//类似于多段线 oLine.Color = 1; oLine.LineWeight = 2; app.ActiveModelReference.AddElement(oLine); }
/// <summary> /// Calculates the intersection of the given Joint and LineElement and returns the /// float value corresponding to the proportion of the vector from defined by the line Joints. /// </summary> /// <param name="line">The LineElement to intersect</param> /// <param name="joint">The Joint to intersect with line</param> /// <returns>A float in [0, 1). If the joint is in the line, the proportion, 0 otherwise.</returns> public static float getIntersection(LineElement line, Joint joint) { Microsoft.DirectX.Vector3 i = line.I.Position; Microsoft.DirectX.Vector3 j = line.J.Position; Microsoft.DirectX.Vector3 pos = joint.Position; float ret, retx, rety, retz; float eps = 0.001f; //retx = (j.X != i.X) ? (pos.X - i.X) / (j.X - i.X) : (equals(pos.X, i.X, eps)) ? float.NaN : 0; //rety = (j.Y != i.Y) ? (pos.Y - i.Y) / (j.Y - i.Y) : (equals(pos.Y, i.Y, eps)) ? retx : 0; //retz = (j.Z != i.Z) ? (pos.Z - i.Z) / (j.Z - i.Z) : (equals(pos.Z, i.Z, eps)) ? rety : 0; //rety = (!float.IsNaN(rety)) ? rety : retz; //retx = (!float.IsNaN(retx)) ? retx : rety; //return (equals(retx, rety, eps) && equals(rety, retz, eps) && retx - eps > 0 && retx + eps < 1) ? retx : 0; Microsoft.DirectX.Vector3 xmp = joint.Position - line.I.Position; Microsoft.DirectX.Vector3 dir = line.J.Position - line.I.Position; ret = (Math.Abs(xmp.X) > Math.Abs(xmp.Y)) ? ((Math.Abs(xmp.X) > Math.Abs(xmp.Z)) ? xmp.X / dir.X : xmp.Z / dir.Z) : ((Math.Abs(xmp.Y) > Math.Abs(xmp.Z)) ? xmp.Y / dir.Y : xmp.Z / dir.Z); return((equals(ret * dir.X, xmp.X, eps) && equals(ret * dir.Y, xmp.Y, eps) && equals(ret * dir.Z, xmp.Z, eps)) ? ret : 0); }
/// <summary> /// Executes the command. /// Creates a series of connected Line Elements given at least 2 points. Each subsequent point given adds a new Line Element. /// </summary> /// <param name="services">CommandServices object to interact with the system</param> public override void Run(Canguro.Controller.CommandServices services) { LineElement line; Joint joint1, joint2; LineProps props = new StraightFrameProps(); List <LineElement> newLines = new List <LineElement>(); List <AreaElement> newAreas = new List <AreaElement>(); services.GetProperties(Culture.Get("addLineProps"), props); joint1 = services.GetJoint(newLines); services.TrackingService = LineTrackingService.Instance; services.TrackingService.SetPoint(joint1.Position); try { while ((joint2 = services.GetJoint(newLines)) != null) { if (joint2 != joint1) { services.Model.LineList.Add(line = new LineElement(props, joint1, joint2)); newLines.Add(line); joint1 = joint2; services.TrackingService.SetPoint(joint1.Position); // Para que se refleje el cambio inmediatamente services.Model.ChangeModel(); } } } catch (Canguro.Controller.CancelCommandException) { } if (newLines.Count == 0) { services.Model.Undo.Rollback(); } else { JoinCmd.Join(services.Model, new List <Joint>(), newLines, newAreas); } }
/// <summary> /// Draw the document header elements /// </summary> /// <param name="htmlToPdfConverter">The HTML to PDF Converter object</param> /// <param name="drawHeaderLine">A flag indicating if a line should be drawn at the bottom of the header</param> private void DrawHeader(HtmlToPdfConverter htmlToPdfConverter, bool drawHeaderLine) { string headerHtmlUrl = m_hostingEnvironment.ContentRootPath + "/wwwroot" + "/DemoAppFiles/Input/HTML_Files/Header_HTML.html"; // Set the header height in points htmlToPdfConverter.PdfHeaderOptions.HeaderHeight = 60; // Set header background color htmlToPdfConverter.PdfHeaderOptions.HeaderBackColor = Color.White; // Create a HTML element to be added in header HtmlToPdfElement headerHtml = new HtmlToPdfElement(headerHtmlUrl); // Set the HTML element to fit the container height headerHtml.FitHeight = true; // Add HTML element to header htmlToPdfConverter.PdfHeaderOptions.AddElement(headerHtml); if (drawHeaderLine) { // Calculate the header width based on PDF page size and margins float headerWidth = htmlToPdfConverter.PdfDocumentOptions.PdfPageSize.Width - htmlToPdfConverter.PdfDocumentOptions.LeftMargin - htmlToPdfConverter.PdfDocumentOptions.RightMargin; // Calculate header height float headerHeight = htmlToPdfConverter.PdfHeaderOptions.HeaderHeight; // Create a line element for the bottom of the header LineElement headerLine = new LineElement(0, headerHeight - 1, headerWidth, headerHeight - 1); // Set line color headerLine.ForeColor = Color.Gray; // Add line element to the bottom of the header htmlToPdfConverter.PdfHeaderOptions.AddElement(headerLine); } }
public static void ReadConfiguration(String Configfilename) { if (File.Exists(Configfilename)) { // get all lines from the String[] ConfigFileContent = File.ReadAllLines(Configfilename); Int32 LineNumber = 0; foreach (String LineElement in ConfigFileContent) { String[] TokenizedLine = LineElement.Split(new char[1] { ' ' }); LineNumber++; if (!LineElement.StartsWith("#")) { NetworkMonitoringHost NewElement = new NetworkMonitoringHost(); if (TokenizedLine.Length == 2) { NewElement.IPAdressOrHostname = TokenizedLine[0]; NewElement.Descriptor = TokenizedLine[1]; NetworkHosts.Add(NewElement); } else { throw (new Exception("NetworkMonitoring Host Configuration File - Error in line " + LineNumber)); } } } } else { throw (new Exception("NetworkMonitoring Host Configuration File not found!")); } }
public static void ReadConfiguration(String Configfilename) { if (File.Exists(Configfilename)) { // get all lines from the String[] ProxyConfigFileContent = File.ReadAllLines(Configfilename); Int32 LineNumber = 0; foreach (String LineElement in ProxyConfigFileContent) { String[] TokenizedLine = LineElement.Split(new char[1] { ' ' }); LineNumber++; if (!LineElement.StartsWith("#")) { ProxyElement NewElement = new ProxyElement(); if (TokenizedLine.Length == 2) { NewElement.ActivationURL = TokenizedLine[0]; NewElement.OutgoingMappingURL = TokenizedLine[1]; ProxyElements.Add(NewElement); } else { throw (new Exception("HTTPProxy Configuration File - Error in line " + LineNumber)); } } } } else { throw (new Exception("HTTPProxy Configuration File not found!")); } }
public float[,] GetForcesDiagram(AbstractCase ac, LineElement line, LineForceComponent component, int numPoints) { if (!model.HasResults) { return(null); } float[,] controlPoints = new float[numPoints, 2]; float[] controlPointsX = new float[1]; // requestXCtrlPts(load); for (int i = 0, bufi = 0; i < numPoints; i++) { controlPoints[i, 0] = i / (numPoints - 1f); // Adjust control points if ((bufi < controlPointsX.Length) && (controlPointsX[bufi] <= controlPoints[i, 0])) { controlPoints[i, 0] = controlPointsX[bufi++]; } controlPoints[i, 1] = 0f; // controlPoints[i, 0] * (fdJ - fdI); } float fI, fJ; getForcesDiagram(ac, line, component, controlPoints, out fI, out fJ); for (int i = 0, bufi = 0; i < numPoints; i++) { // Los valores en los nodos se encuentran volteados. Del lado izquierdo positivo // es arriba, mientras del lado derecho positivo es abajo, por lo que si se tienen // dos valores positivos se debería pintar una recta con pendiente negativa y si // se tienen dos negativos al revés. DeltaY = Y1 + Y2 (por el cambio de signo). controlPoints[i, 1] += controlPoints[i, 0] * (fI + fJ) - fI; } return(controlPoints); }
public static void ReadConfiguration(String Configfilename) { if (File.Exists(Configfilename)) { // get all lines from the String[] ConfigFileContent = File.ReadAllLines(Configfilename); Int32 LineNumber = 0; foreach (String LineElement in ConfigFileContent) { LineNumber++; if (!LineElement.StartsWith("#")) { SensorCheckIgnoreList.Add(LineElement); } } } else { // we simply don't ignore anything... } }
public static void LineAndLineString(string unparsed) { Bentley.Interop.MicroStationDGN.Application app = Bentley.MicroStation.InteropServices.Utilities.ComApp; Point3d startPnt = app.Point3dZero(); Point3d endPnt = startPnt; startPnt.X = 10; LineElement oLine = app.CreateLineElement2(null, ref startPnt, ref endPnt); oLine.Color = 0; oLine.LineWeight = 2; app.ActiveModelReference.AddElement(oLine); Point3d[] pntArray = new Point3d[5]; pntArray[0] = app.Point3dZero(); pntArray[1] = app.Point3dFromXY(1, 2); pntArray[2] = app.Point3dFromXY(3, -2); pntArray[3] = app.Point3dFromXY(5, 2); pntArray[4] = app.Point3dFromXY(6, 0); oLine = app.CreateLineElement1(null, ref pntArray); oLine.Color = 1; oLine.LineWeight = 2; app.ActiveModelReference.AddElement(oLine); }
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 Vector3[] GetCurve(LineElement l, AbstractCase ac, int numPoints, float deformationScale, float paintScaleFactorTranslation, out float[] xPos) { if (l == null) { xPos = null; return(null); } Vector3 iPos, jPos; iPos = new Vector3(model.Results.JointDisplacements[l.I.Id, 0], model.Results.JointDisplacements[l.I.Id, 1], model.Results.JointDisplacements[l.I.Id, 2]); iPos = deformationScale * paintScaleFactorTranslation * iPos + l.I.Position; jPos = new Vector3(model.Results.JointDisplacements[l.J.Id, 0], model.Results.JointDisplacements[l.J.Id, 1], model.Results.JointDisplacements[l.J.Id, 2]); jPos = deformationScale * paintScaleFactorTranslation * jPos + l.J.Position; float[,] local2Values = GetCurvedAxis(l, model.Results.ActiveCase.AbstractCase, Analysis.LineDeformationCalculator.DeformationAxis.Local2, numPoints); float[,] local3Values = GetCurvedAxis(l, model.Results.ActiveCase.AbstractCase, Analysis.LineDeformationCalculator.DeformationAxis.Local3, numPoints); int nVertices = local2Values.GetLength(0); Vector3[] curve = new Vector3[nVertices]; xPos = new float[nVertices]; for (int i = 0; i < nVertices; i++) { xPos[i] = local2Values[i, 0]; curve[i] = iPos + local2Values[i, 0] * (jPos - iPos) + local2Values[i, 1] * deformationScale * paintScaleFactorTranslation * l.LocalAxes[1] + local3Values[i, 1] * deformationScale * paintScaleFactorTranslation * l.LocalAxes[2]; } return(curve); }
private void addConcentratedForceDeflection(LineElement line, float lineLength, ConcentratedSpanLoad load, float[,] controlPoints, float dirComponent, float scale, float EI) { float a, b; float RA, P; float c1, c3; float x = 0.0f, deflection = 0.0f, angle = 0.0f; ConcentratedSpanLoad csl = (ConcentratedSpanLoad)load; a = csl.D * lineLength; b = lineLength - a; P = -csl.L; RA = P * (1f - a / lineLength); c1 = c3 = P * a * (lineLength - a) * (a - 2f * lineLength) / (6f * lineLength); // Flechas, angulos for (int i = 0; i < controlPoints.GetLength(0); i++) { x = controlPoints[i, 0] * lineLength; deflection = addConcentratedForceDeflection(load, x, lineLength, ref angle, a, b, RA, P, c1, c3) * scale / EI; controlPoints[i, 1] += (deflection * dirComponent); controlPoints[i, 2] += angle * dirComponent / EI; } }
public override void OnDblClick() { if (this._lineFeedback != null) { this._Point = null; IPolyline polyline = this._lineFeedback.Stop(); this._lineFeedback = null; if (!polyline.IsEmpty) { IElement lineElementClass = new LineElement() { Geometry = polyline }; (lineElementClass as ILineElement).Symbol = new SimpleLineSymbol(); NewElementOperation newElementOperation = new NewElementOperation() { ActiveView = this._context.ActiveView, ContainHook = this.GetActiveView(), Element = lineElementClass }; this._context.OperationStack.Do(newElementOperation); } } }
private IGeometry RotateLine(IGeometry geom, double newAngle, double oldAngle, bool isLine = true) { IPoint centerPoint; IElement elem; if (isLine) { IPointCollection ptCol = geom as IPointCollection; centerPoint = ptCol.get_Point(0); elem = new LineElement(); } else { centerPoint = new PointClass { X = (geom.Envelope.LowerLeft.X + geom.Envelope.LowerRight.X) / 2, Y = (geom.Envelope.LowerLeft.Y + geom.Envelope.UpperRight.Y) / 2 }; elem = new PolygonElement(); } elem.Geometry = geom; ITransform2D trans = elem as ITransform2D; double angle = newAngle - oldAngle; if ((newAngle - oldAngle) > Math.PI / 2) { angle += Math.PI; } if ((newAngle - oldAngle) < -1 * Math.PI / 2) { angle -= Math.PI; } trans.Rotate(centerPoint, angle); return elem.Geometry; }
public float[] GetCurvedPoint(LineElement l, AbstractCase ac, DeformationAxis component, float xPos) { if (!model.HasResults) { return(null); } /// controlPoints[i, 0]: x position on Beam, controlPoints[i, 1]: 'deflection' for x position, controlPoints[i,2]: deformation angle float[,] controlPoints = new float[1, 3]; controlPoints[0, 0] = xPos; controlPoints[0, 1] = 0f; controlPoints[0, 2] = 0.0f; getCurvedAxis(l, ac, component, controlPoints); // Copy to 1-dimensional array float[] ret = new float[3]; for (int i = 0; i < 3; i++) { ret[i] = controlPoints[0, i]; } return(ret); }
private void CreateResultElements() { IGeometryCollection geometryCollection = new GeometryBag() as IGeometryCollection; for (int i = 0; i < this._networkInfo.arrayList_1.Count; i++) { object missing = Type.Missing; IFeature feature = (IFeature)this._networkInfo.arrayList_1[i]; geometryCollection.AddGeometry(feature.ShapeCopy, ref missing, ref missing); } if (this._networkInfo.arrayList_1.Count > 0) { IRgbColor rgbColor = new RgbColor(); rgbColor.Red = (255); rgbColor.Green = (0); rgbColor.Blue = (255); IGraphicsContainer graphicsContainer = (IGraphicsContainer)m_iApp.ActiveView; for (int j = 0; j < geometryCollection.GeometryCount; j++) { ILineElement lineElement = new LineElement() as ILineElement; IElement element = (IElement)lineElement; element.Geometry = (geometryCollection.get_Geometry(j)); ILineElement arg_F5_0 = lineElement; ISimpleLineSymbol simpleLineSymbolClass = new SimpleLineSymbol(); simpleLineSymbolClass.Color = (rgbColor); simpleLineSymbolClass.Width = (10.0); simpleLineSymbolClass.Style = (0); arg_F5_0.Symbol = (simpleLineSymbolClass); graphicsContainer.AddElement(element, 0); } IEnvelope envelope = ((IGeometry)geometryCollection).Envelope; envelope.Expand(1.2, 1.2, true); m_iApp.ActiveView.Extent = (envelope); m_iApp.ActiveView.Refresh(); } }
private void btnConvert_Click(object sender, EventArgs e) { this.Cursor = Cursors.WaitCursor; try { PdfConverter pdfConverter = new PdfConverter(); // set the license key pdfConverter.LicenseKey = "B4mYiJubiJiInIaYiJuZhpmahpGRkZE="; // show the bookmarks when the document is opened pdfConverter.PdfViewerPreferences.PageMode = ViewerPageMode.UseOutlines; // set top and bottom page margins pdfConverter.PdfDocumentOptions.TopMargin = 5; pdfConverter.PdfDocumentOptions.BottomMargin = 5; // Inform the converter about the HTML elements for which we want the location in PDF // In this sample we want the location of the entries in the Table of Contents // The HTML ID of each entry in the table of contents is of form TOCEntry_{EntryIndex}_ID // the HTML ID of each target of a table of contents entry is of form TOCEntry_{EntryIndex}_Target_ID // Both toc entries and toc entries targets locations in PDF will be retrieved // and therefore the number of IDs is twice TOC entries number pdfConverter.HtmlElementsMappingOptions.HtmlElementSelectors = new string[2 * TOC_ENTRIES_COUNT]; int mappingsTableIdx = 0; for (int tocEntryIndex = 1; tocEntryIndex <= TOC_ENTRIES_COUNT; tocEntryIndex++) { // add the HTML ID of the TOC entry element to the list of elements for which we want the PDF location string tocEntryID = String.Format("#TOCEntry_{0}_ID", tocEntryIndex); pdfConverter.HtmlElementsMappingOptions.HtmlElementSelectors[mappingsTableIdx++] = tocEntryID; // add the HTML ID of the TOC entry target element to the list of elements for which we want the PDF location string tocEntryTargetID = String.Format("#TOCEntry_{0}_Target_ID", tocEntryIndex); pdfConverter.HtmlElementsMappingOptions.HtmlElementSelectors[mappingsTableIdx++] = tocEntryTargetID; } // set bookmark options pdfConverter.PdfBookmarkOptions.HtmlElementSelectors = new string[] { "A[class=\"bookmark\"]" }; // the URL of the HTML document to convert string htmlBookFilePath = System.IO.Path.Combine(Application.StartupPath, @"..\..\HtmlBook\Book.htm"); // call the converter and get a Document object from URL Document pdfDocument = pdfConverter.GetPdfDocumentObjectFromUrl(htmlBookFilePath); // Create a font used to write the page numbers in the table of contents PdfFont pageNumberFont = pdfDocument.Fonts.Add(new Font("Arial", PAGE_NUMBER_FONT_SIZE, FontStyle.Bold, GraphicsUnit.Point), true); // get the right edge of the table of contents where to position the page numbers float tocEntryMaxRight = 0.0f; for (int tocEntryIdx = 1; tocEntryIdx <= TOC_ENTRIES_COUNT; tocEntryIdx++) { string tocEntryID = String.Format("TOCEntry_{0}_ID", tocEntryIdx); HtmlElementMapping tocEntryLocation = pdfConverter.HtmlElementsMappingOptions.HtmlElementsMappingResult.GetElementByHtmlId(tocEntryID); if (tocEntryLocation.PdfRectangles[0].Rectangle.Right > tocEntryMaxRight) tocEntryMaxRight = tocEntryLocation.PdfRectangles[0].Rectangle.Right; } // Add page number for each entry in the table of contents for (int tocEntryIdx = 1; tocEntryIdx <= TOC_ENTRIES_COUNT; tocEntryIdx++) { string tocEntryID = String.Format("TOCEntry_{0}_ID", tocEntryIdx); string tocEntryTargetID = String.Format("TOCEntry_{0}_Target_ID", tocEntryIdx); HtmlElementMapping tocEntryLocation = pdfConverter.HtmlElementsMappingOptions.HtmlElementsMappingResult.GetElementByHtmlId(tocEntryID); HtmlElementMapping tocEntryTargetLocation = pdfConverter.HtmlElementsMappingOptions.HtmlElementsMappingResult.GetElementByHtmlId(tocEntryTargetID); // get the TOC entry page and bounds PdfPage tocEntryPdfPage = pdfDocument.Pages[tocEntryLocation.PdfRectangles[0].PageIndex]; RectangleF tocEntryPdfRectangle = tocEntryLocation.PdfRectangles[0].Rectangle; // get the page number of target where the TOC entry points int tocEntryTargetPageNumber = tocEntryTargetLocation.PdfRectangles[0].PageIndex + 1; // add dashed line from text entry to the page number LineElement lineToNumber = new LineElement(tocEntryPdfRectangle.Right + 5, tocEntryPdfRectangle.Y + tocEntryPdfRectangle.Height / 2, tocEntryMaxRight + 80, tocEntryPdfRectangle.Y + tocEntryPdfRectangle.Height / 2); lineToNumber.LineStyle.LineWidth = 1; lineToNumber.LineStyle.LineDashStyle = LineDashStyle.Dash; lineToNumber.ForeColor = Color.Green; tocEntryPdfPage.AddElement(lineToNumber); // create the page number text element to the right of the TOC entry TextElement pageNumberTextEement = new TextElement(tocEntryMaxRight + 85, tocEntryPdfRectangle.Y, -1, tocEntryPdfRectangle.Height, tocEntryTargetPageNumber.ToString(), pageNumberFont); pageNumberTextEement.TextAlign = HorizontalTextAlign.Left; pageNumberTextEement.VerticalTextAlign = VerticalTextAlign.Middle; pageNumberTextEement.ForeColor = Color.Blue; // add the page number to the right of the TOC entry tocEntryPdfPage.AddElement(pageNumberTextEement); } // save the PDF bytes in a file on disk string outFilePath = System.IO.Path.Combine(Application.StartupPath, "TOCAndBookmarks.pdf"); try { pdfDocument.Save(outFilePath); } finally { // close the Document to realease all the resources pdfDocument.Close(); } // open the generated PDF document in an external viewer DialogResult dr = MessageBox.Show("Open the rendered file in an external viewer?", "Open Rendered File", MessageBoxButtons.YesNo); if (dr == DialogResult.Yes) { System.Diagnostics.Process.Start(outFilePath); } } catch (Exception ex) { MessageBox.Show(ex.Message); return; } finally { this.Cursor = Cursors.Arrow; } }
/// <summary> /// A utility method to determine the length of a line element (in model space) /// </summary> /// <param name="line">the line element to determine the length of</param> /// <returns>a length</returns> public static double Length(LineElement line) { return(Distance(line.FirstPoint, line.SecondPoint)); }
private void DelVertexNode(IPoint pPnt) { try { IFeatureLayer pFeaturelayer = m_EngineEditLayers.TargetLayer; IActiveView pActiveView = m_activeView; IPoint pPoint = pPnt; if (pFeaturelayer.FeatureClass == null) { return; } //如果不是面状地物则退出 if (pFeaturelayer.FeatureClass.ShapeType != esriGeometryType.esriGeometryEnvelope && pFeaturelayer.FeatureClass.ShapeType != esriGeometryType.esriGeometryPolygon && pFeaturelayer.FeatureClass.ShapeType != esriGeometryType.esriGeometryLine && pFeaturelayer.FeatureClass.ShapeType != esriGeometryType.esriGeometryPolyline) { return; } IGeometry pGeo = null; IFeature pSelFeature = null; pSelFeature = EditVertexClass.GetSelectedFeature(pFeaturelayer); //是否有选中的几何体 if (pSelFeature == null) { return; } pGeo = pSelFeature.ShapeCopy; double pSrchDis = 0; double pHitDis = 0; pSrchDis = pActiveView.Extent.Width / 200; pPoint.Z = 0; int pIndex = 0; IElement pElement = null; IHitTest pHtTest = null; bool pBoolHitTest = false; IPoint pPtHit = null; IPointCollection pPointCol = null; IPolygon pPolygon = null; IPolyline pPyline = null; bool bRightZSide = true; int pInt = 0; m_EngineEditor.StartOperation(); //删除面状要素的节点 if (pFeaturelayer.FeatureClass.ShapeType == esriGeometryType.esriGeometryPolygon || pFeaturelayer.FeatureClass.ShapeType == esriGeometryType.esriGeometryEnvelope) { pElement = new PolygonElement(); pElement.Geometry = pSelFeature.Shape; IPolygon pPoly = null; pPoly = pElement.Geometry as IPolygon; pHtTest = pPoly as IHitTest; pBoolHitTest = pHtTest.HitTest(pPoint, pSrchDis, esriGeometryHitPartType.esriGeometryPartVertex, pPtHit, ref pHitDis, ref pInt, ref pIndex, ref bRightZSide); if (pBoolHitTest == false) { return; } EditVertexClass.pHitPnt = pPtHit; pPointCol = pSelFeature.ShapeCopy as IPointCollection; //如果多边形的节点只有3个则不能再删除了 if (pPointCol.PointCount <= 4) { MessageBox.Show("多边形的节点至少需要3个!", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } //顶点删除 pPointCol.RemovePoints(pIndex, 1); pPolygon = pPointCol as IPolygon; pPolygon.Close(); pSelFeature.Shape = pPolygon; pSelFeature.Store(); } //删除线状要素的节点 else if (pFeaturelayer.FeatureClass.ShapeType == esriGeometryType.esriGeometryPolyline || pFeaturelayer.FeatureClass.ShapeType == esriGeometryType.esriGeometryLine) { pElement = new LineElement(); pElement.Geometry = pSelFeature.Shape; IPolyline pPolyLine = default(IPolyline); pPolyLine = pElement.Geometry as IPolyline; pHtTest = pPolyLine as IHitTest; pBoolHitTest = pHtTest.HitTest(pPoint, pSrchDis, esriGeometryHitPartType.esriGeometryPartVertex, pPtHit, ref pHitDis, ref pInt, ref pIndex, ref bRightZSide); if (pBoolHitTest == false) { return; } EditVertexClass.pHitPnt = pPtHit; pPointCol = pSelFeature.ShapeCopy as IPointCollection; //如果Polyline节点只有2个则不能再删除了 if (pPointCol.PointCount <= 2) { MessageBox.Show("线的节点至少需要2个!", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } //顶点删除 pPointCol.RemovePoints(pIndex, 1); pPyline = pPointCol as IPolyline; pSelFeature.Shape = pPyline; pSelFeature.Store(); } //与选中点坐标相同的节点都删除 for (int i = 0; i <= pPointCol.PointCount - 1; i++) { if (i > pPointCol.PointCount - 1) { break; } if (pPointCol.get_Point(i).X == pPoint.X & pPointCol.get_Point(i).Y == pPoint.Y) { pPointCol.RemovePoints(i, 1); i = i - 1; } } //停止编辑 m_EngineEditor.StopOperation("DelVertexTool"); //显示顶点 EditVertexClass.ShowAllVertex(pFeaturelayer); m_activeView.Refresh(); } catch (Exception ex) { m_activeView.Refresh(); } }
public void AddGraphic(IScene iscene_0, IGeometry igeometry_0, ISymbol isymbol_0, bool bool_1, bool bool_2, string string_0) { if (!igeometry_0.IsEmpty) { IGraphicsLayer basicGraphicsLayer = iscene_0.BasicGraphicsLayer; IElement element = null; esriGeometryType geometryType = igeometry_0.GeometryType; switch (geometryType) { case esriGeometryType.esriGeometryPoint: { element = new MarkerElement(); IMarkerElement markerElement = element as IMarkerElement; if (isymbol_0 != null) { markerElement.Symbol = (isymbol_0 as IMarkerSymbol); } else { markerElement.Symbol = new SimpleMarkerSymbol(); } break; } case esriGeometryType.esriGeometryMultipoint: break; case esriGeometryType.esriGeometryPolyline: { element = new LineElement(); ILineElement lineElement = element as ILineElement; if (isymbol_0 != null) { lineElement.Symbol = (isymbol_0 as ILineSymbol); } else { lineElement.Symbol = new SimpleLineSymbol(); } break; } case esriGeometryType.esriGeometryPolygon: { element = new PolygonElement(); IFillShapeElement fillShapeElement = element as IFillShapeElement; if (isymbol_0 != null) { fillShapeElement.Symbol = (isymbol_0 as IFillSymbol); } else { fillShapeElement.Symbol = new SimpleFillSymbol(); } break; } default: if (geometryType == esriGeometryType.esriGeometryMultiPatch) { element = new MultiPatchElement(); IFillShapeElement fillShapeElement = element as IFillShapeElement; if (isymbol_0 != null) { fillShapeElement.Symbol = (isymbol_0 as IFillSymbol); } else { fillShapeElement.Symbol = new SimpleFillSymbol(); } } break; } if (element != null) { element.Geometry = igeometry_0; if (string_0.Length > 0) { IElementProperties elementProperties = element as IElementProperties; elementProperties.Name = string_0; } IGraphicsContainer3D graphicsContainer3D = basicGraphicsLayer as IGraphicsContainer3D; graphicsContainer3D.AddElement(element); IGraphicsSelection graphicsSelection = graphicsContainer3D as IGraphicsSelection; if (bool_2) { if (!bool_1) { graphicsSelection.UnselectAllElements(); } graphicsSelection.SelectElement(element); } iscene_0.SceneGraph.RefreshViewers(); } } }
LineElement TryCreateLineElement(LineElementData data) { var lineElement = new LineElement(data.Line, GetLineElementDrawData(data.Data)); return(lineElement); }
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(); } }
public ProjectElement Parse(String[] inputfiles) { ProjectElement PROJECT = new ProjectElement("new_project", 123323230); // Open file using (CoverageInfo info = JoinCoverageFiles(inputfiles)) { CoverageDS dataSet = info.BuildDataSet(); Dictionary <String, PackageElement> packages = new Dictionary <String, PackageElement>(); Dictionary <uint, FileElement> files = new Dictionary <uint, FileElement>(); // Namespaces DataTable namespacesTable = dataSet.Tables["NameSpaceTable"]; DataTable classesTable = dataSet.Tables["Class"]; DataTable filesTable = dataSet.Tables["SourceFileNames"]; CreateIndexPackages(PROJECT, namespacesTable, packages); CreateIndexFiles(filesTable, files); foreach (DataRow iclass in classesTable.Rows) { DataRow[] childRows = iclass.GetChildRows("Class_Method"); // Since it's one class per file (at least) declare // file here and add it to the class. uint fileid = 0; // uint classlocs = 0; uint covered_methods = 0; FileElement fe = null; foreach (DataRow imethod in childRows) { // Method starting line uint linenum = 0; // Get First Line in class DataRow[] childRows2 = imethod.GetChildRows("Method_Lines"); //if(childRows2.Length > 0) foreach (DataRow iline in childRows2) { LineElement le = null; uint coverage = iline.Field <uint>("Coverage"); if (linenum == 0) { fileid = iline.Field <uint>("SourceFileID"); string methodname = System.Security.SecurityElement.Escape((string)imethod["MethodName"]); linenum = iline.Field <uint>("LnStart"); le = new LineElement(linenum, "method", methodname, coverage); } else { linenum = iline.Field <uint>("LnStart"); le = new LineElement(linenum, "stmt", "", coverage); } // If the file doesn't exists in our report, we'll // just ignore this information if (files.ContainsKey(fileid)) { fe = files[fileid]; fe.AddLine(le); } } // Count how many methods covered we have if ((uint)imethod["LinesCovered"] > 0) { covered_methods++; } } uint totallines = (uint)iclass["LinesCovered"] + (uint)iclass["LinesNotCovered"] + (uint)iclass["LinesPartiallyCovered"]; uint complexity = 1; uint methods = (uint)childRows.Length; uint statements = totallines - methods; uint covered_statements = (uint)iclass["LinesCovered"] - covered_methods; uint conditionals = 0; uint covered_conditionals = 0; ClassElement ce = new ClassElement(System.Security.SecurityElement.Escape((string)iclass["ClassName"])); ce.Metrics = new ClassMetrics(complexity, statements, covered_statements, conditionals, covered_conditionals, methods, covered_methods); if (fe != null) { if (!fe.GetClasses().Contains(ce)) { fe.AddClass(ce); } if (packages.ContainsKey((string)iclass["NamespaceKeyName"])) { PackageElement pe = packages[(string)iclass["NamespaceKeyName"]]; if (!pe.GetFiles().Contains(fe)) { pe.AddFile(fe); } } } } } return(PROJECT); }
public override void OnMouseDown(int button, int shift, int x, int y, double mapX, double mapY) { DF2DApplication app = DF2DApplication.Application; m_ActiveView = app.Current2DMapControl.ActiveView; IGraphicsContainer pGC = m_ActiveView.GraphicsContainer; if (this.m_ActiveView.FocusMap.FeatureSelection != null) { this.m_ActiveView.FocusMap.ClearSelection(); } bool ready = false; if (app == null || app.Current2DMapControl == null) { return; } IGeometry pGeo = null; try { if (button == 1) { PointClass searchPoint = new PointClass(); searchPoint.PutCoords(mapX, mapY); pGeo = PublicFunction.DoBuffer(searchPoint, PublicFunction.ConvertPixelsToMapUnits(m_ActiveView, GlobalValue.System_Selection_Option().Tolerate)); if (pGeo == null) { return; } ready = true; if (ready) { bool haveone = false; foreach (LogicGroup lg in LogicDataStructureManage2D.Instance.RootLogicGroups) { foreach (MajorClass mc in lg.MajorClasses) { string[] arrFc2DId = mc.Fc2D.Split(';'); if (arrFc2DId == null) { continue; } IFeatureCursor pFeatureCursor = null; IFeature pFeature = null; foreach (string fc2DId in arrFc2DId) { DF2DFeatureClass dffc = DF2DFeatureClassManager.Instance.GetFeatureClassByID(fc2DId); if (dffc == null) { continue; } IFeatureClass fc = dffc.GetFeatureClass(); FacilityClass facc = dffc.GetFacilityClass(); if (facc.Name != "PipeNode") { continue; } IFeatureLayer fl = dffc.GetFeatureLayer(); if (fc == null || pGeo == null || fl == null) { continue; } if (!fl.Visible) { continue; } ISpatialFilter pSpatialFilter = new SpatialFilter(); pSpatialFilter.Geometry = pGeo; pSpatialFilter.SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects; pFeatureCursor = fc.Search(pSpatialFilter, false); if (pFeatureCursor == null) { continue; } pFeature = pFeatureCursor.NextFeature(); if (pFeature == null) { continue; } haveone = true; IGeometry pGeometry = pFeature.Shape as IGeometry; if (pGeometry.GeometryType == esriGeometryType.esriGeometryPoint) { IPoint pPoint = pGeometry as IPoint; if (this._bFinished) { this._bFinished = false; this._startFCID = fc.FeatureClassID.ToString(); this._startOid = pFeature.OID; AddCallout(pPoint, "起点"); app.Current2DMapControl.ActiveView.Refresh(); } else { if (this._startFCID == fc.FeatureClassID.ToString() && this._startOid == pFeature.OID) { XtraMessageBox.Show("您选中的是同一个管点设施。", "提示"); return; } this._bFinished = true; AddCallout(pPoint, "终点"); app.Current2DMapControl.ActiveView.Refresh(); if (this._startFCID != fc.FeatureClassID.ToString()) { XtraMessageBox.Show("您选中的不是同一类管点设施。", "提示"); return; } else { WaitForm.Start("正在分析...", "请稍后"); TopoClass2D tc = FacilityInfoService2D.GetTopoClassByFeatureClassID(fc.FeatureClassID.ToString()); if (tc == null) { return; } TopoNetwork net = tc.GetNetwork(); if (net == null) { WaitForm.Stop(); XtraMessageBox.Show("构建拓扑网络失败!", "提示"); return; } else { string startId = this._startFCID + "_" + this._startOid.ToString(); string endId = fc.FeatureClassID.ToString() + "_" + pFeature.OID.ToString(); List <string> path; double shortestLength = net.SPFA(startId, endId, out path); if ((shortestLength > 0.0 && shortestLength != double.MaxValue) || (path != null && path.Count > 0)) { List <IPoint> listPt = new List <IPoint>(); IPointCollection pointCol = new PolylineClass(); foreach (string nodeId in path) { int index = nodeId.LastIndexOf("_"); string fcID = nodeId.Substring(0, index); string oid = nodeId.Substring(index + 1, nodeId.Length - index - 1); DF2DFeatureClass dffcTemp = DF2DFeatureClassManager.Instance.GetFeatureClassByID(fcID); if (dffcTemp == null || dffcTemp.GetFeatureClass() == null) { continue; } if (dffcTemp.GetFacilityClassName() != "PipeNode") { continue; } IQueryFilter filter = new QueryFilter(); filter.WhereClause = "OBJECTID =" + oid; filter.SubFields = "OBJECTID ,SHAPE"; IFeature feature = null; IFeatureCursor cursor = null; try { cursor = dffcTemp.GetFeatureClass().Search(filter, false); while ((feature = cursor.NextFeature()) != null) { if (feature.Shape != null && feature.Shape is IGeometry) { IGeometry geo = feature.Shape as IGeometry; switch (geo.GeometryType) { case esriGeometryType.esriGeometryPoint: IPoint pt = geo as IPoint; //pt.Z = pt.Z + 1; listPt.Add(pt); pointCol.AddPoint(pt); break; } } } } catch (System.Exception ex) { } finally { if (cursor != null) { System.Runtime.InteropServices.Marshal.ReleaseComObject(cursor); cursor = null; } if (feature != null) { System.Runtime.InteropServices.Marshal.ReleaseComObject(feature); feature = null; } } } if (listPt.Count > 0) { IPolyline polyline = pointCol as IPolyline; ISimpleLineSymbol pLineSymbol = new SimpleLineSymbol(); pLineSymbol.Style = esriSimpleLineStyle.esriSLSSolid; pLineSymbol.Width = 5; pLineSymbol.Color = GetRGBColor(0, 230, 240); IElement elementL = new LineElement(); elementL.Geometry = polyline; ILineElement pLineElement = elementL as ILineElement; pLineElement.Symbol = pLineSymbol; pGC.AddElement(elementL, 0); ISimpleMarkerSymbol simpleMarkerSymbol = new SimpleMarkerSymbol(); simpleMarkerSymbol.Color = GetRGBColor(255, 0, 0); simpleMarkerSymbol.Outline = false; simpleMarkerSymbol.Size = 5; simpleMarkerSymbol.Style = esriSimpleMarkerStyle.esriSMSCircle; foreach (IPoint pt in listPt) { try { IMarkerElement pMarkerElement = new MarkerElementClass(); pMarkerElement.Symbol = simpleMarkerSymbol; IElement pElement = pMarkerElement as IElement; pElement.Geometry = pt; pGC.AddElement(pElement, 0); } catch (System.Exception ex) { continue; } } } app.Current2DMapControl.ActiveView.Refresh(); } else { WaitForm.Stop(); XtraMessageBox.Show("两点不连通!", "提示"); pGC.DeleteAllElements(); } } } } } } if (haveone) { break; } } if (haveone) { break; } } } } } catch (System.Exception ex) { XtraMessageBox.Show("分析出错!", "提示"); } finally { WaitForm.Stop(); } }
public void Update(Boolean useTransition) { LegendAreaWidth = 0; D3Data = new Data() { List = Data.Select(d => d as Object).ToList() }; CircleData = Data.SelectMany(l => l.DataPoints).Where(dp => dp.Item2 != null).ToList(); D3CircleData = new Data() { List = CircleData.Select(d => d as Object).ToList() }; if (LegendVisibility == Visibility.Visible) { LegendRectangleElement.Data = D3Data; LegendRectangleElement.Update(useTransition ? TransitionType.Opacity : TransitionType.None); LegendTextElement.Data = D3Data; LegendTextElement.Update(useTransition ? TransitionType.Opacity : TransitionType.None); LegendTextElement.ForceMeasure(); LegendAreaWidth = Math.Max(LegendTextElement.MaxActualWidth + Const.LegendPatchWidth + Const.LegendPatchSpace + Const.PaddingRight, Const.MinimumLegendWidth); LegendTitleElement.Width = LegendAreaWidth; LegendTitleElement.Text = LegendTitle; Canvas.SetTop(LegendTitleElement, LegendPatchYGetter(null, 0) - 30); } Canvas.SetLeft(LegendPanel, this.Width - LegendAreaWidth); if (HorizontalAxisVisibility == Visibility.Visible) { ChartAreaEndY = this.Height - Const.PaddingBottom - Const.HorizontalAxisHeight - Const.HorizontalAxisLabelHeight; } else { ChartAreaEndY = this.Height - Const.PaddingBottom; } if (LegendVisibility == Visibility.Visible) { ChartAreaEndX = this.Width - Const.PaddingRight - LegendAreaWidth; } else { ChartAreaEndX = this.Width - Const.PaddingRight; } HorizontalAxisLabelCanvasLeft = Const.PaddingLeft + Const.VerticalAxisWidth + Const.VerticalAxisLabelWidth; HorizontalAxisLabelCanvasTop = ChartAreaEndY + Const.HorizontalAxisHeight; HorizontalAxisLabelWidth = ChartAreaEndX - Const.PaddingLeft - Const.VerticalAxisWidth - Const.VerticalAxisLabelWidth; VerticalAxisCanvasLeft = Const.PaddingLeft + Const.VerticalAxisLabelWidth + Const.VerticalAxisWidth; VerticalAxisLabelCanvasLeft = Const.PaddingLeft + Const.VerticalAxisLabelWidth / 2 - (ChartAreaEndY - Const.PaddingTop) / 2; VerticalAxisLabelCanvasTop = Const.PaddingTop + (ChartAreaEndY - Const.PaddingTop) / 2; VerticalAxisLabelHeight = ChartAreaEndY - Const.PaddingTop; Double yMin = Math.Min(CircleData.Select(d => (Double)d.EnvelopeItem2).Min(), CircleData.Select(d => (Double)d.Item2).Min()), yMax = Math.Max(CircleData.Select(d => (Double)d.EnvelopeItem2).Max(), CircleData.Select(d => (Double)d.Item2).Max()); if (YStartsFromZero) { yMin = 0; } else if (yMin == yMax) { if (yMin == 0.0) { yMin = -1; yMax = 1; } else if (yMin < 0) { yMin *= 1.2; yMax *= 0.8; } else { yMin *= 0.8; yMax *= 1.2; } } else { if (yMin > 0) { yMin *= 0.9; } else { yMin *= 1.1; } } YScale = new Linear() { DomainStart = yMin, DomainEnd = yMax, RangeStart = ChartAreaEndY, RangeEnd = Const.PaddingTop }; YScale.Nice(); XScale = new Ordinal() { RangeStart = VerticalAxisCanvasLeft, RangeEnd = ChartAreaEndX + Const.PaddingLeft }; foreach (Object item1 in CircleData.OrderBy(dp => dp.Order) .Select(cd => cd.Item1).Distinct()) { XScale.Domain.Add(item1); } HandleLineElement.Data = D3Data; EnvelopeLineElement.Data = D3Data; LineElement.Data = D3Data; EnvelopeCircleElement.Data = D3CircleData; CircleElement.Data = D3CircleData; HorizontalAxis.Scale = XScale; Canvas.SetTop(HorizontalAxis, ChartAreaEndY); HorizontalAxis.Visibility = HorizontalAxisVisibility; Canvas.SetTop(HorizontalAxisTitleElement, HorizontalAxisLabelCanvasTop); Canvas.SetLeft(HorizontalAxisTitleElement, HorizontalAxisLabelCanvasLeft); HorizontalAxisTitleElement.Width = HorizontalAxisLabelWidth; HorizontalAxisTitleElement.Visibility = HorizontalAxisVisibility; HorizontalAxisTitleElement.Text = HorizontalAxisTitle; VerticalAxis.Scale = YScale; Canvas.SetLeft(VerticalAxis, VerticalAxisCanvasLeft); Canvas.SetTop(VerticalAxisTitleElement, VerticalAxisLabelCanvasTop); Canvas.SetLeft(VerticalAxisTitleElement, VerticalAxisLabelCanvasLeft); VerticalAxisTitleElement.Width = VerticalAxisLabelHeight; VerticalAxisTitleElement.Text = VerticalAxisTitle; LegendHandleRectangleElement.Data = D3Data; LegendHandleRectangleElement.Visibility = LegendVisibility; IndicatorTextElement.Data = D3CircleData; HandleLineElement.Update(useTransition ? TransitionType.Opacity : TransitionType.None); LineElement.Update(useTransition ? TransitionType.Opacity & TransitionType.Color: TransitionType.None); EnvelopeCircleElement.Update(useTransition ? TransitionType.Opacity : TransitionType.None); EnvelopeLineElement.Update(useTransition ? TransitionType.Opacity & TransitionType.Color : TransitionType.None); CircleElement.Update(TransitionType.None); // useTransition ? TransitionType.Opacity : TransitionType.None); LegendHandleRectangleElement.Update(TransitionType.None); IndicatorTextElement.Update(TransitionType.None); // useTransition ? TransitionType.Opacity : TransitionType.None); HorizontalAxis.Update(useTransition); VerticalAxis.Update(useTransition); }
/// <summary> /// 连接表 /// </summary> public IElement CreateJionTab(IActiveView pAV, IPoint Leftdown) { IGroupElement groupElementClass = new GroupElement() as IGroupElement; (groupElementClass as IElementProperties).Name = "接图表"; (groupElementClass as IElementProperties).Type = "接图表"; ILineSymbol lineSymbol = null; double num = this.height / 3; double num1 = this.width / 3; double num2 = 0.3; object missing = System.Type.Missing; IElement lineElementClass = new LineElement(); IElement element = new LineElement(); IElement lineElementClass1 = new LineElement(); IElement element1 = new LineElement(); IElement lineElementClass2 = new LineElement(); IPolyline polylineClass = new Polyline() as IPolyline; IPolyline polyline = new Polyline() as IPolyline; IPolyline polylineClass1 = new Polyline() as IPolyline; IPolyline polyline1 = new Polyline() as IPolyline; IPolyline polylineClass2 = new Polyline() as IPolyline; IPointCollection pointCollection = polylineClass as IPointCollection; IPoint pointClass = new ESRI.ArcGIS.Geometry.Point(); IPoint point = new ESRI.ArcGIS.Geometry.Point(); IPoint pointClass1 = new ESRI.ArcGIS.Geometry.Point(); IPoint point1 = new ESRI.ArcGIS.Geometry.Point(); try { lineSymbol = this.LineSymbol; (lineElementClass as ILineElement).Symbol = lineSymbol; (element as ILineElement).Symbol = lineSymbol; (lineElementClass1 as ILineElement).Symbol = lineSymbol; (element1 as ILineElement).Symbol = lineSymbol; (lineElementClass2 as ILineElement).Symbol = lineSymbol; point.PutCoords(Leftdown.X, Leftdown.Y + num2); pointClass.PutCoords(Leftdown.X, Leftdown.Y + num2 + this.height); pointClass1.PutCoords(Leftdown.X + this.width, Leftdown.Y + num2); point1.PutCoords(Leftdown.X + this.width, Leftdown.Y + num2 + this.height); pointCollection.AddPoint(pointClass, ref missing, ref missing); pointCollection.AddPoint(point, ref missing, ref missing); pointCollection.AddPoint(pointClass1, ref missing, ref missing); pointCollection.AddPoint(point1, ref missing, ref missing); pointCollection.AddPoint(pointClass, ref missing, ref missing); lineElementClass.Geometry = polylineClass; groupElementClass.AddElement(lineElementClass); IPoint pointClass2 = new ESRI.ArcGIS.Geometry.Point(); IPoint point2 = new ESRI.ArcGIS.Geometry.Point(); pointClass2.PutCoords(pointClass.X, pointClass.Y - num); point2.PutCoords(point1.X, point1.Y - num); pointCollection = polyline as IPointCollection; pointCollection.AddPoint(pointClass2, ref missing, ref missing); pointCollection.AddPoint(point2, ref missing, ref missing); element.Geometry = polyline; groupElementClass.AddElement(element); pointClass2.PutCoords(pointClass.X, pointClass.Y - num * 2); point2.PutCoords(point1.X, point1.Y - num * 2); pointCollection = polylineClass1 as IPointCollection; pointCollection.AddPoint(pointClass2, ref missing, ref missing); pointCollection.AddPoint(point2, ref missing, ref missing); lineElementClass1.Geometry = polylineClass1; groupElementClass.AddElement(lineElementClass1); pointClass2.PutCoords(pointClass.X + num1, pointClass.Y); point2.PutCoords(pointClass.X + num1, point.Y); pointCollection = polyline1 as IPointCollection; pointCollection.AddPoint(pointClass2, ref missing, ref missing); pointCollection.AddPoint(point2, ref missing, ref missing); element1.Geometry = polyline1; groupElementClass.AddElement(element1); pointClass2.PutCoords(pointClass.X + num1 * 2, pointClass.Y); point2.PutCoords(pointClass.X + num1 * 2, point.Y); pointCollection = polylineClass2 as IPointCollection; pointCollection.AddPoint(pointClass2, ref missing, ref missing); pointCollection.AddPoint(point2, ref missing, ref missing); lineElementClass2.Geometry = polylineClass2; groupElementClass.AddElement(lineElementClass2); IPolygon polygonClass = new Polygon() as IPolygon; IElement polygonElementClass = new PolygonElement(); IPolygonElement polygonElement = polygonElementClass as IPolygonElement; ISimpleFillSymbol simpleFillSymbolClass = new SimpleFillSymbol(); IFillShapeElement fillShapeElement = polygonElement as IFillShapeElement; IRgbColor rgbColorClass = new RgbColor() { Red = 0, Green = 0, Blue = 0 }; simpleFillSymbolClass.Outline = this.LineSymbol; simpleFillSymbolClass.Color = rgbColorClass; simpleFillSymbolClass.Style = esriSimpleFillStyle.esriSFSBackwardDiagonal; fillShapeElement.Symbol = simpleFillSymbolClass; pointCollection = polygonClass as IPointCollection; pointClass2.PutCoords(pointClass.X + num1, pointClass.Y - num); pointCollection.AddPoint(pointClass2, ref missing, ref missing); pointClass2.PutCoords(pointClass.X + num1 * 2, pointClass.Y - num); pointCollection.AddPoint(pointClass2, ref missing, ref missing); pointClass2.PutCoords(pointClass.X + num1 * 2, pointClass.Y - num * 2); pointCollection.AddPoint(pointClass2, ref missing, ref missing); pointClass2.PutCoords(pointClass.X + num1, pointClass.Y - num * 2); pointCollection.AddPoint(pointClass2, ref missing, ref missing); polygonClass.Close(); polygonElementClass.Geometry = polygonClass; groupElementClass.AddElement(polygonElementClass); IEnvelope envelope = polygonClass.Envelope; IEnvelope envelopeClass = new Envelope() as IEnvelope; this.m_pTextElementList.Add( this.CreateJionTabTextElement(pAV, this.Row1Col1Text, pointClass.X + num1 / 2, pointClass.Y - num / 2, envelope) as ITextElement); this.m_pTextElementAdd.Add(true); groupElementClass.AddElement(this.m_pTextElementList[0] as IElement); this.m_pTextElementList.Add( this.CreateJionTabTextElement(pAV, this.Row1Col2Text, pointClass.X + 1.5 * num1, pointClass.Y - 0.5 * num, envelope) as ITextElement); this.m_pTextElementAdd.Add(true); groupElementClass.AddElement(this.m_pTextElementList[1] as IElement); this.m_pTextElementList.Add( this.CreateJionTabTextElement(pAV, this.Row1Col3Text, pointClass.X + 2.5 * num1, pointClass.Y - 0.5 * num, envelope) as ITextElement); this.m_pTextElementAdd.Add(true); groupElementClass.AddElement(this.m_pTextElementList[2] as IElement); this.m_pTextElementList.Add( this.CreateJionTabTextElement(pAV, this.Row2Col1Text, pointClass.X + num1 / 2, pointClass.Y - 1.5 * num, envelope) as ITextElement); this.m_pTextElementAdd.Add(true); groupElementClass.AddElement(this.m_pTextElementList[3] as IElement); this.m_pTextElementList.Add(null); this.m_pTextElementAdd.Add(false); this.m_pTextElementList.Add( this.CreateJionTabTextElement(pAV, this.Row2Col3Text, pointClass.X + 2.5 * num1, pointClass.Y - 1.5 * num, envelope) as ITextElement); this.m_pTextElementAdd.Add(true); groupElementClass.AddElement(this.m_pTextElementList[5] as IElement); this.m_pTextElementList.Add( this.CreateJionTabTextElement(pAV, this.Row3Col1Text, pointClass.X + num1 / 2, pointClass.Y - 2.5 * num, envelope) as ITextElement); this.m_pTextElementAdd.Add(true); groupElementClass.AddElement(this.m_pTextElementList[6] as IElement); this.m_pTextElementList.Add( this.CreateJionTabTextElement(pAV, this.Row3Col2Text, pointClass.X + 1.5 * num1, pointClass.Y - 2.5 * num, envelope) as ITextElement); this.m_pTextElementAdd.Add(true); groupElementClass.AddElement(this.m_pTextElementList[7] as IElement); this.m_pTextElementList.Add( this.CreateJionTabTextElement(pAV, this.Row3Col3Text, pointClass.X + 2.5 * num1, pointClass.Y - 2.5 * num, envelope) as ITextElement); this.m_pTextElementAdd.Add(true); groupElementClass.AddElement(this.m_pTextElementList[8] as IElement); } catch (Exception exception) { } this.m_pGroupElement = groupElementClass as IElement; return(this.m_pGroupElement); }
private static void AddHeaderElements(PdfConverter pdfConverter) { // set the header HTML area var headerHtml = new HtmlToPdfElement("<img src='img/tdb_logo_l2.png' />", "http://www.thedrillbook.com/") { FitHeight = true }; pdfConverter.PdfHeaderOptions.AddElement(headerHtml); // set the header line float pdfPageWidth = pdfConverter.PdfDocumentOptions.PdfPageOrientation == PdfPageOrientation.Portrait ? pdfConverter.PdfDocumentOptions.PdfPageSize.Width : pdfConverter.PdfDocumentOptions.PdfPageSize.Height; var headerLine = new LineElement(0, pdfConverter.PdfHeaderOptions.HeaderHeight, pdfPageWidth - pdfConverter.PdfDocumentOptions.LeftMargin - pdfConverter.PdfDocumentOptions.RightMargin, pdfConverter.PdfHeaderOptions.HeaderHeight) { LineStyle = { LineWidth = 0.5f }, ForeColor = Color.Black }; pdfConverter.PdfHeaderOptions.AddElement(headerLine); }
private void btnConvert_Click(object sender, EventArgs e) { this.Cursor = Cursors.WaitCursor; try { 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; // set the header HTML area HtmlToPdfElement headerHtml = new HtmlToPdfElement(0, 0, 0, pdfConverter.PdfHeaderOptions.HeaderHeight, Path.Combine(Application.StartupPath, @"..\..\HeaderFooter\HeaderAndFooterHtml.htm"), 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, Path.Combine(Application.StartupPath, @"..\..\HeaderFooter\HeaderAndFooterHtml.htm"), 1024, 0); footerHtml.FitHeight = true; pdfConverter.PdfFooterOptions.AddElement(footerHtml); // save the PDF bytes in a file on disk string outFilePath = Path.Combine(Application.StartupPath, "HtmlInHeaderAndFooter.pdf"); if (!cbAlternateHeaderAndFooter.Checked) { // the header content is the same on all the PDF pages // the footer content is the same on all the PDF pages pdfConverter.SavePdfFromUrlToFile(textBoxURL1.Text, outFilePath); } 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(textBoxURL1.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); // add html to the header HtmlToPdfElement altHeaderHtml = new HtmlToPdfElement(0, 0, 0, pdfConverter.PdfHeaderOptions.HeaderHeight, Path.Combine(Application.StartupPath, @"..\..\HeaderFooter\HeaderAndFooterHtml2.htm"), 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, Path.Combine(Application.StartupPath, @"..\..\HeaderFooter\HeaderAndFooterHtml2.htm"), 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; } } // save the PDF document to a file on disk try { pdfDocument.Save(outFilePath); } finally { // close the Document to realease all the resources pdfDocument.Close(); } } DialogResult dr = MessageBox.Show("Open the rendered file in an external viewer?", "Open Rendered File", MessageBoxButtons.YesNo); if (dr == DialogResult.Yes) { System.Diagnostics.Process.Start(outFilePath); } } catch (Exception ex) { MessageBox.Show(ex.Message); return; } finally { this.Cursor = Cursors.Arrow; } }
private void Insert_Arrow(object sender, System.EventArgs e) { LineElement line = new LineElement(); line.EndArrow = true; InsertShape(line); }
protected void createPdfButton_Click(object sender, EventArgs e) { // Create a PDF 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="; // Add a PDF page to PDF document PdfPage pdfPage = pdfDocument.AddPage(); string headerHtmlUrl = Server.MapPath("~/DemoAppFiles/Input/HTML_Files/Header_HTML.html"); try { // Add the header to PDF document if (autoResizeHeaderRadioButton.Checked) { // Create the document header with a default height // It will be automatically resized in headerHtml_NavigationCompletedEvent handler pdfDocument.AddHeaderTemplate(50); // Create a HTML element to be added in header HtmlToPdfElement headerHtml = new HtmlToPdfElement(headerHtmlUrl); // Install a handler where to create the document header based on HTML element height headerHtml.NavigationCompletedEvent += new NavigationCompletedDelegate(headerHtml_NavigationCompletedEvent); // Add the HTML element to header // When the element is rendered in header by converter, the headerHtml_NavigationCompletedEvent handler // will be invoked and the header height will be automatically calculated pdfDocument.Header.AddElement(headerHtml); // Uninstall the handler headerHtml.NavigationCompletedEvent += new NavigationCompletedDelegate(headerHtml_NavigationCompletedEvent); } else { // Create the document header with a fixed height pdfDocument.AddHeaderTemplate(float.Parse(headerHeightTextBox.Text)); // Create a HTML to PDF element to be added in header HtmlToPdfElement headerHtml = new HtmlToPdfElement(headerHtmlUrl); // Set the HTML element to fit the container height headerHtml.FitHeight = true; // Add HTML element to fit the fixed header height pdfDocument.Header.AddElement(headerHtml); } // Draw a line at the header bottom if (drawHeaderLine) { float headerWidth = pdfDocument.Header.Width; float headerHeight = pdfDocument.Header.Height; // Create a line element for the bottom of the header LineElement headerLine = new LineElement(0, headerHeight - 1, headerWidth, headerHeight - 1); // Set line color headerLine.ForeColor = Color.Gray; // Add line element to the bottom of the header pdfDocument.Header.AddElement(headerLine); } // Create a HTML to PDF element to add to document HtmlToPdfElement htmlToPdfElement = new HtmlToPdfElement(urlTextBox.Text); // Optionally set a delay before conversion to allow asynchonous scripts to finish htmlToPdfElement.ConversionDelay = 2; // Add the HTML to PDF element to document pdfPage.AddElement(htmlToPdfElement); // Save the PDF document in a memory buffer byte[] outPdfBuffer = pdfDocument.Save(); // Send the PDF as response to browser // Set response content type Response.AddHeader("Content-Type", "application/pdf"); // Instruct the browser to open the PDF file as an attachment or inline Response.AddHeader("Content-Disposition", String.Format("attachment; filename=Auto_Resize_Header_Footer.pdf; size={0}", outPdfBuffer.Length.ToString())); // Write the PDF document buffer to HTTP response Response.BinaryWrite(outPdfBuffer); // End the HTTP response and stop the current page processing Response.End(); } finally { // Close the PDF document pdfDocument.Close(); } }
//public override void Run(Canguro.Controller.CommandServices services) //{ // objectCount = 0; // if (Clipboard.ContainsData("Canguro")) // { // Stream stream = (Stream)Clipboard.GetData("Canguro"); // Magnet magnet = services.GetPoint(Culture.Get("pasteCmdTitle")); // BinaryFormatter bformatter = new BinaryFormatter(); // Microsoft.DirectX.Vector3 pivot = (Microsoft.DirectX.Vector3)bformatter.Deserialize(stream); // Microsoft.DirectX.Vector3 v = magnet.SnapPosition - pivot; // List<Joint> newJoints = new List<Joint>(); // List<LineElement> newLines = new List<LineElement>(); // ItemList<Joint> jList = services.Model.JointList; // ItemList<LineElement> lList = services.Model.LineList; // Dictionary<uint, Joint> jSelection = new Dictionary<uint, Joint>(); // Joint nJoint; // LineElement nLine; // objectCount = (int) bformatter.Deserialize(stream); // for (int i = 0; i < objectCount; i++) // { // Element elem = (Element)bformatter.Deserialize(stream); // if (elem is Joint) // { // Joint j = (Joint)elem; // jList.Add(nJoint = new Joint(j.X + v.X, j.Y + v.Y, j.Z + v.Z)); // nJoint.Masses = j.Masses; // nJoint.DoF = j.DoF; // jSelection.Add(j.Id, nJoint); // newJoints.Add(nJoint); // CopyLoads(services.Model, j, nJoint); // } // if (elem is LineElement) // { // LineElement l = (LineElement)elem; // lList.Add(nLine = new LineElement(l.Properties)); // nLine.I = jSelection[l.I.Id]; // nLine.J = jSelection[l.J.Id]; // nLine.Angle = l.Angle; // newLines.Add(nLine); // CopyLoads(services.Model, l, nLine); // } // JoinCmd.Join(services.Model, newJoints, newLines); // } // } //} /// <summary> /// Executes the command. /// Pastes the Items in the Clpboard under the key Canguro, in the current Model. /// </summary> /// <param name="services">CommandServices object to interact with the system</param> public override void Run(Canguro.Controller.CommandServices services) { objectCount = 0; if (Clipboard.ContainsData("Canguro")) { object[] data = (object[])Clipboard.GetData("Canguro"); Dictionary <uint, Joint> joints = (Dictionary <uint, Joint>)data[0]; Dictionary <uint, Joint> jSelection = new Dictionary <uint, Joint>(); IList <LineElement> lines = (IList <LineElement>)data[1]; IList <AreaElement> areas = (IList <AreaElement>)data[2]; Microsoft.DirectX.Vector3 pivot = (Microsoft.DirectX.Vector3)data[3]; ItemList <Joint> jList = services.Model.JointList; ItemList <LineElement> lList = services.Model.LineList; ItemList <AreaElement> aList = services.Model.AreaList; Joint nJoint; LineElement nLine; AreaElement nArea; Magnet magnet = services.GetPoint(Culture.Get("pasteCmdTitle")); if (magnet == null) { objectCount = 0; } else { objectCount = joints.Count + lines.Count; Microsoft.DirectX.Vector3 v = magnet.SnapPosition - pivot; List <Joint> newJoints = new List <Joint>(); List <LineElement> newLines = new List <LineElement>(); List <AreaElement> newAreas = new List <AreaElement>(); Dictionary <string, Layer> layers = new Dictionary <string, Layer>(); foreach (Layer l in services.Model.Layers) { if (l != null) { layers.Add(l.Name, l); } } foreach (uint jid in joints.Keys) { Joint j = (joints[jid] == null) ? jList[jid] : joints[jid]; jList.Add(nJoint = new Joint(j.X + v.X, j.Y + v.Y, j.Z + v.Z)); nJoint.Masses = j.Masses; if (!layers.ContainsKey(j.Layer.Name)) { Layer lay = new Layer(j.Layer.Name); services.Model.Layers.Add(lay); layers.Add(lay.Name, lay); } nJoint.Layer = layers[j.Layer.Name]; nJoint.DoF = j.DoF; jSelection.Add(jid, nJoint); newJoints.Add(nJoint); CopyLoads(services.Model, j, nJoint); } foreach (LineElement l in lines) { if (!layers.ContainsKey(l.Layer.Name)) { Layer lay = new Layer(l.Layer.Name); services.Model.Layers.Add(lay); layers.Add(lay.Name, lay); } lList.Add(nLine = new LineElement(l, jSelection[l.I.Id], jSelection[l.J.Id])); nLine.Layer = layers[l.Layer.Name]; newLines.Add(nLine); CopyLoads(services.Model, l, nLine); } foreach (AreaElement a in areas) { if (!layers.ContainsKey(a.Layer.Name)) { Layer lay = new Layer(a.Layer.Name); services.Model.Layers.Add(lay); layers.Add(lay.Name, lay); } aList.Add(nArea = new AreaElement(a, jSelection[a.J1.Id], jSelection[a.J2.Id], jSelection[a.J3.Id], (a.J4 != null) ? jSelection[a.J4.Id] : null)); if (a.J4 != null) { nArea.J4 = jSelection[a.J4.Id]; } nArea.Layer = layers[a.Layer.Name]; newAreas.Add(nArea); CopyLoads(services.Model, a, nArea); } JoinCmd.Join(services.Model, newJoints, newLines, newAreas); } } }
protected void createPdfButton_Click(object sender, EventArgs e) { // Get the server IP and port String serverIP = textBoxServerIP.Text; uint serverPort = uint.Parse(textBoxServerPort.Text); // Create a PDF document Document pdfDocument = new Document(serverIP, serverPort); // Set optional service password if (textBoxServicePassword.Text.Length > 0) { pdfDocument.ServicePassword = textBoxServicePassword.Text; } // 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="; // Add a PDF page to PDF document PdfPage pdfPage = pdfDocument.AddPage(); // Create the document footer template pdfDocument.AddFooterTemplate(50); // ----- Add HTML with Page Numbering to Footer ----- // Create a variable HTML element with page numbering string htmlStringWithPageNumbers = htmlWithPageNumbersTextBox.Text; string baseUrl = baseUrlTextBox.Text; HtmlToPdfVariableElement footerHtmlWithPageNumbers = new HtmlToPdfVariableElement(htmlStringWithPageNumbers, baseUrl); // Set the HTML element to fit the container height footerHtmlWithPageNumbers.FitHeight = true; // Add variable HTML element with page numbering to footer pdfDocument.Footer.AddElement(footerHtmlWithPageNumbers); // Optionally draw a line at the top of the footer if (drawFooterLineCheckBox.Checked) { float footerWidth = pdfDocument.GetPage(0).PageSize.Width; // Create a line element for the top of the footer LineElement footerLine = new LineElement(0, 0, footerWidth, 0); // Set line color footerLine.ForeColor = RgbColor.Gray; // Add line element to the bottom of the footer pdfDocument.Footer.AddElement(footerLine); } // Create a HTML to PDF element to add to document HtmlToPdfElement htmlToPdfElement = new HtmlToPdfElement(0, 0, urlTextBox.Text); // Optionally set a delay before conversion to allow asynchonous scripts to finish htmlToPdfElement.ConversionDelay = 2; // Optionally add a space between footer and the page body // Leave this option not set for no spacing htmlToPdfElement.BottomSpacing = float.Parse(footerSpacingTextBox.Text); // Add the HTML to PDF element to document // This will raise the PrepareRenderPdfPageEvent event where the header and footer visibilit per page can be changed pdfPage.AddElement(htmlToPdfElement); // Save the PDF document in a memory buffer byte[] outPdfBuffer = pdfDocument.Save(); // Write the memory buffer in a PDF file// Send the PDF as response to browser // Set response content type Response.AddHeader("Content-Type", "application/pdf"); // Instruct the browser to open the PDF file as an attachment or inline Response.AddHeader("Content-Disposition", String.Format("attachment; filename=Page_Numbers_in_HTML.pdf; size={0}", outPdfBuffer.Length.ToString())); // Write the PDF document buffer to HTTP response Response.BinaryWrite(outPdfBuffer); // End the HTTP response and stop the current page processing Response.End(); }
protected void btnConvert_Click(object sender, EventArgs e) { PdfConverter pdfConverter = new PdfConverter(); // show the bookmarks when the document is opened pdfConverter.PdfViewerPreferences.PageMode = ViewerPageMode.UseOutlines; // set top and bottom page margins pdfConverter.PdfDocumentOptions.TopMargin = 5; pdfConverter.PdfDocumentOptions.BottomMargin = 5; // Inform the converter about the HTML elements for which we want the location in PDF // In this sample we want the location of the entries in the Table of Contents // The HTML ID of each entry in the table of contents is of form TOCEntry_{EntryIndex}_ID // the HTML ID of each target of a table of contents entry is of form TOCEntry_{EntryIndex}_Target_ID // Both toc entries and toc entries targets locations in PDF will be retrieved // and therefore the number of IDs is twice TOC entries number pdfConverter.HtmlElementsMappingOptions.HtmlElementSelectors = new string[2 * TOC_ENTRIES_COUNT]; int mappingsTableIdx = 0; for (int tocEntryIndex = 1; tocEntryIndex <= TOC_ENTRIES_COUNT; tocEntryIndex++) { // add the HTML ID of the TOC entry element to the list of elements for which we want the PDF location string tocEntryID = String.Format("#TOCEntry_{0}_ID", tocEntryIndex); pdfConverter.HtmlElementsMappingOptions.HtmlElementSelectors[mappingsTableIdx++] = tocEntryID; // add the HTML ID of the TOC entry target element to the list of elements for which we want the PDF location string tocEntryTargetID = String.Format("#TOCEntry_{0}_Target_ID", tocEntryIndex); pdfConverter.HtmlElementsMappingOptions.HtmlElementSelectors[mappingsTableIdx++] = tocEntryTargetID; } // set bookmark options pdfConverter.PdfBookmarkOptions.HtmlElementSelectors = new string[] { "A[class=\"bookmark\"]" }; // the URL of the HTML document to convert string thisPageURL = HttpContext.Current.Request.Url.AbsoluteUri; string htmlBookFilePath = thisPageURL.Substring(0, thisPageURL.LastIndexOf('/')) + "/HtmlBook/Book.htm"; // call the converter and get a Document object from URL Document pdfDocument = pdfConverter.GetPdfDocumentObjectFromUrl(htmlBookFilePath); // Create a font used to write the page numbers in the table of contents PdfFont pageNumberFont = pdfDocument.Fonts.Add(new Font("Arial", PAGE_NUMBER_FONT_SIZE, FontStyle.Bold, GraphicsUnit.Point), true); // get the right edge of the table of contents where to position the page numbers float tocEntryMaxRight = 0.0f; for (int tocEntryIdx = 1; tocEntryIdx <= TOC_ENTRIES_COUNT; tocEntryIdx++) { string tocEntryID = String.Format("TOCEntry_{0}_ID", tocEntryIdx); HtmlElementMapping tocEntryLocation = pdfConverter.HtmlElementsMappingOptions.HtmlElementsMappingResult.GetElementByHtmlId(tocEntryID); if (tocEntryLocation.PdfRectangles[0].Rectangle.Right > tocEntryMaxRight) tocEntryMaxRight = tocEntryLocation.PdfRectangles[0].Rectangle.Right; } // Add page number for each entry in the table of contents for (int tocEntryIdx = 1; tocEntryIdx <= TOC_ENTRIES_COUNT; tocEntryIdx++) { string tocEntryID = String.Format("TOCEntry_{0}_ID", tocEntryIdx); string tocEntryTargetID = String.Format("TOCEntry_{0}_Target_ID", tocEntryIdx); HtmlElementMapping tocEntryLocation = pdfConverter.HtmlElementsMappingOptions.HtmlElementsMappingResult.GetElementByHtmlId(tocEntryID); HtmlElementMapping tocEntryTargetLocation = pdfConverter.HtmlElementsMappingOptions.HtmlElementsMappingResult.GetElementByHtmlId(tocEntryTargetID); // get the TOC entry page and bounds PdfPage tocEntryPdfPage = pdfDocument.Pages[tocEntryLocation.PdfRectangles[0].PageIndex]; RectangleF tocEntryPdfRectangle = tocEntryLocation.PdfRectangles[0].Rectangle; // get the page number of target where the TOC entry points int tocEntryTargetPageNumber = tocEntryTargetLocation.PdfRectangles[0].PageIndex + 1; // add dashed line from text entry to the page number LineElement lineToNumber = new LineElement(tocEntryPdfRectangle.Right + 5, tocEntryPdfRectangle.Y + tocEntryPdfRectangle.Height / 2, tocEntryMaxRight + 80, tocEntryPdfRectangle.Y + tocEntryPdfRectangle.Height / 2); lineToNumber.LineStyle.LineWidth = 1; lineToNumber.LineStyle.LineDashStyle = LineDashStyle.Dash; lineToNumber.ForeColor = Color.Green; tocEntryPdfPage.AddElement(lineToNumber); // create the page number text element to the right of the TOC entry TextElement pageNumberTextEement = new TextElement(tocEntryMaxRight + 85, tocEntryPdfRectangle.Y, -1, tocEntryPdfRectangle.Height, tocEntryTargetPageNumber.ToString(), pageNumberFont); pageNumberTextEement.TextAlign = HorizontalTextAlign.Left; pageNumberTextEement.VerticalTextAlign = VerticalTextAlign.Middle; pageNumberTextEement.ForeColor = Color.Blue; // add the page number to the right of the TOC entry tocEntryPdfPage.AddElement(pageNumberTextEement); } 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=TableOfContents.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(); }
public LineController(LineElement element) { ParentElement = element; }
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 Text Elements to PDF document AddElementResult addTextResult = null; // The titles font used to mark various sections of the PDF document PdfFont titleFont = pdfDocument.AddFont(new Font("Times New Roman", 10, FontStyle.Bold, GraphicsUnit.Point)); titleFont.IsUnderline = true; // 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(); // Text Elements Using Fonts Installed in System // Add section title TextElement titleTextElement = new TextElement(xLocation, yLocation, "Text Elements Using Fonts Installed in System", titleFont); titleTextElement.ForeColor = Color.DarkGreen; addTextResult = pdfPage.AddElement(titleTextElement); yLocation = addTextResult.EndPageBounds.Bottom + 10; xLocation += 5; pdfPage = addTextResult.EndPdfPage; // Embed in PDF document a font with Normal style installed in system Font systemFontNormal = new Font("Times New Roman", 10, GraphicsUnit.Point); PdfFont embeddedSystemFontNormal = pdfDocument.AddFont(systemFontNormal); // Add a text element using a font with Normal style installed in system TextElement embeddedSystemFontNormalTextElement = new TextElement(xLocation, yLocation, "This text uses a font with Normal style installed in system", embeddedSystemFontNormal); addTextResult = pdfPage.AddElement(embeddedSystemFontNormalTextElement); yLocation = addTextResult.EndPageBounds.Bottom + 3; pdfPage = addTextResult.EndPdfPage; // Embed in PDF document a font with Bold style installed in system Font systemFontBold = new Font("Times New Roman", 10, FontStyle.Bold, GraphicsUnit.Point); PdfFont embeddedSystemFontBold = pdfDocument.AddFont(systemFontBold); // Add a text element using a font with Bold style installed in system TextElement embeddedSystemFontBoldTextElement = new TextElement(xLocation, yLocation, "This text uses a font with Bold style installed in system", embeddedSystemFontBold); addTextResult = pdfPage.AddElement(embeddedSystemFontBoldTextElement); yLocation = addTextResult.EndPageBounds.Bottom + 3; pdfPage = addTextResult.EndPdfPage; // Embed in PDF document a font with Italic style installed in system Font systemFontItalic = new Font("Times New Roman", 10, FontStyle.Italic, GraphicsUnit.Point); PdfFont embeddedSystemFontItalic = pdfDocument.AddFont(systemFontItalic); // Add a text element using a font with Italic style installed in system TextElement embeddedSystemFontItalicTextElement = new TextElement(xLocation, yLocation, "This text uses a font with Italic style installed in system", embeddedSystemFontItalic); addTextResult = pdfPage.AddElement(embeddedSystemFontItalicTextElement); yLocation = addTextResult.EndPageBounds.Bottom + 3; pdfPage = addTextResult.EndPdfPage; // Text Elements Using Fonts From Local Files // Add section title xLocation -= 5; yLocation += 10; titleTextElement = new TextElement(xLocation, yLocation, "Text Elements Using Fonts From Local Files", titleFont); titleTextElement.ForeColor = Color.Navy; addTextResult = pdfPage.AddElement(titleTextElement); yLocation = addTextResult.EndPageBounds.Bottom + 10; xLocation += 5; pdfPage = addTextResult.EndPdfPage; // Embed a True Type font from a local file in PDF document PdfFont localTrueTypeFont = pdfDocument.AddFont(m_hostingEnvironment.ContentRootPath + "/wwwroot" + "/DemoAppFiles/Input/Fonts/TrueType.ttf"); // Add a text element using the local True Type font to PDF document TextElement localFontTtfTextElement = new TextElement(xLocation, yLocation, "This text uses a True Type Font loaded from a local file", localTrueTypeFont); addTextResult = pdfPage.AddElement(localFontTtfTextElement); yLocation = addTextResult.EndPageBounds.Bottom; pdfPage = addTextResult.EndPdfPage; // Embed an OpenType font with TrueType Outlines in PDF document PdfFont localOpenTypeTrueTypeFont = pdfDocument.AddFont(m_hostingEnvironment.ContentRootPath + "/wwwroot" + "/DemoAppFiles/Input/Fonts/OpenTypeTrueType.otf"); // Add a text element using the local OpenType font with TrueType Outlines to PDF document TextElement localOpenTypeTrueTypeFontTextElement = new TextElement(xLocation, yLocation, "This text uses an Open Type Font with TrueType Outlines loaded from a local file", localOpenTypeTrueTypeFont); addTextResult = pdfPage.AddElement(localOpenTypeTrueTypeFontTextElement); yLocation = addTextResult.EndPageBounds.Bottom + 3; pdfPage = addTextResult.EndPdfPage; // Embed an OpenType font with PostScript Outlines in PDF document PdfFont localOpenTypePostScriptFont = pdfDocument.AddFont(m_hostingEnvironment.ContentRootPath + "/wwwroot" + "/DemoAppFiles/Input/Fonts/OpenTypePostScript.otf"); // Add a text element using the local OpenType font with PostScript Outlines to PDF document TextElement localOpenTypePostScriptFontTextElement = new TextElement(xLocation, yLocation, "This text uses an Open Type Font with PostScript Outlines loaded from a local file", localOpenTypePostScriptFont); addTextResult = pdfPage.AddElement(localOpenTypePostScriptFontTextElement); yLocation = addTextResult.EndPageBounds.Bottom + 3; pdfPage = addTextResult.EndPdfPage; // Text Elements Using Standard PDF Fonts // Add section title xLocation -= 5; yLocation += 10; titleTextElement = new TextElement(xLocation, yLocation, "Text Elements Using Standard PDF Fonts", titleFont); titleTextElement.ForeColor = Color.DarkGreen; addTextResult = pdfPage.AddElement(titleTextElement); yLocation = addTextResult.EndPageBounds.Bottom + 10; xLocation += 5; pdfPage = addTextResult.EndPdfPage; // Create a standard PDF font with Normal style PdfFont standardPdfFontNormal = pdfDocument.AddFont(StdFontBaseFamily.Helvetica); standardPdfFontNormal.Size = 10; // Add a text element using the standard PDF font with Normal style TextElement standardPdfFontNormalTextElement = new TextElement(xLocation, yLocation, "This text uses a standard PDF font with Normal style", standardPdfFontNormal); addTextResult = pdfPage.AddElement(standardPdfFontNormalTextElement); yLocation = addTextResult.EndPageBounds.Bottom + 3; pdfPage = addTextResult.EndPdfPage; // Create a standard PDF font with Bold style PdfFont standardPdfFontBold = pdfDocument.AddFont(StdFontBaseFamily.HelveticaBold); standardPdfFontBold.Size = 10; // Add a text element using the standard PDF font with Bold style TextElement standardPdfFontBoldTextElement = new TextElement(xLocation, yLocation, "This text uses a standard PDF font with Bold style", standardPdfFontBold); addTextResult = pdfPage.AddElement(standardPdfFontBoldTextElement); yLocation = addTextResult.EndPageBounds.Bottom + 3; pdfPage = addTextResult.EndPdfPage; // Create a standard PDF font with Italic style PdfFont standardPdfFontItalic = pdfDocument.AddFont(StdFontBaseFamily.HelveticaOblique); standardPdfFontItalic.Size = 10; // Add a text element using the standard PDF font with Italic style TextElement standardPdfFontItalicTextElement = new TextElement(xLocation, yLocation, "This text uses a standard PDF font with Italic style", standardPdfFontItalic); addTextResult = pdfPage.AddElement(standardPdfFontItalicTextElement); yLocation = addTextResult.EndPageBounds.Bottom + 3; pdfPage = addTextResult.EndPdfPage; // Text Elements with Vertical Text // Add section title xLocation -= 5; yLocation += 10; titleTextElement = new TextElement(xLocation, yLocation, "Vertical Text", titleFont); titleTextElement.ForeColor = Color.Navy; addTextResult = pdfPage.AddElement(titleTextElement); yLocation = addTextResult.EndPageBounds.Bottom + 10; xLocation += 5; pdfPage = addTextResult.EndPdfPage; // Add a top to bottom vertical text string topBottomText = "This is a Top to Bottom Vertical Text"; float topBottomTextWidth = embeddedSystemFontNormal.GetTextWidth(topBottomText); TextElement topBottomVerticalTextElement = new TextElement(0, 0, topBottomText, embeddedSystemFontNormal); topBottomVerticalTextElement.Translate(xLocation + 25, yLocation); topBottomVerticalTextElement.Rotate(90); pdfPage.AddElement(topBottomVerticalTextElement); // Add a bottom to top vertical text string bottomTopText = "This is a Bottom to Top Vertical Text"; float bottomTopTextWidth = embeddedSystemFontNormal.GetTextWidth(bottomTopText); TextElement bottomTopVerticalTextElement = new TextElement(0, 0, bottomTopText, embeddedSystemFontNormal); bottomTopVerticalTextElement.Translate(xLocation + 125, yLocation + bottomTopTextWidth); bottomTopVerticalTextElement.Rotate(-90); pdfPage.AddElement(bottomTopVerticalTextElement); yLocation += bottomTopTextWidth + 10; // Add a text element that flows freely in width and height string text = System.IO.File.ReadAllText(m_hostingEnvironment.ContentRootPath + "/wwwroot" + "/DemoAppFiles/Input/Text_Files/Text_File.txt"); // Add section title xLocation -= 5; yLocation += 10; titleTextElement = new TextElement(xLocation, yLocation, "Text Element that flows freely in width and height", titleFont); titleTextElement.ForeColor = Color.DarkGreen; addTextResult = pdfPage.AddElement(titleTextElement); yLocation = addTextResult.EndPageBounds.Bottom + 10; xLocation += 5; pdfPage = addTextResult.EndPdfPage; // Add the text element TextElement freeWidthAndHeightTextElement = new TextElement(xLocation, yLocation, text, embeddedSystemFontNormal); addTextResult = pdfPage.AddElement(freeWidthAndHeightTextElement); yLocation = addTextResult.EndPageBounds.Bottom + 3; pdfPage = addTextResult.EndPdfPage; // Add a text element with a given width that flows freely in height // Add section title xLocation -= 5; yLocation += 10; titleTextElement = new TextElement(xLocation, yLocation, "Text Element with a given width that flows freely in height", titleFont); titleTextElement.ForeColor = Color.Navy; addTextResult = pdfPage.AddElement(titleTextElement); yLocation = addTextResult.EndPageBounds.Bottom + 10; xLocation += 5; pdfPage = addTextResult.EndPdfPage; // Add the text element TextElement freeHeightTextElement = new TextElement(xLocation, yLocation, 400, text, embeddedSystemFontNormal); addTextResult = pdfPage.AddElement(freeHeightTextElement); yLocation = addTextResult.EndPageBounds.Bottom + 3; pdfPage = addTextResult.EndPdfPage; // Add a bounding rectangle for text element RectangleElement border = new RectangleElement(addTextResult.EndPageBounds.X, addTextResult.EndPageBounds.Y, addTextResult.EndPageBounds.Width, addTextResult.EndPageBounds.Height); pdfPage.AddElement(border); // Add a text element with a given width and height // Add section title xLocation -= 5; yLocation += 10; titleTextElement = new TextElement(xLocation, yLocation, "Text Element with a given width and height", titleFont); titleTextElement.ForeColor = Color.DarkGreen; addTextResult = pdfPage.AddElement(titleTextElement); yLocation = addTextResult.EndPageBounds.Bottom + 10; xLocation += 5; pdfPage = addTextResult.EndPdfPage; // Add the text element TextElement boundedTextElement = new TextElement(xLocation, yLocation, 400, 50, text, embeddedSystemFontNormal); addTextResult = pdfPage.AddElement(boundedTextElement); yLocation = addTextResult.EndPageBounds.Bottom + 3; pdfPage = addTextResult.EndPdfPage; // Add a bounding rectangle for text element border = new RectangleElement(addTextResult.EndPageBounds.X, addTextResult.EndPageBounds.Y, addTextResult.EndPageBounds.Width, addTextResult.EndPageBounds.Height); pdfPage.AddElement(border); // Add a text element that flows freely on next PDF page // Add section title xLocation -= 5; yLocation += 10; titleTextElement = new TextElement(xLocation, yLocation, "Text Element that flows freely on multiple PDF pages", titleFont); titleTextElement.ForeColor = Color.Navy; addTextResult = pdfPage.AddElement(titleTextElement); yLocation = addTextResult.EndPageBounds.Bottom + 10; xLocation += 5; pdfPage = addTextResult.EndPdfPage; // Add the text element string multiPageText = System.IO.File.ReadAllText(m_hostingEnvironment.ContentRootPath + "/wwwroot" + "/DemoAppFiles/Input/Text_Files/Large_Text_File.txt"); TextElement multiPageTextElement = new TextElement(xLocation, yLocation, 575, multiPageText, embeddedSystemFontNormal); multiPageTextElement.BackColor = Color.WhiteSmoke; addTextResult = pdfPage.AddElement(multiPageTextElement); yLocation = addTextResult.EndPageBounds.Bottom + 3; pdfPage = addTextResult.EndPdfPage; // Add a line at the bottom of the multipage text element LineElement bottomLine = new LineElement(addTextResult.EndPageBounds.X, addTextResult.EndPageBounds.Bottom + 1, addTextResult.EndPageBounds.X + addTextResult.EndPageBounds.Width, addTextResult.EndPageBounds.Bottom + 1); pdfPage.AddElement(bottomLine); // Add a text stamp to a PDF document // Create a .NET font Font timesNewRomanFont = new Font("Times New Roman", 24, GraphicsUnit.Point); // Create a PDF font PdfFont stampPdfFont = pdfDocument.AddFont(timesNewRomanFont, true); // The stamp text string stampText = String.Format("Text Stamp {0}", DateTime.Now.ToString("d")); // Measure the text float textWidth = stampPdfFont.GetTextWidth(stampText); foreach (PdfPage page in pdfDocument.Pages) { // Get the PDF page drawable area width and height float pdfPageWidth = page.ClientRectangle.Width; float pdfPageHeight = page.ClientRectangle.Height; // Calculate the PDF page diagonal float pdfPageDiagonal = (float)Math.Sqrt(pdfPageWidth * pdfPageWidth + pdfPageHeight * pdfPageHeight); // The text location on PDF page diagonal float xStampLocation = (pdfPageDiagonal - textWidth) / 2; // Create the stamp as a rotated text element TextElement stampTextElement = new TextElement(xStampLocation, 0, stampText, stampPdfFont); stampTextElement.ForeColor = Color.Coral; stampTextElement.Rotate((float)(Math.Atan(pdfPageHeight / pdfPageWidth) * (180 / Math.PI))); stampTextElement.Opacity = 75; // Add the stamp to PDF page page.AddElement(stampTextElement); } // 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 = "Text_Elements.pdf"; return(fileResult); } finally { // Close the PDF document pdfDocument.Close(); } }
/// <summary> обновление/добавление в базу _usersList информации о пользователе извлечённой из LineElement </summary> public void UpdateStatistic(LineElement line) { //чистим имя пользователя var nick = line.Nick; //обновляем базу пользователей if (_usersList.ContainsKey(nick)) { _usersList[nick]._moments.Add(line.Time); _usersList[nick].StringFatness.Add(line.LineLength); } else { var moment = new List<DateTime> {line.Time}; var fatness = new List<ushort> {line.LineLength}; var newNick = new List<string> {nick}; _usersList.Add(nick, new UserElement(newNick, moment, fatness)); } }
void AddLineElements(NormalizedSnapshotSpanCollection spans) { if (spans.Count == 0) { return; } var list = new List <StructureVisualizerData>(); var updated = new HashSet <StructureVisualizerData>(StructureVisualizerDataComparer.Instance); foreach (var span in spans) { list.Clear(); structureVisualizerServiceDataProvider.GetData(GetLineExtent(span), list); foreach (var info in list) { if (updated.Contains(info)) { continue; } updated.Add(info); var lineElement = FindLineElement(info); if (lineElement != null) { layer.RemoveAdornment(lineElement); Debug.Assert(!lineElements.Contains(lineElement)); } if (lineElement == null) { lineElement = new LineElement(info); } var lines = wpfTextView.TextViewLines.GetTextViewLinesIntersectingSpan(lineElement.Span); if (lines.Count == 0) { continue; } int lineStartIndex = 0; int lineEndIndex = lines.Count - 1; // Don't add a vertical line to the line containing the start or end block if (LineContainsSpan(info.Top, lines[lineStartIndex])) { lineStartIndex++; } if (LineContainsSpan(info.Bottom, lines[lineEndIndex])) { lineEndIndex--; } if (lineStartIndex > lineEndIndex) { continue; } double top = lines[lineStartIndex].Top; double bottom = lines[lineEndIndex].Bottom; if (bottom - top < 0.5) { continue; } double x = GetLineXPosition(info); var pen = GetPen(info.BlockKind); lineElement.Update(x, bottom, top, pen); bool added = layer.AddAdornment(AdornmentPositioningBehavior.TextRelative, lineElement.Span, null, lineElement, onRemovedDelegate); if (added) { lineElements.Add(lineElement); } } } }
void RecreateColumnLines() { delayRecreateColumnLinesCalled = false; if (wpfHexView.IsClosed) return; RemoveAllLines(); if (!enabled) return; if (wpfHexView.ViewportHeight == 0) return; var line = wpfHexView.HexViewLines.FirstVisibleLine; var top = wpfHexView.ViewportTop; var bottom = wpfHexView.ViewportBottom; foreach (var info in GetColumnPositions(line.BufferLine)) { var lineKind = GetColumnLineKind(info.Key); if (lineKind == HexColumnLineKind.None) continue; var props = editorFormatMap.GetProperties(classificationTypeNames[(int)info.Key]); var pen = GetPen(props, lineKind); var bounds = line.GetCharacterBounds(info.Value); var x = Math.Round(bounds.Left + bounds.Width / 2 - PEN_THICKNESS / 2) + 0.5; var lineElem = new LineElement(info.Key, x, top, bottom, pen); bool added = adornmentLayer.AddAdornment(VSTE.AdornmentPositioningBehavior.OwnerControlled, (HexBufferSpan?)null, null, lineElem, null); if (added) lineElements.Add(lineElem); } latestBufferLines = wpfHexView.BufferLines; }